"""Configuration management for scry-run.

Loads config from ~/.scry-run/config.toml and converts to env vars.
"""

import os
from dataclasses import dataclass
from pathlib import Path
from typing import Optional

try:
    import tomllib
except ImportError:
    import tomli as tomllib

from scry_run.home import get_config_path


DEFAULT_CONFIG = """\
# scry-run configuration
# https://github.com/scry-run/scry-run

[defaults]
backend = "auto"              # auto, claude, frozen
quiet = false                 # Suppress generation messages
full_context = true           # Use full codebase context

[logging]
level = "info"                # debug, info, warn, error

[backend.claude]
# model = "opus"              # sonnet, opus, haiku (or full model ID)
"""


@dataclass
class Config:
    """Configuration for scry-run."""

    # Defaults
    backend: str = "auto"
    quiet: bool = False
    full_context: bool = True

    # Logging
    log_level: str = "info"

    # Backend: claude
    claude_model: Optional[str] = None


def load_config() -> Config:
    """Load configuration from file and environment.

    Priority (highest to lowest):
    1. Environment variables
    2. Config file (~/.scry-run/config.toml)
    3. Default values

    Returns:
        Config object with merged settings
    """
    config_path = get_config_path()

    # Start with defaults
    kwargs = {}

    # Load from file if exists
    if config_path.exists():
        with open(config_path, "rb") as f:
            data = tomllib.load(f)

        # Parse [defaults] section
        defaults = data.get("defaults", {})
        if "backend" in defaults:
            kwargs["backend"] = defaults["backend"]
        if "quiet" in defaults:
            kwargs["quiet"] = defaults["quiet"]
        if "full_context" in defaults:
            kwargs["full_context"] = defaults["full_context"]

        # Parse [logging] section
        logging = data.get("logging", {})
        if "level" in logging:
            kwargs["log_level"] = logging["level"]

        # Parse backend sections
        backends = data.get("backend", {})

        # [backend.claude]
        claude = backends.get("claude", {})
        if "model" in claude:
            kwargs["claude_model"] = claude["model"]

    # Environment variables OVERRIDE config file (highest priority)
    if env_backend := os.environ.get("SCRY_BACKEND"):
        kwargs["backend"] = env_backend
    if env_quiet := os.environ.get("SCRY_QUIET"):
        kwargs["quiet"] = env_quiet.lower() in ("true", "1", "yes")
    if env_full_context := os.environ.get("SCRY_FULL_CONTEXT"):
        kwargs["full_context"] = env_full_context.lower() in ("true", "1", "yes")
    if env_log_level := os.environ.get("SCRY_LOG_LEVEL"):
        kwargs["log_level"] = env_log_level

    return Config(**kwargs)


def get_env_vars(config: Config) -> dict[str, str]:
    """Convert config to environment variables dict for subprocess.

    Existing environment variables take precedence.

    Args:
        config: Config object to convert

    Returns:
        Dict of environment variable names to values
    """
    env_vars = {}

    def set_if_value(key: str, value) -> None:
        """Set env var if value is truthy, respecting existing env."""
        if key in os.environ:
            env_vars[key] = os.environ[key]
        elif value is not None and value != "":
            env_vars[key] = str(value).lower() if isinstance(value, bool) else str(value)

    # Core settings (always have defaults)
    set_if_value("SCRY_BACKEND", config.backend)
    set_if_value("SCRY_QUIET", config.quiet)
    set_if_value("SCRY_FULL_CONTEXT", config.full_context)
    set_if_value("SCRY_LOG_LEVEL", config.log_level)

    # Model env vars - export for selected backend, but always preserve existing env vars
    if config.backend == "claude":
        set_if_value("SCRY_MODEL", config.claude_model)
    # For "auto" or other: still preserve any existing env vars
    if "SCRY_MODEL" in os.environ:
        env_vars["SCRY_MODEL"] = os.environ["SCRY_MODEL"]

    return env_vars
