"""
FrankenClaw — Config Loader

Reads API keys from a JSON keys file (default ~/.frankenclaw/keys.json,
override with `FRANKENCLAW_KEYS_PATH`). Manages FrankenClaw's own tool
settings at ~/.frankenclaw/config.json. Creates sane defaults on first run —
no setup wizard.

The keys file is a flat JSON object. Top-level keys are referenced by name
from the tools (e.g. "firecrawl" for web_scrape, "openrouter" for vision).
Some entries are objects with multiple fields (e.g. shopify needs
store/client_id/client_secret).

Legacy path back-compat: if neither FRANKENCLAW_KEYS_PATH nor
~/.frankenclaw/keys.json exists but the historical ~/.rockys-switch/keys.json
does, the latter is used with a stderr deprecation warning. Move the file
or set the env var when convenient.
"""

import json
import os
import sys
from pathlib import Path

CONFIG_DIR = Path.home() / ".frankenclaw"
CONFIG_PATH = CONFIG_DIR / "config.json"

_NEW_DEFAULT_KEYS = CONFIG_DIR / "keys.json"
_LEGACY_DEFAULT_KEYS = Path.home() / ".rockys-switch" / "keys.json"
_legacy_warning_emitted = False


def _resolve_keys_path() -> Path:
    """Resolve the keys file path with legacy fallback.

    Precedence: FRANKENCLAW_KEYS_PATH env var → ~/.frankenclaw/keys.json →
    ~/.rockys-switch/keys.json (legacy, warns once). If none exist, returns
    the new default so the FileNotFoundError points at the right place.
    """
    global _legacy_warning_emitted
    env_override = os.environ.get("FRANKENCLAW_KEYS_PATH")
    if env_override:
        return Path(env_override)
    if _NEW_DEFAULT_KEYS.exists():
        return _NEW_DEFAULT_KEYS
    if _LEGACY_DEFAULT_KEYS.exists():
        if not _legacy_warning_emitted:
            print(
                f"[frankenclaw] WARNING: reading keys from legacy path "
                f"{_LEGACY_DEFAULT_KEYS}. The default moved to "
                f"{_NEW_DEFAULT_KEYS} — move the file there (or set "
                f"FRANKENCLAW_KEYS_PATH={_LEGACY_DEFAULT_KEYS}) to silence "
                f"this warning.",
                file=sys.stderr,
            )
            _legacy_warning_emitted = True
        return _LEGACY_DEFAULT_KEYS
    return _NEW_DEFAULT_KEYS


# Back-compat: keep KEYS_PATH as a module-level name so any external caller
# that imported it keeps working. Resolved at import time, same as before;
# fallback logic applies. For long-running processes where the file might
# appear after import, call load_keys() / get_key() — they re-resolve.
KEYS_PATH = _resolve_keys_path()

DEFAULTS = {
    "searxng_url": "",
    "vision_model": "google/gemini-3.1-pro-preview",
    "vision_provider": "openrouter",
    "lightpanda_binary": "/usr/local/bin/lightpanda",
    "browser_engine": "default",
    "browser_executable": "",
    "browser_timeout": 30,
    "max_search_results": 10,
    "image_max_bytes": 1_048_576,
}


def load_keys() -> dict:
    """Load the JSON keys file. Re-resolves path on each call so a keys file
    appearing after import is picked up without restart."""
    path = _resolve_keys_path()
    if not path.exists():
        raise FileNotFoundError(
            f"Keys file not found at {path}. "
            f"Set FRANKENCLAW_KEYS_PATH to point at your keys.json, or create one "
            f"at the default location with your provider keys (firecrawl, openrouter, "
            f"shopify, etc.)."
        )
    with open(path) as f:
        return json.load(f)


def load_config() -> dict:
    """Load FrankenClaw config. Creates defaults on first run."""
    if not CONFIG_PATH.exists():
        CONFIG_DIR.mkdir(parents=True, exist_ok=True)
        with open(CONFIG_PATH, "w") as f:
            json.dump(DEFAULTS, f, indent=2)
        return dict(DEFAULTS)

    with open(CONFIG_PATH) as f:
        saved = json.load(f)

    # Merge with defaults — new keys get added, existing keys preserved
    merged = {**DEFAULTS, **saved}
    if merged != saved:
        with open(CONFIG_PATH, "w") as f:
            json.dump(merged, f, indent=2)

    return merged


def get_key(provider: str) -> str:
    """Get an API key for a specific provider from the keys file."""
    keys = load_keys()
    if provider not in keys:
        raise KeyError(
            f"No key for provider '{provider}' in {_resolve_keys_path()}. "
            f"Available: {list(keys.keys())}"
        )
    return keys[provider]
