"""租户登录全局开关 — control/tenant_auth.yaml。"""

from __future__ import annotations

from pathlib import Path
from typing import Any

import yaml


class TenantAuthSettings:
    def __init__(self, home: Path) -> None:
        self._home = Path(home)
        self._path = self._home / "control" / "tenant_auth.yaml"
        self._path.parent.mkdir(parents=True, exist_ok=True)

    @property
    def path(self) -> Path:
        return self._path

    def _load(self) -> dict[str, Any]:
        if not self._path.is_file():
            return {}
        with self._path.open(encoding="utf-8") as f:
            data = yaml.safe_load(f) or {}
        return data if isinstance(data, dict) else {}

    def login_enabled(self, config: dict[str, Any]) -> bool:
        file_val = self._load().get("login_enabled")
        if file_val is not None:
            return bool(file_val)
        tenant_auth = config.get("tenant_auth") or {}
        if isinstance(tenant_auth, dict):
            return bool(tenant_auth.get("login_enabled", True))
        return True

    def set_login_enabled(self, enabled: bool) -> bool:
        payload = {"login_enabled": bool(enabled)}
        with self._path.open("w", encoding="utf-8") as f:
            yaml.safe_dump(payload, f, allow_unicode=True, default_flow_style=False, sort_keys=False)
        return bool(enabled)
