# SPDX-License-Identifier: Apache-2.0
# Copyright (C) 2024-2026 SYMFLUENCE Team <dev@symfluence.org>

"""
Snow-17 Configuration.

Pydantic schema and configuration adapter for standalone Snow-17 usage.
"""

from typing import Any, Dict, List, Optional

from pydantic import BaseModel, Field

from symfluence.models.base.base_config import AutoGeneratedConfigAdapter


class Snow17Config(BaseModel):
    """Snow-17 model configuration schema."""

    latitude: float = Field(
        default=45.0, ge=-90.0, le=90.0,
        description="Catchment latitude for seasonal melt factor.",
    )
    si: float = Field(
        default=100.0, ge=0.0,
        description="SWE threshold for 100% areal coverage (mm).",
    )
    dt: float = Field(
        default=1.0, gt=0.0,
        description="Timestep in days.",
    )
    adc: Optional[List[float]] = Field(
        default=None,
        description="11-point areal depletion curve. Uses default if None.",
    )

    model_config = {'extra': 'forbid'}


class Snow17ConfigAdapter(AutoGeneratedConfigAdapter):
    """Configuration adapter for Snow-17 model."""

    MODEL_NAME = "SNOW17"
    CONFIG_PREFIX = "SNOW17_"

    @classmethod
    def get_config_schema(cls) -> type:
        return Snow17Config

    @classmethod
    def get_defaults(cls) -> Dict[str, Any]:
        return {
            'SNOW17_LATITUDE': 45.0,
            'SNOW17_SI': 100.0,
            'SNOW17_DT': 1.0,
        }

    @classmethod
    def _get_legacy_transformers(cls) -> Dict[str, tuple]:
        return {
            'SNOW17_LATITUDE': ('latitude', float),
            'SNOW17_SI': ('si', float),
            'SNOW17_DT': ('dt', float),
        }

    @classmethod
    def from_dict(cls, config_dict: Dict[str, Any]) -> Snow17Config:
        transformers = cls._get_legacy_transformers()
        defaults = cls.get_defaults()
        kwargs = {}
        for config_key, (field_name, field_type) in transformers.items():
            value = config_dict.get(config_key, defaults.get(config_key))
            if value is not None:
                try:
                    kwargs[field_name] = field_type(value)
                except (ValueError, TypeError):
                    kwargs[field_name] = value
        return Snow17Config(**kwargs)

    @classmethod
    def to_dict(cls, config: Snow17Config) -> Dict[str, Any]:
        transformers = cls._get_legacy_transformers()
        result = {}
        for config_key, (field_name, _) in transformers.items():
            if hasattr(config, field_name):
                result[config_key] = getattr(config, field_name)
        return result
