"""
AgniPod SDK — Configuration
=============================

Centralised defaults and credential resolution.

Key resolution order (first non-empty wins):
  1. Explicit ``api_key=`` passed to ``AgniPod()``
  2. ``AGNIPOD_API_KEY`` environment variable
  3. Saved credentials file (``~/.agnipod/credentials``)
"""

import json
import os
from pathlib import Path

# ── Defaults ─────────────────────────────────────────────────────────────

BASE_URL = "https://api.agnipod.com"

ENV_API_KEY = "AGNIPOD_API_KEY"

DEFAULT_TIMEOUT = 120            # seconds
DEFAULT_STREAM_TIMEOUT = 300     # seconds (longer for streaming)
DEFAULT_MAX_RETRIES = 2
RETRY_BACKOFF_FACTOR = 0.5       # seconds
RETRY_STATUS_CODES = {429, 500, 502, 503, 504}

VERSION = "0.2.0"
USER_AGENT = f"agnipod-python/{VERSION}"

# ── Credentials file ────────────────────────────────────────────────────

CREDENTIALS_DIR = Path.home() / ".agnipod"
CREDENTIALS_FILE = CREDENTIALS_DIR / "credentials"


def _sanitize_key(key: str | None) -> str | None:
    """Strip whitespace and surrounding quotes from an API key."""
    if not key:
        return None
    key = key.strip().strip('"').strip("'").strip()
    return key if key else None


def _read_saved_key() -> str | None:
    """Read API key from ``~/.agnipod/credentials`` (JSON or plain text)."""
    try:
        if not CREDENTIALS_FILE.is_file():
            return None
        text = CREDENTIALS_FILE.read_text().strip()
        if not text:
            return None
        # Try JSON first  {"api_key": "agni_..."}
        if text.startswith("{"):
            data = json.loads(text)
            return _sanitize_key(data.get("api_key"))
        # Fallback: plain key string
        cleaned = _sanitize_key(text)
        return cleaned if cleaned and cleaned.startswith("agni_") else None
    except Exception:
        return None


def save_api_key(api_key: str) -> Path:
    """Persist an API key to ``~/.agnipod/credentials``.

    Returns the path of the credentials file.
    """
    CREDENTIALS_DIR.mkdir(parents=True, exist_ok=True)
    CREDENTIALS_FILE.write_text(json.dumps({"api_key": api_key}, indent=2) + "\n")
    # Restrict permissions (owner-only)
    try:
        CREDENTIALS_FILE.chmod(0o600)
    except OSError:
        pass
    return CREDENTIALS_FILE


def clear_saved_key() -> bool:
    """Remove the saved credentials file. Returns True if it existed."""
    try:
        if CREDENTIALS_FILE.is_file():
            CREDENTIALS_FILE.unlink()
            return True
    except OSError:
        pass
    return False


# ── Resolution helpers ───────────────────────────────────────────────────

def resolve_api_key(api_key: str | None = None) -> str | None:
    """Return the first non-empty key: explicit → env var → saved file.

    Sanitizes the key by stripping whitespace and surrounding quotes
    to prevent "Invalid API key format" errors.
    """
    raw = api_key or os.environ.get(ENV_API_KEY) or _read_saved_key()
    return _sanitize_key(raw)


def get_base_url() -> str:
    """Return the fixed API base URL."""
    return BASE_URL
