"""Secure credential storage for AgentCost.

Stores API key in ~/.config/agentcost/credentials.json with
restricted file permissions (owner-only read/write).

Resolution order:
  1. Explicit api_key= parameter
  2. AGENTCOST_API_KEY environment variable
  3. Stored credentials from `agentcost login`
"""

import json
import os
import stat

CONFIG_DIR = os.path.join(os.path.expanduser("~"), ".config", "agentcost")
CREDENTIALS_FILE = os.path.join(CONFIG_DIR, "credentials.json")


def save(api_key: str, api_url: str = "https://agentmeter.com/api/v1") -> None:
    """Save credentials to disk with restricted permissions."""
    os.makedirs(CONFIG_DIR, mode=0o700, exist_ok=True)

    data = {"api_key": api_key, "api_url": api_url}

    # Write to a temp file first, then rename for atomicity
    tmp_path = CREDENTIALS_FILE + ".tmp"
    with open(tmp_path, "w") as f:
        json.dump(data, f, indent=2)

    # Set file permissions to owner-only (600)
    os.chmod(tmp_path, stat.S_IRUSR | stat.S_IWUSR)
    os.replace(tmp_path, CREDENTIALS_FILE)


def load() -> dict | None:
    """Load stored credentials. Returns None if not logged in."""
    if not os.path.exists(CREDENTIALS_FILE):
        return None

    try:
        with open(CREDENTIALS_FILE) as f:
            return json.load(f)
    except (json.JSONDecodeError, OSError):
        return None


def clear() -> bool:
    """Remove stored credentials. Returns True if file existed."""
    if os.path.exists(CREDENTIALS_FILE):
        os.remove(CREDENTIALS_FILE)
        return True
    return False


def resolve_api_key(explicit_key: str | None = None) -> str | None:
    """Resolve API key from all sources in priority order.

    1. Explicit key passed as argument
    2. AGENTCOST_API_KEY environment variable
    3. Stored credentials from `agentcost login`
    """
    if explicit_key:
        return explicit_key

    env_key = os.environ.get("AGENTCOST_API_KEY")
    if env_key:
        return env_key

    stored = load()
    if stored and stored.get("api_key"):
        return stored["api_key"]

    return None
