"""Credentials store at ``~/.a2a/credentials.json``."""
from __future__ import annotations

import json
import os
from dataclasses import dataclass
from pathlib import Path

DEFAULT_API_URL = "https://api.a2acloud.io"


def _config_dir() -> Path:
    return Path.home() / ".a2a"


def _creds_path() -> Path:
    return _config_dir() / "credentials.json"


@dataclass
class Credentials:
    api_url: str
    token: str
    email: str


def save(api_url: str, token: str, email: str) -> Path:
    d = _config_dir()
    d.mkdir(parents=True, exist_ok=True)
    path = _creds_path()
    path.write_text(json.dumps({"api_url": api_url, "token": token, "email": email}))
    os.chmod(path, 0o600)
    return path


def load() -> Credentials | None:
    path = _creds_path()
    if not path.exists():
        return None
    try:
        data = json.loads(path.read_text())
    except (OSError, json.JSONDecodeError):
        return None
    return Credentials(
        api_url=data.get("api_url", DEFAULT_API_URL),
        token=data["token"],
        email=data.get("email", ""),
    )


def clear() -> bool:
    path = _creds_path()
    if path.exists():
        path.unlink()
        return True
    return False


def resolve_api_url(override: str | None = None) -> str:
    if override:
        return override
    env = os.environ.get("A2A_API_URL")
    if env:
        return env
    creds = load()
    if creds is not None:
        return creds.api_url
    return DEFAULT_API_URL
