from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Any, Mapping

import tomllib


@dataclass(frozen=True)
class Config:
    listening_addr: str
    listening_port: int
    secret: str


def _read_toml(path: Path) -> Mapping[str, Any]:
    with path.open("rb") as handle:
        return tomllib.load(handle)


def read_config(
    config_path: str = "config.toml",
    secret_config_path: str = "secret-config.toml",
) -> Config:
    config_data = _read_toml(Path(config_path))
    secret_data = _read_toml(Path(secret_config_path))

    addr = str(config_data.get("listening_addr", "127.0.0.1"))
    port_raw = config_data.get("listening_port", 9000)
    try:
        port = int(port_raw)
    except (TypeError, ValueError) as exc:
        raise ValueError(f"Invalid listening_port value {port_raw!r}") from exc

    secret = secret_data.get("secret")
    if not secret:
        raise ValueError("Missing secret in secret-config.toml")

    return Config(
        listening_addr=addr,
        listening_port=port,
        secret=str(secret),
    )
