"""
AIIR internal — human-readable verification explanations.

Translates technical verification results into plain-English narratives
that non-cryptography users can understand and act on.

Copyright 2025-2026 Invariant Systems, Inc.
SPDX-License-Identifier: Apache-2.0
"""

from __future__ import annotations

from typing import Any, Dict, List


def explain_verification(result: Dict[str, Any]) -> str:
    """Return a human-readable explanation of a verification result.

    Covers:
    - Why it passed (what was checked, what guarantees hold)
    - Why it failed (what specifically broke, what it means, what to do)
    - Schema warnings (structural issues that don't break integrity)
    """
    lines: List[str] = []
    valid = result.get("valid", False)
    errors = result.get("errors", [])
    schema_errors = result.get("schema_errors", [])

    if valid:
        lines.append("VERIFICATION PASSED")
        lines.append("")
        lines.append("What was checked:")
        lines.append(
            "  1. Recomputed the SHA-256 hash of the receipt's core fields"
            " (type, schema, version, commit, ai_attestation, provenance)."
        )
        lines.append(
            "  2. Compared the recomputed content_hash against the stored value"
            " — they match."
        )
        lines.append("  3. Derived receipt_id from the same hash — it matches.")
        lines.append("")
        lines.append("What this means:")
        lines.append(
            "  The receipt has not been modified since it was created."
            " The commit metadata, AI attestation, and provenance are"
            " exactly as recorded. Any change — even a single character —"
            " would break the hash."
        )
        lines.append("")
        lines.append("What this does NOT prove:")
        lines.append(
            "  Integrity only proves the receipt hasn't been tampered with."
            " It does not prove WHO generated it. For authenticity, verify"
            " a Sigstore signature (--verify-signature)."
        )
    else:
        lines.append("VERIFICATION FAILED")
        lines.append("")

        # Categorize failures
        has_hash_mismatch = "content hash mismatch" in errors
        has_id_mismatch = "receipt_id mismatch" in errors
        has_type_error = any("unknown receipt type" in e for e in errors)
        has_schema_error = any("unknown schema" in e for e in errors)
        has_version_error = any("invalid version" in e for e in errors)
        has_nested_error = any("too deeply nested" in e for e in errors)
        has_not_dict = any("not a dict" in e for e in errors)

        if has_not_dict:
            lines.append("Problem: The input is not a valid receipt.")
            lines.append(
                "  AIIR receipts are JSON objects (dictionaries)."
                " This input is a different data type."
            )
            lines.append("")
            lines.append("What to do:")
            lines.append(
                "  Check that the file contains a JSON object (starts with {)"
                " or an array of objects (starts with [)."
            )

        elif has_type_error or has_schema_error:
            lines.append("Problem: This doesn't look like an AIIR receipt.")
            lines.append("")
            if has_type_error:
                rtype = "unknown"
                for e in errors:
                    if "unknown receipt type" in e:
                        rtype = e.split(":")[-1].strip().strip("'\"")
                lines.append(f"  Expected type 'aiir.commit_receipt', found: {rtype}")
            if has_schema_error:
                lines.append(
                    "  The schema field is missing or doesn't start with 'aiir/'."
                )
            lines.append("")
            lines.append("What to do:")
            lines.append(
                "  Verify this file was generated by AIIR (aiir CLI, GitHub Action,"
                " or MCP server). Receipts from other tools cannot be verified here."
            )

        elif has_version_error:
            lines.append("Problem: The version field contains invalid characters.")
            lines.append(
                "  Version must be a semver string (digits, dots, hyphens, plus signs)."
                " Special characters like HTML tags are rejected for safety."
            )

        elif has_nested_error:
            lines.append("Problem: The receipt JSON is too deeply nested.")
            lines.append(
                "  AIIR enforces a maximum nesting depth of 64 to prevent"
                " denial-of-service attacks. This receipt exceeds that limit."
            )

        elif has_hash_mismatch or has_id_mismatch:
            lines.append("Problem: The receipt has been modified after creation.")
            lines.append("")
            if has_hash_mismatch and has_id_mismatch:
                lines.append(
                    "  Both content_hash and receipt_id fail to match the"
                    " recomputed values. The core fields (commit data,"
                    " AI attestation, or provenance) were altered."
                )
            elif has_hash_mismatch:
                lines.append(
                    "  The content_hash does not match the recomputed hash."
                    " One or more core fields were changed."
                )
            else:  # has_id_mismatch (only remaining case)
                lines.append(
                    "  The receipt_id does not match the recomputed value."
                    " The receipt may have been re-issued with a different ID."
                )
            lines.append("")
            lines.append("What this means:")
            lines.append(
                "  The receipt's integrity seal is broken."
                " It cannot be trusted as an accurate record of the original commit."
            )
            lines.append("")
            lines.append("Common causes:")
            lines.append("  - Receipt was manually edited after generation")
            lines.append("  - Receipt was regenerated with different parameters")
            lines.append("  - File was corrupted during transfer")
            lines.append("  - Receipt was not generated by AIIR")
            lines.append("")
            lines.append("What to do:")
            lines.append(
                "  Regenerate the receipt from the original commit with `aiir -c <sha>`."
                " If the receipt was provided by a third party, request the"
                " original unmodified file."
            )
        else:
            # Generic fallback
            for e in errors:
                lines.append(f"  - {e}")

    # Schema warnings (independent of hash validity)
    if schema_errors:
        lines.append("")
        lines.append(f"Schema warnings ({len(schema_errors)}):")
        lines.append(
            "  These are structural issues that don't affect hash integrity"
            " but indicate the receipt may not conform to the specification."
        )
        for se in schema_errors[:10]:
            lines.append(f"  - {se}")
        if len(schema_errors) > 10:
            lines.append(f"  ... and {len(schema_errors) - 10} more")

    return "\n".join(lines)
