"""
AmunPy — Digest verification for AMUN snapshot payloads.

This module validates xxhash digests stored in AMUN snapshot XML metadata.
It provides configurable policies for how to handle mismatches.
"""

from __future__ import annotations

from typing import Optional, Literal

DigestPolicy = Literal["ignore", "warn", "raise"]


class DigestError(RuntimeError):
    """Raised when digest verification fails under a strict policy."""


def compute_digest(data: bytes, hash_type: str) -> str:
    import xxhash

    ht = str(hash_type).strip().lower()
    if ht == "xxh64":
        return xxhash.xxh64(data).hexdigest()
    if ht == "xxh3":
        return xxhash.xxh3_64(data).hexdigest()

    raise ValueError(f"Unsupported digest_type={hash_type!r}")


def verify_digest(
    *,
    data: bytes,
    expected: str,
    hash_type: str,
    filename: Optional[str] = None,
    label: str = "digest",
    policy: DigestPolicy = "warn",
) -> None:
    """
    Verify that `expected` matches digest(data) for the given hash_type.

    - policy="ignore": no-op
    - policy="warn": print a warning message on mismatch
    - policy="raise": raise DigestError on mismatch
    """
    pol = str(policy).strip().lower()
    if pol == "ignore":
        return

    expected_norm = str(expected).strip().lower()
    got = compute_digest(data, hash_type)

    if got == expected_norm:
        return

    where = f"File '{filename}'" if filename else "Payload"
    msg = (
        f"{where} failed {label} verification ({hash_type}): "
        f"expected={expected_norm} got={got}"
    )

    if pol == "warn":
        # keep it simple and dependency-free; can later swap to warnings.warn
        print(msg)
        return

    if pol == "raise":
        raise DigestError(msg)

    raise ValueError(f"Unsupported digest policy: {policy!r}")
