"""管理员创建的访问 UUID 持久化存储。

位置:`data/user_data/access_uuids.json`,权限 0600。
与 secrets.json 分离,避免凭据文件过大且便于独立管理。
"""
from __future__ import annotations

import json
import logging
import os
import time
import uuid
from pathlib import Path

logger = logging.getLogger(__name__)


def _path() -> Path:
    from app.config import settings
    p = settings.data_dir / "user_data" / "access_uuids.json"
    p.parent.mkdir(parents=True, exist_ok=True)
    return p


def _load() -> list[dict]:
    p = _path()
    if p.exists():
        try:
            data = json.loads(p.read_text(encoding="utf-8"))
            if isinstance(data, list):
                return data
        except Exception as e:  # noqa: BLE001
            logger.warning("access_uuids.json malformed: %s", e)
    return []


def _save(records: list[dict]) -> list[dict]:
    p = _path()
    p.write_text(json.dumps(records, indent=2, ensure_ascii=False), encoding="utf-8")
    try:
        os.chmod(p, 0o600)
    except OSError:
        pass
    return records


def list_uuids() -> list[dict]:
    """返回所有 UUID 记录(按创建时间倒序)。"""
    records = _load()
    records.sort(key=lambda r: r.get("created_at", 0), reverse=True)
    return records


def exists(uuid: str) -> bool:
    """检查 UUID 是否存在且启用。"""
    normalized = uuid.strip()
    return any(r.get("uuid") == normalized and r.get("enabled", True) for r in _load())


def create(label: str = "") -> dict:
    """创建一个新的访问 UUID。"""
    records = _load()
    new_uuid = str(uuid.uuid4())
    record = {
        "uuid": new_uuid,
        "label": (label or "").strip(),
        "enabled": True,
        "created_at": int(time.time()),
    }
    records.append(record)
    _save(records)
    return record


def delete(uuid: str) -> bool:
    """删除指定 UUID。"""
    records = _load()
    original_len = len(records)
    records = [r for r in records if r.get("uuid") != uuid.strip()]
    if len(records) == original_len:
        return False
    _save(records)
    return True


def toggle(uuid: str, enabled: bool) -> bool:
    """启用/禁用指定 UUID。"""
    records = _load()
    found = False
    for r in records:
        if r.get("uuid") == uuid.strip():
            r["enabled"] = enabled
            found = True
            break
    if not found:
        return False
    _save(records)
    return True
