import os
from dataclasses import dataclass


@dataclass(frozen=True, slots=True)
class ServerConfig:
    host: str
    port: int
    default_width: int
    default_height: int
    render_supersample_scale: int
    weather_update_secs: int
    next_rain_gap_tolerance_hours: float
    weather_latitude: float | None
    weather_longitude: float | None


def load_server_config() -> ServerConfig:
    weather_latitude_raw = os.getenv("WEATHER_LATITUDE")
    weather_longitude_raw = os.getenv("WEATHER_LONGITUDE")
    if (weather_latitude_raw is None) != (weather_longitude_raw is None):
        message = "WEATHER_LATITUDE and WEATHER_LONGITUDE must both be set together"
        raise ValueError(message)
    next_rain_gap_tolerance_hours = float(
        os.getenv("NEXT_RAIN_GAP_TOLERANCE_HOURS", "1")
    )
    if next_rain_gap_tolerance_hours < 0:
        message = "NEXT_RAIN_GAP_TOLERANCE_HOURS must be non-negative"
        raise ValueError(message)
    return ServerConfig(
        host=os.getenv("HOST", "127.0.0.1"),
        port=int(os.getenv("PORT", "42137")),
        default_width=int(os.getenv("IMAGE_WIDTH", "600")),
        default_height=int(os.getenv("IMAGE_HEIGHT", "800")),
        render_supersample_scale=int(os.getenv("RENDER_SUPERSAMPLE_SCALE", "2")),
        weather_update_secs=int(os.getenv("WEATHER_UPDATE_SECS", str(30 * 60))),
        next_rain_gap_tolerance_hours=next_rain_gap_tolerance_hours,
        weather_latitude=float(weather_latitude_raw)
        if weather_latitude_raw is not None
        else None,
        weather_longitude=float(weather_longitude_raw)
        if weather_longitude_raw is not None
        else None,
    )
