import os
from pathlib import Path

from pydantic import BaseModel, Field


class MessagesSettings(BaseModel):
    display_tools: bool = Field(default=True)
    accept_files: bool = Field(default=True)


class ChannelsSettings(BaseModel):
    telegram_bot_token: str = Field(default="")


class ToolsSettings(BaseModel):
    console: bool = Field(default=True)
    enable_execute: bool = Field(default=False)
    skill_usage: bool = Field(default=True)
    skill_creation: bool = Field(default=True)
    send_file: bool = Field(default=True)
    web_fetch: bool = Field(default=True)
    get_text: bool = Field(default=True)


class ModelsSettings(BaseModel):
    primary_model: str = Field(default="google-gla:gemini-3.1-flash-lite")
    fallback_model: str | None = Field(default="google-gla:gemini-2.5-flash-lite")
    primary_smart_model: str | None = Field(default=None)
    fallback_smart_model: str | None = Field(default=None)


class Settings(BaseModel):
    models: ModelsSettings = Field(default_factory=ModelsSettings)
    tools: ToolsSettings = Field(default_factory=ToolsSettings)
    channels: ChannelsSettings = Field(default_factory=ChannelsSettings)
    messages: MessagesSettings = Field(default_factory=MessagesSettings)
    environment: dict[str, str] = Field(default_factory=dict)

    def ensure_environment_variables(self) -> None:
        for key, value in self.environment.items():
            if value:
                os.environ[key] = value

    @classmethod
    def load(cls, path: Path) -> "Settings":
        return cls.model_validate_json(path.read_text(encoding="utf-8"))

    @classmethod
    def ensure(cls, path: Path) -> "Settings":
        if not path.exists():
            settings = cls()
            path.write_text(settings.model_dump_json(indent=2), encoding="utf-8")
        return cls.load(path)
