from __future__ import annotations

from dataclasses import dataclass
import os
from pathlib import Path


def _env_int(name: str, default: int) -> int:
    value = os.getenv(name)
    if value is None or value == "":
        return default
    return int(value)


def _env_path(name: str, default: str) -> Path:
    value = os.getenv(name)
    if value is None or value == "":
        value = default
    return Path(value)


def _env_bool(name: str, default: bool) -> bool:
    value = os.getenv(name)
    if value is None or value == "":
        return default
    return value.strip().lower() in ("1", "true", "yes", "on")


@dataclass(frozen=True)
class Config:
    bind: str
    port: int
    data_dir: Path
    db_path: Path
    storage_dir: Path
    backups_dir: Path

    cert_dir: Path | None
    cert_file: str
    key_file: str
    cert_reload_seconds: int

    session_ttl_seconds: int
    otp_ttl_seconds: int

    max_attachment_bytes: int
    upload_chunk_bytes: int

    backup_enabled: bool
    backup_interval_seconds: int
    backup_keep_daily: int
    backup_keep_monthly: int
    backup_include_storage: bool


def load_config() -> Config:
    data_dir = _env_path("CHATAPP_DATA_DIR", "./data")
    db_path = _env_path("CHATAPP_DB_PATH", str(data_dir / "app.db"))
    storage_dir = _env_path("CHATAPP_STORAGE_DIR", str(data_dir / "storage"))
    backups_dir = _env_path("CHATAPP_BACKUPS_DIR", "./backups")

    cert_dir_raw = os.getenv("CHATAPP_CERT_DIR", "").strip()
    cert_dir = Path(cert_dir_raw) if cert_dir_raw else None

    return Config(
        bind=os.getenv("CHATAPP_BIND", "127.0.0.1"),
        port=_env_int("CHATAPP_PORT", 8080),
        data_dir=data_dir,
        db_path=db_path,
        storage_dir=storage_dir,
        backups_dir=backups_dir,
        cert_dir=cert_dir,
        cert_file=os.getenv("CHATAPP_CERT_FILE", "fullchain.pem"),
        key_file=os.getenv("CHATAPP_KEY_FILE", "privkey.pem"),
        cert_reload_seconds=_env_int("CHATAPP_CERT_RELOAD_SECONDS", 300),
        session_ttl_seconds=_env_int("CHATAPP_SESSION_TTL_SECONDS", 60 * 60 * 24 * 30),
        otp_ttl_seconds=_env_int("CHATAPP_OTP_TTL_SECONDS", 60 * 60 * 24),
        max_attachment_bytes=_env_int("CHATAPP_MAX_ATTACHMENT_BYTES", 1_000_000_000),
        upload_chunk_bytes=_env_int("CHATAPP_UPLOAD_CHUNK_BYTES", 50 * 1024 * 1024),
        backup_enabled=_env_bool("CHATAPP_BACKUP_ENABLED", True),
        backup_interval_seconds=_env_int("CHATAPP_BACKUP_INTERVAL_SECONDS", 60 * 60 * 24),
        backup_keep_daily=_env_int("CHATAPP_BACKUP_KEEP_DAILY", 7),
        backup_keep_monthly=_env_int("CHATAPP_BACKUP_KEEP_MONTHLY", 1),
        backup_include_storage=_env_bool("CHATAPP_BACKUP_INCLUDE_STORAGE", True),
    )
