#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Algorithm Configuration
主配置类 - 整合所有算法组件的配置
"""

from typing import Dict, Any, Optional, Union
from pathlib import Path
import json
import os
import logging

from .models import (
    AlgorithmConfig as BaseAlgorithmConfig,
    AIModelConfig,
    PromptConfig,
    ContentGenerationConfig,
    PosterGenerationConfig,
    DocumentProcessingConfig,
    WebCrawlingConfig,
    KeywordAnalysisConfig,
    ContentAnalysisConfig,
    OutputConfig,
    ResourceConfig
)
from .defaults import DefaultConfigProvider

logger = logging.getLogger(__name__)


class AlgorithmConfig(BaseAlgorithmConfig):
    """
    算法配置聚合器 - 重构版本
    包含所有算法模块的配置
    """
    
    # 核心配置
    ai_model: AIModelConfig
    prompts: PromptConfig
    resources: ResourceConfig
    output: OutputConfig
    
    # 算法模块配置
    content_generation: ContentGenerationConfig
    poster_generation: PosterGenerationConfig
    document_processing: DocumentProcessingConfig
    web_crawling: WebCrawlingConfig
    keyword_analysis: KeywordAnalysisConfig
    content_analysis: ContentAnalysisConfig
    
    def __init__(self, **data):
        super().__init__(**data)
        self._validate_configuration()
    
    def _validate_configuration(self):
        """验证配置的一致性"""
        # 验证AI模型配置
        if not self.ai_model.base_url or not self.ai_model.api_key:
            logger.warning("AI模型配置不完整，某些功能可能无法使用")
        
        # 验证资源路径
        if self.resources.base_directory:
            base_path = Path(self.resources.base_directory)
            if not base_path.exists():
                logger.warning(f"资源目录不存在: {base_path}")
        
        # 验证输出配置
        if self.output.base_directory:
            output_path = Path(self.output.base_directory)
            try:
                output_path.mkdir(parents=True, exist_ok=True)
            except Exception as e:
                logger.warning(f"无法创建输出目录: {e}")
    
    def get_task_configs(self) -> Dict[str, Dict[str, Any]]:
        """获取所有任务的配置"""
        return {
            "topic_generation": self.ai_model.get_task_config("topic_generation"),
            "content_generation": self.ai_model.get_task_config("content_generation"),
            "content_judging": self.ai_model.get_task_config("content_judging"),
            "poster_generation": self.ai_model.get_task_config("poster_generation"),
            "content_transformation": self.ai_model.get_task_config("content_transformation"),
            "keyword_analysis": self.ai_model.get_task_config("keyword_analysis"),
            "content_analysis": self.ai_model.get_task_config("content_analysis")
        }
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "ai_model": self.ai_model.dict(),
            "prompts": self.prompts.dict(),
            "resources": self.resources.dict(),
            "output": self.output.dict(),
            "content_generation": self.content_generation.dict(),
            "poster_generation": self.poster_generation.dict(),
            "document_processing": self.document_processing.dict(),
            "web_crawling": self.web_crawling.dict(),
            "keyword_analysis": self.keyword_analysis.dict(),
            "content_analysis": self.content_analysis.dict()
        }
    
    def save_to_file(self, file_path: Union[str, Path]) -> None:
        """
        保存配置到JSON文件
        
        Args:
            file_path: 保存路径
        """
        file_path = Path(file_path)
        file_path.parent.mkdir(parents=True, exist_ok=True)
        
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(self.to_dict(), f, ensure_ascii=False, indent=2)
    
    def get_prompt(self, prompt_type: str, template_key: str = "system") -> str:
        """
        获取提示词
        
        Args:
            prompt_type: 提示词类型 (topic_generation, content_generation, etc.)
            template_key: 模板键 (system, user)
            
        Returns:
            提示词字符串
        """
        prompts = getattr(self.prompts, prompt_type, {})
        if isinstance(prompts, dict):
            return prompts.get(template_key, "")
        return ""
    
    def get_resource_path(self, resource_type: str, resource_name: str = None) -> Optional[str]:
        """
        获取资源文件路径
        
        Args:
            resource_type: 资源类型 (font, image, etc.)
            resource_name: 资源名称
            
        Returns:
            资源文件路径
        """
        if resource_type == "font":
            return self.resources.get_font_path(resource_name or "default")
        elif resource_type == "prompt_template":
            if self.resources.prompt_template_directory:
                return self.resources.resolve_path(self.resources.prompt_template_directory)
        elif resource_type == "image_assets":
            if self.resources.image_assets_directory:
                return self.resources.resolve_path(self.resources.image_assets_directory)
        
        return None
    
    def update_from_dict(self, updates: Dict[str, Any]) -> None:
        """
        从字典更新配置
        
        Args:
            updates: 更新的配置字典
        """
        current_dict = self.to_dict()
        merged = self._deep_merge(current_dict, updates)
        
        # 重新创建配置对象
        self.ai_model = AIModelConfig(**merged.get("ai_model", {}))
        self.content_generation = ContentGenerationConfig(**merged.get("content_generation", {}))
        self.poster_generation = PosterGenerationConfig(**merged.get("poster_generation", {}))
        self.document_processing = DocumentProcessingConfig(**merged.get("document_processing", {}))
        self.output = OutputConfig(**merged.get("output", {}))
        self.prompts = PromptConfig(**merged.get("prompts", {}))
        self.resources = ResourceConfig(**merged.get("resources", {}))
    
    @staticmethod
    def _deep_merge(base: Dict[str, Any], updates: Dict[str, Any]) -> Dict[str, Any]:
        """
        深度合并两个字典
        
        Args:
            base: 基础字典
            updates: 更新字典
            
        Returns:
            合并后的字典
        """
        result = base.copy()
        
        for key, value in updates.items():
            if key in result and isinstance(result[key], dict) and isinstance(value, dict):
                result[key] = AlgorithmConfig._deep_merge(result[key], value)
            else:
                result[key] = value
        
        return result
    
    def validate(self) -> bool:
        """
        验证配置的完整性和有效性
        
        Returns:
            验证是否通过
        """
        try:
            # 验证AI配置
            if not self.ai_model.api_key or not self.ai_model.api_url:
                print("警告：AI模型配置不完整（缺少api_key或api_url）")
                return False
            
            # 验证必要的提示词
            required_prompts = ["topic_generation", "content_generation"]
            for prompt_type in required_prompts:
                prompts = getattr(self.prompts, prompt_type, {})
                if not prompts or not prompts.get("system") or not prompts.get("user"):
                    print(f"警告：缺少必要的提示词配置: {prompt_type}")
                    return False
            
            return True
            
        except Exception as e:
            print(f"配置验证失败: {e}")
            return False
    
    def __repr__(self) -> str:
        return f"AlgorithmConfig(ai_model={self.ai_model.model}, templates={list(self.poster_generation.available_templates)})" 