"""Configuration loader for TactTerm."""
import os
import json
from typing import Dict, Any


class Config:
    """Manages application configuration settings."""

    DEFAULT_CONFIG = {
        "llm": {
            "base_url": "http://localhost:8080/v1",
            "model": "local-model",
            "api_key": "not-needed",
            "temperature": 0.7,
            "max_tokens": 512,
            "timeout_seconds": 5.0,
        },
        "web": {
            "host": "127.0.0.1",
            "port": 8000,
            "public": False,
        },
    }

    def __init__(self, config_path: str = "config.json") -> None:
        self.config_path = config_path
        self._data = self.load_config()

    def load_config(self) -> Dict[str, Any]:
        # Deep copy default configuration structure
        config = json.loads(json.dumps(self.DEFAULT_CONFIG))
        if os.path.exists(self.config_path):
            try:
                with open(self.config_path, "r", encoding="utf-8") as f:
                    user_config = json.load(f)
                    if "llm" in user_config and isinstance(user_config["llm"], dict):
                        config["llm"].update(user_config["llm"])
                    if "web" in user_config and isinstance(user_config["web"], dict):
                        config["web"].update(user_config["web"])
            except Exception as e:
                print(f"Warning: Failed to load {self.config_path}: {e}")
        else:
            try:
                dirname = os.path.dirname(self.config_path)
                if dirname:
                    os.makedirs(dirname, exist_ok=True)
                with open(self.config_path, "w", encoding="utf-8") as f:
                    json.dump(config, f, indent=2)
            except Exception as e:
                print(f"Warning: Failed to create default {self.config_path}: {e}")


        # Allow environment variable overrides
        env_base_url = os.getenv("TACTTERM_LLM_BASE_URL")
        if env_base_url:
            config["llm"]["base_url"] = env_base_url

        env_model = os.getenv("TACTTERM_LLM_MODEL")
        if env_model:
            config["llm"]["model"] = env_model

        env_web_host = os.getenv("TACTTERM_WEB_HOST")
        if env_web_host:
            config["web"]["host"] = env_web_host

        env_web_port = os.getenv("TACTTERM_WEB_PORT")
        if env_web_port:
            try:
                config["web"]["port"] = int(env_web_port)
            except ValueError:
                pass

        env_web_public = os.getenv("TACTTERM_WEB_PUBLIC")
        if env_web_public is not None:
            config["web"]["public"] = env_web_public.lower() in ("true", "1", "yes")

        return config

    @property
    def llm_base_url(self) -> str:
        return self._data["llm"]["base_url"].rstrip("/")

    @property
    def llm_model(self) -> str:
        return self._data["llm"]["model"]

    @property
    def llm_api_key(self) -> str:
        return self._data["llm"]["api_key"]

    @property
    def llm_temperature(self) -> float:
        return float(self._data["llm"]["temperature"])

    @property
    def llm_max_tokens(self) -> int:
        return int(self._data["llm"]["max_tokens"])

    @property
    def llm_timeout(self) -> float:
        return float(self._data["llm"]["timeout_seconds"])

    @property
    def web_public(self) -> bool:
        return bool(self._data.get("web", {}).get("public", False))

    @property
    def web_host(self) -> str:
        if self.web_public:
            return "0.0.0.0"
        return self._data.get("web", {}).get("host", "127.0.0.1")

    @property
    def web_port(self) -> int:
        return int(self._data.get("web", {}).get("port", 8000))


config = Config()

