"""Independent verification of hash-chained audit logs."""

from __future__ import annotations

from typing import Any

from langchain_nobulex.audit import GENESIS_HASH, AuditEntry, _compute_hash


def verify(audit_log: list[dict[str, Any]] | list[AuditEntry]) -> bool:
    """Verify the integrity of a hash-chained audit log.

    Recomputes every hash from scratch and checks that:
    1. Each entry's hash matches its recomputed value
    2. Each entry's prev_hash matches the previous entry's hash
    3. The first entry's prev_hash is the genesis hash

    Args:
        audit_log: List of audit entries (dicts or AuditEntry objects).

    Returns:
        True if the chain is valid, False if tampered.
    """
    if not audit_log:
        return True

    entries: list[dict[str, Any]] = []
    for entry in audit_log:
        if isinstance(entry, AuditEntry):
            entries.append({
                "timestamp": entry.timestamp,
                "action": entry.action,
                "params": entry.params,
                "allowed": entry.allowed,
                "matching_rule": entry.matching_rule,
                "prev_hash": entry.prev_hash,
                "hash": entry.hash,
            })
        else:
            entries.append(entry)

    for i, entry in enumerate(entries):
        expected_prev = entries[i - 1]["hash"] if i > 0 else GENESIS_HASH

        if entry["prev_hash"] != expected_prev:
            return False

        expected_hash = _compute_hash(
            entry["prev_hash"],
            entry["timestamp"],
            entry["action"],
            entry["params"],
            entry["allowed"],
            entry["matching_rule"],
        )

        if entry["hash"] != expected_hash:
            return False

    return True
