"""Server configuration: read/write server.toml."""

from __future__ import annotations

import secrets
import tomllib
from dataclasses import dataclass, field, fields
from pathlib import Path

from icarus.utils.toml import save_toml

SERVER_DIR = Path.home() / ".icarus" / "server"
DEFAULT_CONFIG_PATH = Path.home() / ".icarus" / "server.toml"


@dataclass
class AuthConfig:
    local: bool = True
    signing_algorithm: str = "ES256"
    access_token_ttl: int = 900        # 15 minutes
    refresh_token_ttl: int = 2592000   # 30 days


@dataclass
class ServerConfig:
    name: str = "Icarus Server"
    port: int = 8642
    bind: str = "0.0.0.0"
    token: str = ""
    logo: str = ""
    daemon_mode: str = "none"  # "none" | "user" | "system"
    auth: AuthConfig = field(default_factory=AuthConfig)


def read_config(path: Path | None = None) -> ServerConfig | None:
    """Read server.toml and return a ServerConfig, or None if file doesn't exist."""
    p = path or DEFAULT_CONFIG_PATH
    if not p.exists():
        return None
    with open(p, "rb") as f:
        raw = tomllib.load(f)
    server = raw.get("server", {})
    daemon = raw.get("daemon", {})
    auth_raw = raw.get("auth", {})
    auth = AuthConfig(
        local=auth_raw.get("local", True),
        signing_algorithm=auth_raw.get("signing_algorithm", "ES256"),
        access_token_ttl=auth_raw.get("access_token_ttl", 900),
        refresh_token_ttl=auth_raw.get("refresh_token_ttl", 2592000),
    )
    return ServerConfig(
        name=server.get("name", "Icarus Server"),
        port=server.get("port", 8642),
        bind=server.get("bind", "0.0.0.0"),
        token=server.get("token", ""),
        logo=server.get("logo", ""),
        daemon_mode=daemon.get("mode", "none"),
        auth=auth,
    )


def write_config(config: ServerConfig, path: Path | None = None) -> None:
    """Write a ServerConfig to server.toml."""
    p = path or DEFAULT_CONFIG_PATH
    data = {
        "server": {
            f.name: getattr(config, f.name)
            for f in fields(config)
            if f.name not in ("daemon_mode", "auth")
        },
        "daemon": {"mode": config.daemon_mode},
        "auth": {
            f.name: getattr(config.auth, f.name)
            for f in fields(config.auth)
        },
    }
    save_toml(p, data)


def generate_token() -> str:
    """Generate a secure random bearer token."""
    return secrets.token_urlsafe(32)
