"""
Configuration models for AgentChain.
"""

from dataclasses import dataclass, field
from typing import Dict, Optional, Any, List
from pathlib import Path


@dataclass
class AgentConfig:
    """Configuration for an individual agent."""
    enabled: bool = True
    model: Optional[str] = None  # Override model for this agent
    max_retries: int = 3
    timeout: int = 300
    extra: Dict[str, Any] = field(default_factory=dict)


@dataclass
class ChainConfig:
    """
    Configuration for AgentChain.
    
    This is built up via the fluent API and then used during execution.
    """
    # Requirements
    requirements: str = ""
    requirements_file: Optional[str] = None
    
    # LLM settings
    default_model: str = "llama3:8b"
    ollama_url: str = "http://localhost:11434"
    timeout: int = 300
    temperature: float = 0.7
    
    # Output settings
    output_dir: str = "./output"
    workspace_name: str = "project"
    
    # Agent configurations (agent_name -> config)
    agents: Dict[str, AgentConfig] = field(default_factory=dict)
    
    # Orchestrator override
    orchestrator_name: Optional[str] = None
    
    # Execution settings
    max_task_retries: int = 3
    auto_retry: bool = True
    infinity_mode: bool = False  # Continuous improvement mode
    
    # Logging
    log_level: str = "INFO"
    verbose: bool = False
    
    def get_agent_config(self, name: str) -> AgentConfig:
        """Get config for an agent, creating default if needed."""
        if name not in self.agents:
            self.agents[name] = AgentConfig()
        return self.agents[name]
    
    def get_agent_model(self, name: str) -> str:
        """Get model for an agent (agent-specific or default)."""
        config = self.agents.get(name)
        if config and config.model:
            return config.model
        return self.default_model
    
    def validate(self) -> List[str]:
        """Validate configuration, return list of errors."""
        errors = []
        
        if not self.requirements and not self.requirements_file:
            errors.append("No requirements provided")
        
        if self.requirements_file:
            if not Path(self.requirements_file).exists():
                errors.append(f"Requirements file not found: {self.requirements_file}")
        
        return errors
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary."""
        return {
            "requirements": self.requirements,
            "requirements_file": self.requirements_file,
            "default_model": self.default_model,
            "ollama_url": self.ollama_url,
            "output_dir": self.output_dir,
            "agents": {
                name: {
                    "enabled": cfg.enabled,
                    "model": cfg.model,
                    "max_retries": cfg.max_retries,
                }
                for name, cfg in self.agents.items()
            },
        }
