"""Agent 发布遥测伪名密钥的本地版本化存储。"""

from __future__ import annotations

import base64
import binascii
import os
import re
import secrets
from pathlib import Path

from app.core.config import SERVER_DIR

FINGERPRINT_KEY_DIRECTORY = SERVER_DIR / ".secrets" / "agent-release-telemetry"
ACTIVE_KEY_VERSION_ENV = "AGENT_RELEASE_TELEMETRY_KEY_VERSION"
DEFAULT_ACTIVE_KEY_VERSION = "v1"
KEY_BYTES = 32
_VERSION_PATTERN = re.compile(r"^[a-zA-Z0-9._-]{1,32}$")


def active_agent_release_telemetry_key_version() -> str:
    version = str(os.environ.get(ACTIVE_KEY_VERSION_ENV) or DEFAULT_ACTIVE_KEY_VERSION).strip()
    if not _VERSION_PATTERN.fullmatch(version):
        raise ValueError("Agent 发布遥测指纹密钥版本无效。")
    return version


def available_agent_release_telemetry_key_versions() -> list[str]:
    active = active_agent_release_telemetry_key_version()
    versions = {active}
    if FINGERPRINT_KEY_DIRECTORY.exists():
        for path in FINGERPRINT_KEY_DIRECTORY.glob("*.key"):
            if path.is_file() and not path.is_symlink() and _VERSION_PATTERN.fullmatch(path.stem):
                versions.add(path.stem)
    return [active, *sorted(versions - {active})]


def get_agent_release_telemetry_key(version: str, *, create: bool) -> bytes:
    normalized = str(version or "").strip()
    if not _VERSION_PATTERN.fullmatch(normalized):
        raise ValueError("Agent 发布遥测指纹密钥版本无效。")
    key_path = FINGERPRINT_KEY_DIRECTORY / f"{normalized}.key"
    if not key_path.exists():
        if not create:
            raise ValueError("Agent 发布遥测指纹密钥版本不可用。")
        _create_key_atomically(key_path)
    if key_path.is_symlink() or not key_path.is_file():
        raise ValueError("Agent 发布遥测指纹密钥文件无效。")
    os.chmod(key_path, 0o600)
    try:
        key = base64.urlsafe_b64decode(key_path.read_text(encoding="utf-8").strip())
    except (binascii.Error, ValueError, UnicodeError) as error:
        raise ValueError("Agent 发布遥测指纹密钥内容无效。") from error
    if len(key) != KEY_BYTES:
        raise ValueError("Agent 发布遥测指纹密钥长度无效。")
    return key


def _create_key_atomically(key_path: Path) -> None:
    key_path.parent.mkdir(parents=True, exist_ok=True)
    os.chmod(key_path.parent, 0o700)
    encoded = base64.urlsafe_b64encode(secrets.token_bytes(KEY_BYTES))
    try:
        descriptor = os.open(key_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    except FileExistsError:
        return
    with os.fdopen(descriptor, "wb") as stream:
        stream.write(encoded)
        stream.flush()
        os.fsync(stream.fileno())
