# -*- coding: utf-8 -*-
"""OK ITHAKI server settings.

Environment variables remain authoritative. A small JSON runtime file is used
only for values explicitly changed through the server admin API.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import json
import os

ROOT = Path(__file__).resolve().parent
RUNTIME_CONFIG_FILE = ROOT / "relay_runtime_config.json"


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


def _env_int(name: str, default: int) -> int:
    try:
        return int(os.getenv(name, str(default)))
    except Exception:
        return default


def _runtime() -> dict:
    try:
        if RUNTIME_CONFIG_FILE.exists():
            value = json.loads(RUNTIME_CONFIG_FILE.read_text(encoding="utf-8"))
            return value if isinstance(value, dict) else {}
    except Exception:
        pass
    return {}


@dataclass(frozen=True)
class Settings:
    admin_key: str
    public_api_url: str
    production_api_url: str
    public_app_token: str
    public_display_name: str
    seed_max_daily: int
    enable_internal_seed_thread: bool
    seed_cron_min_interval_seconds: int
    seed_loop_seconds: int


def get_settings() -> Settings:
    rt = _runtime()
    return Settings(
        admin_key=os.getenv("ITHAKI_ADMIN_KEY", "local-beta-admin"),
        public_api_url=os.getenv("ITHAKI_PUBLIC_API_URL", str(rt.get("active_api_url") or rt.get("public_api_url") or "https://ok-ithaki.gr")),
        production_api_url=os.getenv("ITHAKI_PRODUCTION_API_URL", str(rt.get("production_api_url") or "https://ok-ithaki.gr")),
        public_app_token=os.getenv("ITHAKI_PUBLIC_APP_TOKEN", str(rt.get("public_app_token") or "OKITHAKI_PUBLIC_BETA_TOKEN_CHANGE_ON_SERVER")),
        public_display_name=os.getenv("ITHAKI_PUBLIC_DISPLAY_NAME", str(rt.get("public_display_name") or "OK ITHAKI")),
        seed_max_daily=_env_int("ITHAKI_SEED_MAX_DAILY", int(rt.get("seed_max_daily") or 24)),
        enable_internal_seed_thread=_env_bool("ITHAKI_ENABLE_INTERNAL_SEED_THREAD", bool(rt.get("enable_internal_seed_thread", False))),
        seed_cron_min_interval_seconds=_env_int("ITHAKI_SEED_CRON_MIN_INTERVAL_SECONDS", int(rt.get("seed_cron_min_interval_seconds") or 300)),
        seed_loop_seconds=_env_int("ITHAKI_SEED_LOOP_SECONDS", int(rt.get("seed_loop_seconds") or 300)),
    )


def save_runtime_config(changes: dict) -> dict:
    current = _runtime()
    if isinstance(changes, dict):
        for key, value in changes.items():
            if value is not None:
                current[str(key)] = value
    tmp = RUNTIME_CONFIG_FILE.with_suffix(".tmp")
    tmp.write_text(json.dumps(current, ensure_ascii=False, indent=2), encoding="utf-8")
    tmp.replace(RUNTIME_CONFIG_FILE)
    return current


def public_bootstrap_config() -> dict:
    st = get_settings()
    return {
        "active_api_url": st.public_api_url,
        "default_api_url": st.public_api_url,
        "production_api_url": st.production_api_url,
        "public_app_token": st.public_app_token,
        "public_display_name": st.public_display_name,
        "show_connection_settings_to_user": False,
        "allow_user_relay_edit": False,
        "auto_login_enabled": True,
        "require_name": False,
        "require_login": False,
        "require_profile": False,
        "default_room_id": "ithaki-phone-test",
    }
