"""Local config file read/write."""
from __future__ import annotations

import json
from pathlib import Path

CONFIG_DIR = Path.home() / ".agentradar"
CONFIG_FILE = CONFIG_DIR / "config.json"
PRICING_FILE = CONFIG_DIR / "pricing.json"

DEFAULT_CONFIG = {
    "port": 7111,
    "open_browser": True,
    "token_budget": None,
    "timeout": 30,
    "theme": "dark",
    "patch": True,
}

DEFAULT_PRICING = {
    "gpt-4o": {"prompt": 0.000005, "completion": 0.000015},
    "gpt-4o-mini": {"prompt": 0.00000015, "completion": 0.0000006},
    "claude-sonnet-4-6": {"prompt": 0.000003, "completion": 0.000015},
    "claude-haiku-4-5": {"prompt": 0.00000025, "completion": 0.00000125},
    "gemini-1.5-pro": {"prompt": 0.000003, "completion": 0.000015},
    "gemini-1.5-flash": {"prompt": 0.00000035, "completion": 0.00000105},
    "deepseek-chat": {"prompt": 0.00000014, "completion": 0.00000028},
    "llama3": {"prompt": 0.0, "completion": 0.0},
}


def _ensure_dir():
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)


def load_config() -> dict:
    _ensure_dir()
    if CONFIG_FILE.exists():
        try:
            data = json.loads(CONFIG_FILE.read_text())
            return {**DEFAULT_CONFIG, **data}
        except Exception:
            pass
    return DEFAULT_CONFIG.copy()


def save_config(config: dict) -> None:
    _ensure_dir()
    current = load_config()
    current.update(config)
    CONFIG_FILE.write_text(json.dumps(current, indent=2))


def load_pricing() -> dict:
    _ensure_dir()
    if PRICING_FILE.exists():
        try:
            data = json.loads(PRICING_FILE.read_text())
            return {**DEFAULT_PRICING, **data}
        except Exception:
            pass
    return DEFAULT_PRICING.copy()


def save_pricing(pricing: dict) -> None:
    _ensure_dir()
    PRICING_FILE.write_text(json.dumps(pricing, indent=2))


def estimate_cost(tokens: dict, model: str | None = None) -> float:
    """Estimate cost in USD for a token usage dict."""
    if not model:
        return 0.0
    pricing = load_pricing()
    model_lower = model.lower()
    # Try exact match, then prefix match
    rates = pricing.get(model_lower)
    if not rates:
        for key in pricing:
            if key in model_lower or model_lower in key:
                rates = pricing[key]
                break
    if not rates:
        return 0.0
    prompt_cost = tokens.get("prompt", 0) * rates.get("prompt", 0)
    completion_cost = tokens.get("completion", 0) * rates.get("completion", 0)
    return round(prompt_cost + completion_cost, 6)
