from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path


@dataclass
class Config:
    wp_base_url: str
    wp_user: str | None
    wp_application_password: str | None
    llm_provider: str
    openai_api_key: str | None
    anthropic_api_key: str | None
    gemini_api_key: str | None
    llm_model: str | None
    llm_image_model: str
    repo_root: Path
    prompt_path: Path
    exports_dir: Path


def load_secrets(path: Path) -> dict[str, str]:
    raw = path.read_text(encoding="utf-8")
    cfg: dict[str, str] = {}

    for line in raw.splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        if line.rstrip() == "wordpress:":
            continue
        if "=" in line and ":" not in line.split("=", 1)[0]:
            k, _, v = line.partition("=")
            cfg[k.strip()] = v.strip().strip('"').strip("'")
            continue
        if ":" in line:
            k, _, v = line.partition(":")
            key = k.strip().lower()
            val = v.strip()
            if key in ("id", "user", "login"):
                cfg.setdefault("WP_USER", val)
            elif "application" in key.replace(" ", "") or "appllication" in key:
                cfg.setdefault("WP_APPLICATION_PASSWORD", val)
            elif key in ("wp_base_url", "base_url", "url"):
                cfg.setdefault("WP_BASE_URL", val.rstrip("/"))

    if "WP_APPLICATION_PASSWORD" in cfg:
        cfg["WP_APPLICATION_PASSWORD"] = cfg["WP_APPLICATION_PASSWORD"].replace(" ", "")
    return cfg


def default_model(provider: str) -> str:
    return {
        "openai": "gpt-4o",
        "anthropic": "claude-sonnet-4-20250514",
        "gemini": "gemini-2.0-flash",
    }.get(provider, "gpt-4o")


def load_config(
    env_path: Path | None = None,
    repo_root: Path | None = None,
) -> Config:
    root = repo_root or Path(__file__).resolve().parents[2]
    env = env_path or root / ".secrets" / ".env"
    if not env.is_file():
        raise FileNotFoundError(f"Fichier introuvable : {env}")

    raw = load_secrets(env)
    provider = (raw.get("LLM_PROVIDER") or "openai").strip().lower()

    return Config(
        wp_base_url=(raw.get("WP_BASE_URL") or "https://www.arnaud-merigeau.fr").rstrip("/"),
        wp_user=raw.get("WP_USER") or raw.get("WP_USERNAME"),
        wp_application_password=raw.get("WP_APPLICATION_PASSWORD"),
        llm_provider=provider,
        openai_api_key=raw.get("OPENAI_API_KEY"),
        anthropic_api_key=raw.get("ANTHROPIC_API_KEY"),
        gemini_api_key=raw.get("GEMINI_API_KEY") or raw.get("GOOGLE_API_KEY"),
        llm_model=(raw.get("LLM_MODEL") or "").strip() or None,
        llm_image_model=(raw.get("LLM_IMAGE_MODEL") or "dall-e-3").strip(),
        repo_root=root,
        prompt_path=root / "prompts" / "redaction-articles-blog-prestashop-wordpress.txt",
        exports_dir=root / "exports" / "article-studio",
    )


def api_key_for_provider(cfg: Config) -> str:
    keys = {
        "openai": cfg.openai_api_key,
        "anthropic": cfg.anthropic_api_key,
        "gemini": cfg.gemini_api_key,
    }
    key = keys.get(cfg.llm_provider)
    if not key:
        raise ValueError(
            f"Clé API manquante pour le fournisseur « {cfg.llm_provider} » "
            f"(voir .secrets/.env.example)."
        )
    return key
