"""Configuration management for Hephaestus."""

from __future__ import annotations

from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

import yaml


@dataclass
class HephaestusConfig:
    """Configuration for Hephaestus MCP server."""

    default_theme: str = "material-3"
    default_routing: str = "official"
    enable_reactive: bool = True
    output_directory: str = "./generated"
    template_directory: str = "./templates"
    validation_strict: bool = True
    auto_backup: bool = True

    @classmethod
    def from_file(cls, config_path: Path) -> "HephaestusConfig":
        """Load configuration from YAML file."""
        if not config_path.exists():
            return cls()

        try:
            with open(config_path, "r", encoding="utf-8") as f:
                config_data = yaml.safe_load(f)
                return cls(**config_data)
        except Exception as e:
            raise ValueError(f"Failed to load config from {config_path}: {e}")

    def to_file(self, config_path: Path) -> None:
        """Save configuration to YAML file."""
        config_path.parent.mkdir(parents=True, exist_ok=True)

        config_dict = {
            "default_theme": self.default_theme,
            "default_routing": self.default_routing,
            "enable_reactive": self.enable_reactive,
            "output_directory": self.output_directory,
            "template_directory": self.template_directory,
            "validation_strict": self.validation_strict,
            "auto_backup": self.auto_backup,
        }

        with open(config_path, "w", encoding="utf-8") as f:
            yaml.dump(config_dict, f, default_flow_style=False)

    def get_theme_config(self, theme_type: str) -> dict[str, Any]:
        """Get theme-specific configuration."""
        themes = {
            "material-3": {
                "primary_color": "#1976d2",
                "secondary_color": "#424242",
                "surface_color": "#ffffff",
                "background_color": "#fafafa",
            },
            "classic": {
                "primary_color": "#2196f3",
                "secondary_color": "#757575",
                "surface_color": "#ffffff",
                "background_color": "#f5f5f5",
            },
        }
        return themes.get(theme_type, themes["material-3"])

    def get_routing_config(self, routing_type: str) -> dict[str, Any]:
        """Get routing-specific configuration."""
        routing_configs = {
            "official": {
                "enable_data_loading": True,
                "enable_caching": True,
                "default_timeout": 30,
            },
            "anvil-extras": {
                "enable_data_loading": False,
                "enable_caching": False,
                "default_timeout": 10,
            },
            "none": {
                "enable_data_loading": False,
                "enable_caching": False,
                "default_timeout": 5,
            },
        }
        return routing_configs.get(routing_type, routing_configs["official"])

    def validate(self) -> list[str]:
        """Validate configuration and return any issues."""
        issues = []

        if self.default_theme not in ["material-3", "classic", "shoelace", "custom"]:
            issues.append(f"Invalid default_theme: {self.default_theme}")

        if self.default_routing not in ["official", "anvil-extras", "none"]:
            issues.append(f"Invalid default_routing: {self.default_routing}")

        if not Path(self.output_directory).parent.exists():
            issues.append(
                f"Output directory parent does not exist: {self.output_directory}"
            )

        if not Path(self.template_directory).exists():
            issues.append(
                f"Template directory does not exist: {self.template_directory}"
            )

        return issues
