"""
Settings manager — luu/doc cau hinh tai ~/.sora-tool/settings.json
"""
from __future__ import annotations

import json

from .constants import APP_DATA_DIR

SETTINGS_FILE = APP_DATA_DIR / "settings.json"


def load_settings() -> dict:
    if not SETTINGS_FILE.exists():
        return {}
    return json.loads(SETTINGS_FILE.read_text(encoding="utf-8"))


def save_settings(settings: dict) -> None:
    APP_DATA_DIR.mkdir(parents=True, exist_ok=True)
    SETTINGS_FILE.write_text(
        json.dumps(settings, indent=2, ensure_ascii=False),
        encoding="utf-8",
    )


def validate_settings(settings: dict) -> None:
    """Raise ValueError neu thieu cac truong bat buoc."""
    required = {
        "username": "Username",
        "backend_key": "Backend key",
        "profiles": "Danh sach profiles",
    }
    missing = [label for key, label in required.items() if not settings.get(key)]
    if missing:
        raise ValueError(
            f"Thieu cau hinh: {', '.join(missing)}. "
            "Vui long chay `sora setup` truoc."
        )
