from __future__ import annotations

import os
import secrets
from pathlib import Path

from pydantic_settings import BaseSettings, SettingsConfigDict

BASE_DIR = Path(__file__).resolve().parent.parent
DATA_DIR = Path(os.environ.get("CMS_DATA_DIR") or BASE_DIR / "data")
DATA_DIR.mkdir(parents=True, exist_ok=True)


class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_prefix="CMS_", env_file=str(BASE_DIR / ".env"), extra="ignore")

    database_url: str = "mysql+pymysql://root:@127.0.0.1:3306/classroom_management_db?charset=utf8mb4"
    secret_key: str = ""
    host: str = "0.0.0.0"
    port: int = 8443
    ssl_certfile: str = ""
    ssl_keyfile: str = ""
    access_token_minutes: int = 30
    refresh_token_days: int = 7
    wol_broadcast: str = "255.255.255.255"
    login_rate_per_min: int = 8
    offline_after_seconds: int = 25
    command_ttl_seconds: int = 300
    frontend_dist: str = str(BASE_DIR.parent / "frontend" / "dist")
    agent_dist: str = str(BASE_DIR.parent / "client-agent")
    create_tables_on_start: bool = True


settings = Settings()


def _load_secret() -> str:
    if settings.secret_key:
        return settings.secret_key
    f = DATA_DIR / "secret.key"
    if f.exists():
        return f.read_text().strip()
    key = secrets.token_urlsafe(64)
    f.write_text(key)
    try:
        f.chmod(0o600)
    except OSError:
        pass
    return key


SECRET_KEY = _load_secret()
