"""Configuration management for boba.

Handles loading and saving .boba.yaml configuration files.
"""

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

try:
    import yaml
except ImportError:
    yaml = None


CONFIG_FILENAME = ".boba.yaml"


@dataclass
class BobaConfig:
    """Boba configuration."""
    runtime: str = "local"  # "local" or "docker-compose"
    service: Optional[str] = None  # Docker service name


def find_config() -> Optional[Path]:
    """Find .boba.yaml in evals/ folder or current directory."""
    # Check evals/ folder first
    evals_config = Path("evals") / CONFIG_FILENAME
    if evals_config.exists():
        return evals_config

    # Check current directory
    cwd_config = Path(CONFIG_FILENAME)
    if cwd_config.exists():
        return cwd_config

    return None


def load_config() -> Optional[BobaConfig]:
    """Load configuration from .boba.yaml if it exists."""
    config_path = find_config()
    if not config_path:
        return None

    if yaml is None:
        # PyYAML not installed, return None
        return None

    try:
        with open(config_path) as f:
            data = yaml.safe_load(f) or {}

        return BobaConfig(
            runtime=data.get("runtime", "local"),
            service=data.get("service"),
        )
    except Exception:
        return None


def save_config(config: BobaConfig, path: Path) -> None:
    """Save configuration to a file."""
    if yaml is None:
        # Write manually without PyYAML
        lines = [
            "# Boba configuration",
            "# Auto-generated by boba init",
            "",
            f"runtime: {config.runtime}",
        ]
        if config.service:
            lines.append(f"service: {config.service}")
        lines.append("")
        path.write_text("\n".join(lines))
    else:
        data = {"runtime": config.runtime}
        if config.service:
            data["service"] = config.service

        with open(path, "w") as f:
            f.write("# Boba configuration\n")
            f.write("# Auto-generated by boba init\n\n")
            yaml.dump(data, f, default_flow_style=False)


def inside_container() -> bool:
    """Check if we're running inside a Docker container."""
    # Check for /.dockerenv file (Docker)
    if Path("/.dockerenv").exists():
        return True

    # Check cgroup (works for Docker and other container runtimes)
    try:
        with open("/proc/1/cgroup", "r") as f:
            content = f.read()
            if "docker" in content or "kubepods" in content or "containerd" in content:
                return True
    except (FileNotFoundError, PermissionError):
        pass

    # Check for container environment variables
    if os.environ.get("container") or os.environ.get("KUBERNETES_SERVICE_HOST"):
        return True

    return False


def maybe_exec_in_docker() -> None:
    """If configured for Docker and not already in container, exec into Docker.

    This function should be called early in CLI execution. If Docker mode
    is configured and we're not already inside a container, it will exec
    into the Docker container, replacing the current process.
    """
    # Skip if we're already in a container
    if inside_container():
        return

    # Skip if explicitly disabled
    if os.environ.get("BOBA_NO_DOCKER") == "1":
        return

    # Load config
    config = load_config()
    if not config:
        return

    # Only handle docker-compose for now
    if config.runtime != "docker-compose":
        return

    if not config.service:
        return

    # Build the docker compose exec command
    # We need to pass through all arguments
    args = ["docker", "compose", "exec", config.service, "boba"] + sys.argv[1:]

    # Replace current process with docker exec
    os.execvp("docker", args)
