"""Configuration management for WCG."""

import os
import yaml
from typing import Dict, List, Any
from dataclasses import dataclass, asdict
from pathlib import Path


@dataclass
class LLMConfig:
    """LLM API configuration."""
    api_url: str
    api_key: str
    model: str = "gpt-3.5-turbo"


@dataclass
class RepositoryConfig:
    """GitHub repository configuration."""
    name: str
    branch: str
    webhook_url: str


@dataclass
class Config:
    """Main configuration."""
    llm: LLMConfig
    repositories: List[RepositoryConfig]
    schedule_time: str = "10:00"
    summary_dir: str = "summaries"
    github_token: str = ""
    timezone: str = "Asia/Shanghai"  # UTC+8 (China Standard Time)


class ConfigManager:
    """Manages configuration file operations."""
    
    def __init__(self, config_path: str = None):
        """Initialize configuration manager.
        
        Args:
            config_path: Path to configuration file. Defaults to config/config.yaml
        """
        if config_path is None:
            config_path = os.path.join(os.getcwd(), "config", "config.yaml")
        self.config_path = Path(config_path)
        self.config_path.parent.mkdir(parents=True, exist_ok=True)
        
    def load(self) -> Config:
        """Load configuration from file.
        
        Returns:
            Config object
        """
        if not self.config_path.exists():
            return self._create_default_config()
        
        with open(self.config_path, 'r', encoding='utf-8') as f:
            data = yaml.safe_load(f)
        
        return self._dict_to_config(data)
    
    def save(self, config: Config) -> None:
        """Save configuration to file.
        
        Args:
            config: Config object to save
        """
        data = {
            'llm': asdict(config.llm),
            'repositories': [asdict(repo) for repo in config.repositories],
            'schedule_time': config.schedule_time,
            'summary_dir': config.summary_dir,
            'github_token': config.github_token,
            'timezone': config.timezone
        }
        
        with open(self.config_path, 'w', encoding='utf-8') as f:
            yaml.dump(data, f, allow_unicode=True, default_flow_style=False)
    
    def _create_default_config(self) -> Config:
        """Create default configuration.
        
        Returns:
            Default Config object
        """
        config = Config(
            llm=LLMConfig(
                api_url="https://api.openai.com/v1",
                api_key="your-api-key-here",
                model="gpt-3.5-turbo"
            ),
            repositories=[
                RepositoryConfig(
                    name="owner/repo",
                    branch="main",
                    webhook_url="https://example.com/webhook"
                )
            ],
            schedule_time="10:00",
            summary_dir="summaries",
            github_token="your-github-token-here",
            timezone="Asia/Shanghai"  # UTC+8 (China Standard Time)
        )
        self.save(config)
        return config
    
    def _dict_to_config(self, data: Dict[str, Any]) -> Config:
        """Convert dictionary to Config object.
        
        Args:
            data: Dictionary with configuration data
            
        Returns:
            Config object
        """
        llm_config = LLMConfig(**data['llm'])
        repositories = [RepositoryConfig(**repo) for repo in data['repositories']]
        
        return Config(
            llm=llm_config,
            repositories=repositories,
            schedule_time=data.get('schedule_time', '10:00'),
            summary_dir=data.get('summary_dir', 'summaries'),
            github_token=data.get('github_token', ''),
            timezone=data.get('timezone', 'Asia/Shanghai')
        )
    
    def update_llm(self, api_url: str, api_key: str, model: str = None) -> None:
        """Update LLM configuration.
        
        Args:
            api_url: LLM API URL
            api_key: LLM API key
            model: Model name (optional)
        """
        config = self.load()
        config.llm.api_url = api_url
        config.llm.api_key = api_key
        if model:
            config.llm.model = model
        self.save(config)
    
    def add_repository(self, name: str, branch: str, webhook_url: str) -> None:
        """Add repository configuration.
        
        Args:
            name: Repository name (owner/repo)
            branch: Branch name
            webhook_url: Webhook URL
        """
        config = self.load()
        config.repositories.append(
            RepositoryConfig(name=name, branch=branch, webhook_url=webhook_url)
        )
        self.save(config)
    
    def remove_repository(self, name: str, branch: str) -> None:
        """Remove repository configuration.
        
        Args:
            name: Repository name (owner/repo)
            branch: Branch name
        """
        config = self.load()
        config.repositories = [
            repo for repo in config.repositories
            if not (repo.name == name and repo.branch == branch)
        ]
        self.save(config)
