"""Local configuration and state management for b2alpha CLI."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

B2A_DIR = Path.home() / ".b2alpha"
AUTH_FILE = B2A_DIR / "auth.json"
PROFILE_FILE = B2A_DIR / "profile.json"
KEYS_DIR = B2A_DIR / "keys"

# Must be set to your Supabase project values
SUPABASE_URL = "https://lmrtjclgcaxzvghyosct.supabase.co"
SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImxtcnRqY2xnY2F4enZnaHlvc2N0Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzEzNDEwNzksImV4cCI6MjA4NjkxNzA3OX0.zwk92t0SnxkULjNY2XlbnW4_e9RoEzOyB9rdRe3AmWs"


def _ensure_dirs() -> None:
    B2A_DIR.mkdir(parents=True, exist_ok=True)
    KEYS_DIR.mkdir(parents=True, exist_ok=True)


def load_json(path: Path) -> dict[str, Any]:
    if not path.exists():
        return {}
    return json.loads(path.read_text())


def save_json(path: Path, data: dict[str, Any]) -> None:
    _ensure_dirs()
    path.write_text(json.dumps(data, indent=2) + "\n")


def load_env_config() -> tuple[str, str]:
    """Load Supabase URL and anon key, preferring env vars over defaults."""
    import os

    url = os.environ.get("B2A_SUPABASE_URL", SUPABASE_URL)
    key = os.environ.get("B2A_SUPABASE_ANON_KEY", SUPABASE_ANON_KEY)
    return url, key


def get_access_token() -> str | None:
    auth = load_json(AUTH_FILE)
    return auth.get("access_token")


def get_active_did() -> str | None:
    profile = load_json(PROFILE_FILE)
    return profile.get("did")


def get_profile() -> dict[str, Any]:
    return load_json(PROFILE_FILE)
