"""Config file management (~/.clawsy/config.toml)."""

from __future__ import annotations

import sys
from dataclasses import dataclass, field
from pathlib import Path

if sys.version_info >= (3, 11):
    import tomllib
else:
    import tomli as tomllib


CONFIG_DIR = Path.home() / ".clawsy"
CONFIG_FILE = CONFIG_DIR / "config.toml"


@dataclass
class LLMConfig:
    provider: str = "openai"
    api_key: str = ""
    model: str = "gpt-4o"
    base_url: str = "https://api.openai.com/v1"


@dataclass
class ToolsConfig:
    web_search: bool = True
    fetch_url: bool = True


@dataclass
class Config:
    hub_url: str = "https://agenthub.clawsy.app"
    api_key: str = ""
    llm: LLMConfig = field(default_factory=LLMConfig)
    tools: ToolsConfig = field(default_factory=ToolsConfig)

    @classmethod
    def load(cls) -> Config:
        """Load config from ~/.clawsy/config.toml, or return defaults."""
        if not CONFIG_FILE.exists():
            return cls()
        with open(CONFIG_FILE, "rb") as f:
            data = tomllib.load(f)
        llm_data = data.get("llm", {})
        tools_data = data.get("tools", {})
        return cls(
            hub_url=data.get("hub_url", cls.hub_url),
            api_key=data.get("api_key", ""),
            llm=LLMConfig(
                provider=llm_data.get("provider", "openai"),
                api_key=llm_data.get("api_key", ""),
                model=llm_data.get("model", "gpt-4o"),
                base_url=llm_data.get("base_url", "https://api.openai.com/v1"),
            ),
            tools=ToolsConfig(
                web_search=tools_data.get("web_search", True),
                fetch_url=tools_data.get("fetch_url", True),
            ),
        )

    def save(self) -> None:
        """Write config to ~/.clawsy/config.toml."""
        CONFIG_DIR.mkdir(parents=True, exist_ok=True)
        lines = [
            f'hub_url = "{self.hub_url}"',
            f'api_key = "{self.api_key}"',
            "",
            "[llm]",
            f'provider = "{self.llm.provider}"',
            f'api_key = "{self.llm.api_key}"',
            f'model = "{self.llm.model}"',
            f'base_url = "{self.llm.base_url}"',
            "",
        ]
        CONFIG_FILE.write_text("\n".join(lines))
