#!/usr/bin/env python3
"""Verify a VoxDrop profile-3 AI marking against a trusted public Ed25519 key.

Usage: python verify_ai_marking.py document.pdf public-key.pem
Dependencies: pip install pypdf cryptography
Profile 3 covers the exact delivered file. Editing or re-saving invalidates it.
"""
from __future__ import annotations

import argparse
import base64
import hashlib
import hmac
import io
from pathlib import Path
import re
import sys
import xml.etree.ElementTree as ET

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from pypdf import PdfReader
from pypdf.errors import PdfReadError

PROFILE = "voxdrop-ai-marking/3"
NS = {
    "vdai": "https://voxdrop.live/ns/ai/1.0/",
    "xmp": "http://ns.adobe.com/xap/1.0/",
    "iptc": "http://iptc.org/std/Iptc4xmpExt/2008-02-29/",
    "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
}


class VerificationError(ValueError):
    """The file has no valid complete-file marking under the supplied key."""


class UnsupportedProfile(VerificationError):
    """An old marking must not be mistaken for complete-file integrity."""


def one_element(root: ET.Element, namespace: str, name: str) -> ET.Element:
    matches = list(root.iter("{" + NS[namespace] + "}" + name))
    if len(matches) != 1:
        raise VerificationError(f"Metadatenfeld fehlt oder ist mehrdeutig: {name}")
    return matches[0]


def field(root: ET.Element, namespace: str, name: str) -> str:
    element = one_element(root, namespace, name)
    if len(element):
        raise VerificationError(f"Unerwartete Struktur im Metadatenfeld: {name}")
    return (element.text or "").strip()


def metadata_of(raw: bytes) -> tuple[bytes, ET.Element]:
    try:
        reader = PdfReader(io.BytesIO(raw), strict=True)
        if reader.is_encrypted:
            raise VerificationError("Verschlüsselte Dateien werden nicht unterstützt.")
        stream = reader.trailer["/Root"]["/Metadata"].get_object()
        if stream.get("/Filter") is not None:
            raise VerificationError("Profil 3 verlangt ein unkomprimiertes XMP-Paket.")
        packet = stream.get_data()
    except (KeyError, AttributeError, PdfReadError) as error:
        raise VerificationError("Das PDF besitzt kein lesbares XMP-Paket.") from error
    if not packet or len(packet) > 1024 * 1024 or raw.count(packet) != 1:
        raise VerificationError("Das XMP-Paket fehlt, ist zu groß oder liegt mehrfach vor.")
    if re.search(br"<!\s*(?:DOCTYPE|ENTITY)\b", packet, re.IGNORECASE):
        raise VerificationError("DTD und Entitäten sind in diesem Profil nicht erlaubt.")
    try:
        return packet, ET.fromstring(packet)
    except ET.ParseError as error:
        raise VerificationError("Das XMP-Paket ist kein gültiges XML.") from error


def value_slot(packet: bytes, name: str, length: int) -> tuple[int, int]:
    opening = f"<vdai:{name}>".encode("ascii")
    closing = f"</vdai:{name}>".encode("ascii")
    if packet.count(opening) != 1 or packet.count(closing) != 1:
        raise VerificationError(f"Signaturfeld fehlt oder ist mehrdeutig: {name}")
    start = packet.index(opening) + len(opening)
    end = packet.index(closing)
    if end - start != length:
        raise VerificationError(f"Falsche Länge des Signaturfelds: {name}")
    return start, end


def file_digest(raw: bytes, packet: bytes) -> str:
    packet_start = raw.index(packet)
    slots = sorted(value_slot(packet, name, length) for name, length in [("contentSha256", 64), ("signature", 88)])
    if slots[0][1] > slots[1][0]:
        raise VerificationError("Signaturfelder überlappen sich.")
    digest = hashlib.sha256()
    view = memoryview(raw)
    cursor = 0
    for start, end in slots:
        digest.update(view[cursor:packet_start + start])
        digest.update(b"0" * (end - start))
        cursor = packet_start + end
    digest.update(view[cursor:])
    return digest.hexdigest()


def verify_pdf(raw: bytes, public_key_pem: bytes) -> dict[str, object]:
    packet, root = metadata_of(raw)
    if not list(root.iter("{" + NS["vdai"] + "}signatureProfile")) and list(root.iter("{" + NS["vdai"] + "}signature")):
        raise UnsupportedProfile("Die ältere Signatur ohne Profilangabe belegt keine vollständige Dateiintegrität.")
    profile = field(root, "vdai", "signatureProfile")
    if profile != PROFILE:
        raise UnsupportedProfile("Dieses Profil belegt keine vollständige Dateiintegrität; erforderlich ist Profil 3.")
    content = field(root, "vdai", "contentSha256")
    encoded_signature = field(root, "vdai", "signature")
    key_id = field(root, "vdai", "signatureKey")
    source_type = field(root, "iptc", "DigitalSourceType")
    created = field(root, "xmp", "CreateDate")
    parts_element = one_element(root, "vdai", "generatedParts")
    bags = parts_element.findall("{" + NS["rdf"] + "}Bag")
    if len(bags) != 1 or len(parts_element) != 1:
        raise VerificationError("Die Liste der Modellteile ist mehrdeutig.")
    parts = [(item.text or "").strip() for item in bags[0]]
    allowed = ["overview", "orientation", "image-description", "image-text"]
    if (parts != [name for name in allowed if name in parts]
            or any(item.tag != "{" + NS["rdf"] + "}li" or len(item) for item in bags[0])):
        raise VerificationError("Die Liste der Modellteile ist ungültig.")
    source_elements = list(root.iter("{" + NS["vdai"] + "}sourceMarkings"))
    source_markings = []
    if source_elements:
        source = one_element(root, "vdai", "sourceMarkings")
        source_bags = source.findall("{" + NS["rdf"] + "}Bag")
        if len(source_bags) != 1 or len(source) != 1:
            raise VerificationError("Die Quellmarkierungen sind mehrdeutig.")
        source_markings = [(item.text or "").strip() for item in source_bags[0]]
        pattern = r"(?:trainedAlgorithmicMedia|compositeWithTrainedAlgorithmicMedia|algorithmicMedia|compositeSynthetic)\|(?:document|slide:[1-9][0-9]{0,3}|page:[1-9][0-9]{0,4})\|(?:xmp|c2pa)"
        if (not source_markings or len(source_markings) > 200 or source_markings != sorted(set(source_markings))
                or any(not re.fullmatch(pattern, value) for value in source_markings)
                or any(item.tag != "{" + NS["rdf"] + "}li" or len(item) for item in source_bags[0])):
            raise VerificationError("Die Quellmarkierungen sind ungültig.")
    if not parts and not source_markings:
        raise VerificationError("Die Datei enthält keine KI-Kennzeichnung.")
    if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,39}", key_id) or not re.fullmatch(r"[0-9a-f]{64}", content):
        raise VerificationError("Schlüsselname oder SHA-256 ist ungültig.")
    if not hmac.compare_digest(file_digest(raw, packet), content):
        raise VerificationError("Die Datei wurde nach dem Signieren verändert.")
    try:
        signature = base64.b64decode(encoded_signature, validate=True)
        if len(signature) != 64 or base64.b64encode(signature).decode("ascii") != encoded_signature:
            raise VerificationError("Die Signaturkodierung ist ungültig.")
        key = load_pem_public_key(public_key_pem)
        if not isinstance(key, Ed25519PublicKey):
            raise VerificationError("Erforderlich ist ein öffentlicher Ed25519-Schlüssel.")
        statement = "\n".join([PROFILE, source_type, ",".join(parts), created, content, key_id])
        if source_markings:
            statement += "\n" + ",".join(source_markings)
        key.verify(signature, statement.encode("utf-8"))
    except (InvalidSignature, ValueError) as error:
        raise VerificationError("Die Signatur passt nicht zum angegebenen öffentlichen Schlüssel.") from error
    return {"profile": profile, "key_id": key_id, "parts": parts, "source_markings": source_markings, "created": created}


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("pdf", type=Path)
    parser.add_argument("public_key", type=Path, help="Vertrauenswürdiger Schlüssel, z. B. von voxdrop.live/ki-kennzeichnung")
    arguments = parser.parse_args()
    try:
        result = verify_pdf(arguments.pdf.read_bytes(), arguments.public_key.read_bytes())
    except UnsupportedProfile as error:
        print(f"Nicht unterstütztes Profil: {error}", file=sys.stderr)
        return 2
    except (VerificationError, OSError, PdfReadError) as error:
        print(f"Signatur ungültig: {error}", file=sys.stderr)
        return 1
    print(f"Signatur gültig: {result['key_id']}, Profil 3, {result['created']}, {','.join(result['parts'])}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
