"""发布遥测的确定性标识与可轮换 HMAC 伪名。"""

from __future__ import annotations

import hashlib
import hmac
import json
import uuid
from typing import Any

from app.core.agent_release_telemetry_keys import (
    active_agent_release_telemetry_key_version,
    available_agent_release_telemetry_key_versions,
    get_agent_release_telemetry_key,
)


def deterministic_fingerprint(*parts: Any) -> str:
    payload = "\x1f".join(str(item) for item in parts)
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def release_pseudonym_fingerprint(domain: str, *parts: Any, version: str | None = None) -> str:
    key_version = version or active_agent_release_telemetry_key_version()
    key = get_agent_release_telemetry_key(key_version, create=version is None)
    payload = "\x1f".join(("agent-release-telemetry:v1", domain, *(str(item) for item in parts)))
    return hmac.new(key, payload.encode("utf-8"), hashlib.sha256).hexdigest()


def release_source_fingerprint(*, tenant_id: str, source_key: str, rule_code: str) -> str:
    """使用当前版本密钥生成不可字典反推的租户内业务来源伪名。"""

    return release_pseudonym_fingerprint(
        "expense-claim-risk-source",
        tenant_id,
        source_key,
        rule_code,
    )


def release_source_fingerprints(*, tenant_id: str, source_key: str, rule_code: str) -> set[str]:
    """轮换期间同时核验仍保留的历史密钥，避免在途样本失联。"""

    return {
        release_pseudonym_fingerprint(
            "expense-claim-risk-source",
            tenant_id,
            source_key,
            rule_code,
            version=version,
        )
        for version in available_agent_release_telemetry_key_versions()
    }


def json_fingerprint(payload: dict[str, Any]) -> str:
    serialized = json.dumps(
        payload,
        ensure_ascii=False,
        sort_keys=True,
        separators=(",", ":"),
    )
    return hashlib.sha256(serialized.encode("utf-8")).hexdigest()


def stable_uuid(key: str) -> str:
    return str(uuid.uuid5(uuid.NAMESPACE_URL, f"x-financial:{key}"))
