"""Load temperature daemon configuration."""

from __future__ import annotations

import json
from dataclasses import dataclass
from pathlib import Path

from .reader import DEFAULT_DEVICES_PATH


@dataclass
class TempConfig:
    interval_s: float = 5.0
    devices_path: Path = DEFAULT_DEVICES_PATH
    redis_url: str = "redis://127.0.0.1:6379/0"
    log_path: Path = Path("/var/log/hot-tub/temp.log")
    probe_map_path: Path = Path("/etc/hot-tub/temp-probes.json")
    setup_mode: bool = False


def load_config(path: Path | None) -> TempConfig:
    cfg = TempConfig()
    if path is None or not path.exists():
        return cfg
    try:
        data = json.loads(path.read_text())
    except json.JSONDecodeError as exc:
        raise ValueError(f"Invalid JSON in config {path}: {exc}") from exc
    except OSError as exc:
        raise ValueError(f"Cannot read config {path}: {exc}") from exc
    if "interval_s" in data:
        cfg.interval_s = float(data["interval_s"])
    if "devices_path" in data:
        cfg.devices_path = Path(data["devices_path"])
    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 "probe_map_path" in data:
        cfg.probe_map_path = Path(data["probe_map_path"])
    if "setup_mode" in data:
        cfg.setup_mode = bool(data["setup_mode"])
    return cfg
