"""Configuration loading and discovery for transduck."""

import os
from dataclasses import dataclass
from pathlib import Path

import yaml


CONFIG_FILENAME = "transduck.yaml"


@dataclass(frozen=True)
class TransduckConfig:
    project_name: str
    project_context: str
    source_lang: str
    target_langs: list[str]
    storage_path: Path
    provider: str
    api_key_env: str
    token_env: str
    backend_model: str
    backend_timeout: int
    backend_max_retries: int
    shared_url: str | None
    read_only: bool


def _find_config() -> Path:
    env_path = os.environ.get("TRANSDUCK_CONFIG")
    if env_path:
        p = Path(env_path)
        if p.is_file():
            return p
        raise FileNotFoundError(f"TRANSDUCK_CONFIG points to {env_path} which does not exist")

    current = Path.cwd()
    while True:
        candidate = current / CONFIG_FILENAME
        if candidate.is_file():
            return candidate
        parent = current.parent
        if parent == current:
            break
        current = parent

    raise FileNotFoundError(
        f"Could not find {CONFIG_FILENAME}. Run 'transduck init' or set TRANSDUCK_CONFIG."
    )


def _load_dotenv() -> None:
    try:
        from dotenv import load_dotenv, find_dotenv
        load_dotenv(find_dotenv(usecwd=True))
    except ImportError:
        pass


def load_config(path: Path | None = None) -> TransduckConfig:
    _load_dotenv()
    if path is None:
        path = _find_config()
    path = Path(path)

    with open(path) as f:
        raw = yaml.safe_load(f)

    config_dir = path.parent
    storage_rel = raw["storage"]["path"]
    storage_path = (config_dir / storage_rel).resolve()

    backend = raw.get("backend", {})
    provider = backend.get("provider", "openai")
    api_key_env = backend.get("api_key_env", "OPENAI_API_KEY")
    token_env = backend.get("token_env", "CLAUDE_CODE_OAUTH_TOKEN")
    backend_model = backend.get("model", "gpt-4.1-mini")
    backend_timeout = backend.get("timeout_seconds", 10)
    backend_max_retries = backend.get("max_retries", 2)

    shared_url = os.environ.get("TRANSDUCK_SHARED_URL") or raw.get("storage", {}).get("shared_url")

    read_only = raw.get("runtime", {}).get("read_only", False)
    if provider == "claude_code":
        read_only = True

    return TransduckConfig(
        project_name=raw["project"]["name"],
        project_context=raw["project"]["context"],
        source_lang=raw["languages"]["source"].upper(),
        target_langs=[lang.upper() for lang in raw["languages"]["targets"]],
        shared_url=shared_url,
        storage_path=storage_path,
        provider=provider,
        api_key_env=api_key_env,
        token_env=token_env,
        backend_model=backend_model,
        backend_timeout=backend_timeout,
        backend_max_retries=backend_max_retries,
        read_only=read_only,
    )
