"""Load configuration from environment variables."""

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


@dataclass
class Config:
    bot_token: str = ""
    owner_id: int = 0
    data_dir: Path = Path(".")
    claude_cmd: str = "claude"
    proxy: str | None = None
    stt_url: str | None = None
    allowed_tools: list[str] = field(default_factory=list)
    claude_idle_timeout: int = 120
    claude_max_timeout: int = 1800
    workspace_dir: Path | None = None

    @classmethod
    def from_env(cls) -> "Config":
        bot_token = os.environ.get("BOT_TOKEN", "")
        owner_id_str = os.environ.get("OWNER_ID", "0")
        owner_id = int(owner_id_str)

        data_dir_str = os.environ.get("DATA_DIR", "")
        if not data_dir_str:
            raise ValueError("DATA_DIR env var is required")
        data_dir = Path(data_dir_str)

        claude_cmd = os.environ.get("CLAUDE_CMD", "claude")
        proxy = os.environ.get("PROXY") or None
        stt_url = os.environ.get("STT_URL") or os.environ.get("WHISPER_URL") or None

        default_tools = "Read,Write,Edit,Glob,Grep,Bash,WebSearch,WebFetch,mcp__fetcher,mcp__yandex-search"
        allowed_tools_str = os.environ.get("ALLOWED_TOOLS", default_tools)
        allowed_tools = [t.strip() for t in allowed_tools_str.split(",") if t.strip()]

        idle_timeout_str = os.environ.get("CLAUDE_IDLE_TIMEOUT",
                                         os.environ.get("CLAUDE_TIMEOUT", "120"))
        claude_idle_timeout = int(idle_timeout_str)
        max_timeout_str = os.environ.get("CLAUDE_MAX_TIMEOUT", "1800")
        claude_max_timeout = int(max_timeout_str)

        workspace_dir_str = os.environ.get("WORKSPACE_DIR")
        workspace_dir = Path(workspace_dir_str) if workspace_dir_str else None

        return cls(
            bot_token=bot_token,
            owner_id=owner_id,
            data_dir=data_dir,
            claude_cmd=claude_cmd,
            proxy=proxy,
            stt_url=stt_url,
            allowed_tools=allowed_tools,
            claude_idle_timeout=claude_idle_timeout,
            claude_max_timeout=claude_max_timeout,
            workspace_dir=workspace_dir,
        )
