"""Digest authority derived from exact Telegram and profile evidence."""

from __future__ import annotations

import hashlib
import json
from pathlib import Path
from typing import Any


def consent_receipt_digest(*, session: Any, query: Any, message: Any) -> str:
    return hashlib.sha256(
        json.dumps(
            {
                "chat_id": session.chat_id,
                "topic_id": getattr(message, "message_thread_id", None),
                "customer_user_id": getattr(
                    getattr(query, "from_user", None),
                    "id",
                    None,
                ),
                "consent_card_message_id": getattr(message, "message_id", None),
                "bootstrap_generation": session.generation,
                "notice_version": "privacy-v1",
            },
            sort_keys=True,
            separators=(",", ":"),
        ).encode()
    ).hexdigest()


def feature_epoch_digest(*, profile_root: Path, customer_key: str) -> str:
    path = (
        profile_root
        / "data"
        / "customers"
        / customer_key
        / "nutrition-plans"
        / "feature-epoch.json"
    )
    if not path.exists() and not path.is_symlink():
        disabled_epoch = {
            "epoch": 0,
            "analytics_shadow": False,
            "operator_candidates": False,
            "activation": False,
            "delivery": False,
        }
        return hashlib.sha256(
            json.dumps(
                disabled_epoch,
                ensure_ascii=False,
                sort_keys=True,
                separators=(",", ":"),
            ).encode("utf-8")
        ).hexdigest()
    value = json.loads(path.read_text(encoding="utf-8"))
    configured = value.get("config_digest") if isinstance(value, dict) else None
    if isinstance(configured, str) and len(configured) == 64:
        return configured
    return hashlib.sha256(path.read_bytes()).hexdigest()
