"""Weather source data model.

A WeatherSource represents a weather data feed — a specific provider + location.
It is a standalone entity referenced by WeatherColorStripSource via weather_source_id.
"""

from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Dict, List, Optional


def _parse_common(data: dict) -> dict:
    """Extract common fields from a dict, parsing timestamps."""
    created = data.get("created_at", "")
    updated = data.get("updated_at", "")
    return {
        "id": data["id"],
        "name": data["name"],
        "created_at": datetime.fromisoformat(created) if isinstance(created, str) and created else datetime.now(timezone.utc),
        "updated_at": datetime.fromisoformat(updated) if isinstance(updated, str) and updated else datetime.now(timezone.utc),
        "description": data.get("description"),
        "tags": data.get("tags") or [],
    }


@dataclass
class WeatherSource:
    """Weather data source configuration."""

    id: str
    name: str
    created_at: datetime
    updated_at: datetime
    provider: str = "open_meteo"
    provider_config: Dict = field(default_factory=dict)
    latitude: float = 50.0
    longitude: float = 0.0
    update_interval: int = 600  # seconds (10 min default)
    description: Optional[str] = None
    tags: List[str] = field(default_factory=list)

    def to_dict(self) -> dict:
        return {
            "id": self.id,
            "name": self.name,
            "provider": self.provider,
            "provider_config": dict(self.provider_config),
            "latitude": self.latitude,
            "longitude": self.longitude,
            "update_interval": self.update_interval,
            "description": self.description,
            "tags": self.tags,
            "created_at": self.created_at.isoformat(),
            "updated_at": self.updated_at.isoformat(),
        }

    @staticmethod
    def from_dict(data: dict) -> "WeatherSource":
        common = _parse_common(data)
        return WeatherSource(
            **common,
            provider=data.get("provider", "open_meteo"),
            provider_config=data.get("provider_config") or {},
            latitude=data.get("latitude", 50.0),
            longitude=data.get("longitude", 0.0),
            update_interval=data.get("update_interval", 600),
        )
