from __future__ import annotations

import os
from dataclasses import dataclass


@dataclass(frozen=True)
class Config:
    token: str
    public_base_url: str
    webhook_secret: str
    listen_host: str
    listen_port: int
    sqlite_path: str
    tz: str
    web_ui_secret: str | None
    reminder_dm: bool

    @property
    def webhook_path(self) -> str:
        return f"/telegram/{self.webhook_secret}/"

    @property
    def webhook_url(self) -> str:
        return f"{self.public_base_url.rstrip('/')}{self.webhook_path}"


def load_config() -> Config:
    token = os.environ.get("TELEGRAM_BOT_TOKEN", "").strip()
    public_base_url = os.environ.get("PUBLIC_BASE_URL", "").strip()
    webhook_secret = os.environ.get("WEBHOOK_SECRET", "").strip()
    listen_host = os.environ.get("LISTEN_HOST", "127.0.0.1").strip()
    listen_port = int(os.environ.get("LISTEN_PORT", "9000"))
    sqlite_path = os.environ.get("SQLITE_PATH", "/var/lib/telegram-bot/bot.sqlite3").strip()
    tz = os.environ.get("TZ", "Europe/Bratislava").strip()
    web_ui_secret = os.environ.get("WEB_UI_SECRET", "").strip() or None
    reminder_dm = os.environ.get("REMINDER_DM", "0").strip() in {"1", "true", "yes", "on"}

    missing = [
        name
        for name, value in [
            ("TELEGRAM_BOT_TOKEN", token),
            ("PUBLIC_BASE_URL", public_base_url),
            ("WEBHOOK_SECRET", webhook_secret),
        ]
        if not value
    ]
    if missing:
        raise RuntimeError(f"Missing required env vars: {', '.join(missing)}")

    return Config(
        token=token,
        public_base_url=public_base_url,
        webhook_secret=webhook_secret,
        listen_host=listen_host,
        listen_port=listen_port,
        sqlite_path=sqlite_path,
        tz=tz,
        web_ui_secret=web_ui_secret,
        reminder_dm=reminder_dm,
    )
