"""Configuration management for doc-to-skill."""

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


@dataclass
class CrawlerConfig:
    """Configuration for web crawler."""
    max_depth: int = 3
    max_pages: int = 100
    delay: float = 0.5
    user_agent: str = "doc-to-skill/0.1"
    allowed_extensions: list[str] = field(default_factory=lambda: [
        ".html", ".htm", ".md", ".txt", ""
    ])
    exclude_patterns: list[str] = field(default_factory=lambda: [
        "/api/", "/search", "/login", "/signup", "?", "#"
    ])


@dataclass
class GeneratorConfig:
    """Configuration for skill generator."""
    max_skill_lines: int = 500
    include_examples: bool = True
    include_reference: bool = True


@dataclass
class Config:
    """Main configuration class."""
    crawler: CrawlerConfig = field(default_factory=CrawlerConfig)
    generator: GeneratorConfig = field(default_factory=GeneratorConfig)
    
    @classmethod
    def load(cls, path: Path) -> "Config":
        """Load configuration from YAML file."""
        if not path.exists():
            return cls()
        
        with open(path, "r", encoding="utf-8") as f:
            data = yaml.safe_load(f) or {}
        
        crawler_data = data.get("crawler", {})
        generator_data = data.get("generator", {})
        
        return cls(
            crawler=CrawlerConfig(**crawler_data),
            generator=GeneratorConfig(**generator_data)
        )
    
    def save(self, path: Path):
        """Save configuration to YAML file."""
        data = {
            "crawler": {
                "max_depth": self.crawler.max_depth,
                "max_pages": self.crawler.max_pages,
                "delay": self.crawler.delay,
                "user_agent": self.crawler.user_agent,
            },
            "generator": {
                "max_skill_lines": self.generator.max_skill_lines,
                "include_examples": self.generator.include_examples,
                "include_reference": self.generator.include_reference,
            }
        }
        
        path.parent.mkdir(parents=True, exist_ok=True)
        with open(path, "w", encoding="utf-8") as f:
            yaml.dump(data, f, default_flow_style=False)
