"""Configuration management for Promethian."""

from __future__ import annotations

from pathlib import Path
from typing import Literal, Optional
from pydantic_settings import BaseSettings


class PromethianConfig(BaseSettings):
    """Configuration for the Promethian agent."""

    # API Configuration
    promethian_api_url: str = "https://promethian-api.fly.dev"
    promethian_api_key: Optional[str] = None

    # Anthropic Configuration (user's key)
    anthropic_api_key: Optional[str] = None

    # Model Configuration
    # Main orchestration model (planning, synthesis)
    model: str = "claude-opus-4-5-20251101"
    # Sub-agent model for step execution (can be faster/cheaper)
    sub_agent_model: Optional[str] = None  # Defaults to main model if not set
    # Context gathering model (can be fastest/cheapest)
    context_model: Optional[str] = None  # Defaults to "claude-haiku-4-5-20251001" if not set

    max_tokens: int = 8192
    sub_agent_max_tokens: int = 4096  # Sub-agents often need less

    # Local Cache Configuration
    cache_dir: Path = Path("~/.promethian/cache").expanduser()
    cache_ttl: int = 3600  # 1 hour

    # Tool Execution Configuration
    tool_envs_dir: Path = Path("~/.promethian/tool_envs").expanduser()
    tool_timeout: int = 60  # seconds
    tool_max_output: int = 100000  # bytes
    working_dir: Path | None = None  # Working directory for tool execution (default: cwd)

    # Agent Behavior
    confidence_threshold: float = 0.7
    high_confidence_threshold: float = 0.85
    max_self_heal_attempts: int = 3
    max_tool_iterations: int = 10  # Max agentic loop iterations per step (controls API costs)

    # Usage Tracking
    track_usage: bool = True  # Track token/model usage for cost visibility

    # Retrieval Settings
    max_retrieved_skills: int = 5
    max_retrieved_tools: int = 5
    similarity_threshold: float = 0.3

    # Verbose Logging
    verbose_logging: bool = False  # Enable detailed logging to file
    log_dir: Path = Path("~/.promethian/logs").expanduser()

    # Session Log Sharing (helps improve Promethian)
    # "none" = don't share logs
    # "failures" = only share logs when tasks struggle/fail (default)
    # "all" = share all session logs
    share_logs: Literal["none", "failures", "all"] = "failures"

    class Config:
        env_prefix = ""
        env_file = ".env"
        extra = "ignore"

    def get_sub_agent_model(self) -> str:
        """Get the model for sub-agents (defaults to main model)."""
        return self.sub_agent_model or self.model

    def get_context_model(self) -> str:
        """Get the model for context gathering (defaults to Haiku for speed)."""
        return self.context_model or "claude-haiku-4-5-20251001"

    def validate_config(self) -> None:
        """Validate that required configuration is present."""
        if not self.anthropic_api_key:
            raise ValueError(
                "ANTHROPIC_API_KEY is required. "
                "Set it in your environment or .env file."
            )
        if not self.promethian_api_key:
            raise ValueError(
                "PROMETHIAN_API_KEY is required. "
                "Set it in your environment or .env file."
            )


_config: Optional[PromethianConfig] = None


def get_config() -> PromethianConfig:
    """Get the global configuration singleton."""
    global _config
    if _config is None:
        _config = PromethianConfig()
    return _config


def set_config(config: PromethianConfig) -> None:
    """Set the global configuration."""
    global _config
    _config = config
