from __future__ import annotations

import tomllib
from dataclasses import dataclass
from pathlib import Path


DEFAULT_MAX_EPISODE_BYTES = 256 * 1024 * 1024


@dataclass(frozen=True)
class ReceiverConfig:
    listen_host: str
    listen_port: int
    store_root: Path
    incoming_root: Path
    index_path: Path
    max_episode_bytes: int
    bearer_token: str | None
    # Code-version gate. Production source is the local Forgejo
    # (canonical repo both lab hosts and the receiver pull from);
    # local-git path is a dev-only fallback.
    version_gate_enabled: bool
    version_gate_window: int
    version_gate_forgejo_url: str | None
    version_gate_repo_owner: str | None
    version_gate_repo_name: str | None
    version_gate_branch: str
    version_gate_auth_token: str | None
    version_gate_local_repo: Path | None
    # Per-host doctor snapshots (PUT /v1/host-health/<host>). Disabled
    # if unset — the receiver returns 404. Default points alongside
    # the index in /var/lib/cis490 since that's the receiver's only
    # persistent writable area under hardening.
    health_root: Path | None

    @classmethod
    def load(cls, path: str | Path) -> "ReceiverConfig":
        with open(path, "rb") as f:
            data = tomllib.load(f)

        listen_addr = data.get("listen_addr", "127.0.0.1:8443")
        host, _, port = listen_addr.rpartition(":")
        version_gate = data.get("version_gate", {})
        local_repo = version_gate.get("local_repo_path")
        return cls(
            listen_host=host or "127.0.0.1",
            listen_port=int(port),
            store_root=Path(data["store_root"]).resolve(),
            incoming_root=Path(data["incoming_root"]).resolve(),
            index_path=Path(data["index_path"]).resolve(),
            max_episode_bytes=int(
                data.get("limits", {}).get("max_episode_bytes", DEFAULT_MAX_EPISODE_BYTES)
            ),
            bearer_token=data.get("auth", {}).get("bearer_token"),
            version_gate_enabled=bool(version_gate.get("enabled", True)),
            version_gate_window=int(version_gate.get("window", 100)),
            version_gate_forgejo_url=version_gate.get("forgejo_url"),
            version_gate_repo_owner=version_gate.get("repo_owner"),
            version_gate_repo_name=version_gate.get("repo_name"),
            version_gate_branch=version_gate.get("branch", "main"),
            version_gate_auth_token=version_gate.get("auth_token"),
            version_gate_local_repo=Path(local_repo).resolve() if local_repo else None,
            health_root=(
                Path(data["health_root"]).resolve()
                if "health_root" in data
                else Path("/var/lib/cis490/host-health").resolve()
            ),
        )
