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


@dataclass
class FactorAnalysisConfig:
    """Lightweight config for factor analysis runs."""

    data_source: str = "csv"  # csv|parquet|clickhouse
    data_path: Optional[str] = None
    date_column: str = "date"
    code_column: str = "code"
    clickhouse: Dict[str, Any] = field(default_factory=dict)
    extras: Dict[str, Any] = field(default_factory=dict)

    @classmethod
    def from_yaml(cls, path: str) -> "FactorAnalysisConfig":
        cfg_path = Path(path)
        if not cfg_path.exists():
            raise FileNotFoundError(f"Config not found: {cfg_path}")
        with cfg_path.open("r", encoding="utf-8") as f:
            data = yaml.safe_load(f) or {}
        return cls(
            data_source=str(data.get("data_source", "csv")),
            data_path=data.get("data_path"),
            date_column=data.get("date_column", "date"),
            code_column=data.get("code_column", "code"),
            clickhouse=data.get("clickhouse", {}) or {},
            extras=data.get("extras", {}) or {},
        )

    def to_dict(self) -> Dict[str, Any]:
        return {
            "data_source": self.data_source,
            "data_path": self.data_path,
            "date_column": self.date_column,
            "code_column": self.code_column,
            "clickhouse": self.clickhouse,
            "extras": self.extras,
        }

    def get_clickhouse_option(self, key: str, default: Any = None) -> Any:
        """Fetch a ClickHouse option while keeping config access centralized."""
        return self.clickhouse.get(key, default)
