from __future__ import annotations

import os
from dataclasses import dataclass
from pathlib import Path


@dataclass(frozen=True)
class Settings:
    root_aliases: dict[str, str]
    task_db_path: str
    remote_client_registration_token: str
    remote_client_offline_timeout_seconds: int
    remote_client_agent_auth_header: str
    remote_client_agent_auth_scheme: str
    remote_client_agent_auth_token: str


DEFAULT_ROOT_ALIASES = {
    "storage1": "/Volumes/8TB",
    "storage2": "/Volumes/8TB_RAID1",
}


def _load_root_aliases() -> dict[str, str]:
    # Minimal env override format: storage1=/path1,storage2=/path2
    raw = os.getenv("WEBMANAGER_ROOT_ALIASES", "").strip()
    if not raw:
        return dict(DEFAULT_ROOT_ALIASES)

    parsed: dict[str, str] = {}
    for entry in raw.split(","):
        if "=" not in entry:
            continue
        alias, root = entry.split("=", 1)
        alias = alias.strip()
        root = root.strip()
        if alias and root:
            parsed[alias] = root
    return parsed or dict(DEFAULT_ROOT_ALIASES)


def get_settings() -> Settings:
    default_task_db_path = str(Path(__file__).resolve().parents[1] / "data" / "tasks.db")
    task_db_path = os.getenv("WEBMANAGER_TASK_DB_PATH", default_task_db_path).strip()
    if not task_db_path:
        task_db_path = default_task_db_path
    raw_offline_timeout = os.getenv("WEBMANAGER_REMOTE_CLIENT_OFFLINE_TIMEOUT_SECONDS", "60").strip()
    try:
        remote_client_offline_timeout_seconds = max(1, int(raw_offline_timeout))
    except ValueError:
        remote_client_offline_timeout_seconds = 60
    return Settings(
        root_aliases=_load_root_aliases(),
        task_db_path=task_db_path,
        remote_client_registration_token=os.getenv("WEBMANAGER_REMOTE_CLIENT_REGISTRATION_TOKEN", "").strip(),
        remote_client_offline_timeout_seconds=remote_client_offline_timeout_seconds,
        remote_client_agent_auth_header=os.getenv("WEBMANAGER_REMOTE_CLIENT_AGENT_AUTH_HEADER", "Authorization").strip()
        or "Authorization",
        remote_client_agent_auth_scheme=os.getenv("WEBMANAGER_REMOTE_CLIENT_AGENT_AUTH_SCHEME", "Bearer").strip() or "Bearer",
        remote_client_agent_auth_token=os.getenv("WEBMANAGER_REMOTE_CLIENT_AGENT_AUTH_TOKEN", "").strip(),
    )
