"""
配置模块 - 管理爬虫配置
"""

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


@dataclass
class LLMConfig:
    """LLM 配置"""
    provider: str = "openai"  # openai, anthropic, deepseek, ollama
    model: str = "gpt-4o"
    api_key: Optional[str] = None
    base_url: Optional[str] = None
    temperature: float = 0.0
    
    def __post_init__(self):
        # 从环境变量读取 API Key
        if self.api_key is None:
            env_key_map = {
                "openai": "OPENAI_API_KEY",
                "anthropic": "ANTHROPIC_API_KEY",
                "deepseek": "DEEPSEEK_API_KEY",
            }
            env_key = env_key_map.get(self.provider, "OPENAI_API_KEY")
            self.api_key = os.getenv(env_key)


@dataclass
class BrowserConfig:
    """浏览器配置"""
    headless: bool = False
    user_data_dir: Optional[str] = None
    profile_directory: str = "Default"
    
    # 反检测延迟设置
    wait_between_actions: float = 1.0
    minimum_wait_page_load_time: float = 0.5
    wait_for_network_idle_page_load_time: float = 1.0
    
    # 超时设置
    screenshot_timeout: float = 60.0
    action_timeout: float = 60.0
    
    # 其他设置
    highlight_elements: bool = True
    keep_alive: bool = True


@dataclass
class ScraperConfig:
    """爬虫总配置"""
    llm: LLMConfig = field(default_factory=LLMConfig)
    browser: BrowserConfig = field(default_factory=BrowserConfig)
    
    # 输出设置
    output_dir: str = "./output"
    output_format: str = "json"  # json, csv, markdown
    
    # 任务设置
    max_steps: int = 100
    max_retries: int = 3
    
    @classmethod
    def from_env(cls) -> "ScraperConfig":
        """从环境变量创建配置"""
        llm_config = LLMConfig(
            provider=os.getenv("LLM_PROVIDER", "openai"),
            model=os.getenv("LLM_MODEL", "gpt-4o"),
            api_key=os.getenv("LLM_API_KEY"),
            base_url=os.getenv("LLM_BASE_URL"),
        )
        
        browser_config = BrowserConfig(
            headless=os.getenv("NSFC_HEADLESS", "false").lower() == "true",
            user_data_dir=os.getenv("NSFC_USER_DATA_DIR"),
        )
        
        return cls(
            llm=llm_config,
            browser=browser_config,
            output_dir=os.getenv("NSFC_OUTPUT_DIR", "./output"),
        )
    
    def ensure_output_dir(self):
        """确保输出目录存在"""
        Path(self.output_dir).mkdir(parents=True, exist_ok=True)
