"""Load web service configuration."""

from __future__ import annotations

import json
from dataclasses import dataclass
from pathlib import Path


@dataclass
class WebConfig:
    bind_host: str = "0.0.0.0"
    bind_port: int = 8080
    redis_url: str = "redis://127.0.0.1:6379/0"
    log_path: Path = Path("/var/log/hot-tub/web.log")
    static_dir: Path = Path(__file__).resolve().parent / "frontend" / "dist"
    stale_s: float = 15.0
    heartbeat_s: float = 5.0
    sse_keepalive_s: float = 15.0


def load_config(path: Path | None) -> WebConfig:
    cfg = WebConfig()
    if path is None or not path.exists():
        return cfg
    data = json.loads(path.read_text())
    if "bind_host" in data:
        cfg.bind_host = str(data["bind_host"])
    if "bind_port" in data:
        cfg.bind_port = int(data["bind_port"])
    if "redis_url" in data:
        cfg.redis_url = str(data["redis_url"])
    if "log_path" in data:
        cfg.log_path = Path(data["log_path"])
    if "static_dir" in data:
        cfg.static_dir = Path(data["static_dir"])
    if not cfg.static_dir.is_absolute():
        cfg.static_dir = Path(__file__).resolve().parent / cfg.static_dir
    if "stale_s" in data:
        cfg.stale_s = float(data["stale_s"])
    if "heartbeat_s" in data:
        cfg.heartbeat_s = float(data["heartbeat_s"])
    if "sse_keepalive_s" in data:
        cfg.sse_keepalive_s = float(data["sse_keepalive_s"])
    return cfg
