#!/usr/bin/env python3
"""Independent static-seal and optional final-capture verifier."""
from __future__ import annotations
import hashlib, json, os, stat, struct, sys, zlib
from pathlib import Path
from typing import NoReturn
from PIL import Image

ROOT = Path(__file__).resolve().parent
SELF_EXCLUDED = {"inventory.json", "SEAL.json", "independent-verification.json", "capture-receipt.redacted.json"}

def sha(data: bytes) -> str: return hashlib.sha256(data).hexdigest()
def fail(message: str) -> NoReturn: raise RuntimeError(message)
def read_regular(path: Path, mode: int | None = None) -> bytes:
    fd = os.open(path, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW)
    try:
        st = os.fstat(fd)
        if not stat.S_ISREG(st.st_mode) or (mode is not None and stat.S_IMODE(st.st_mode) != mode): fail(f"unsafe mode/type: {path.name}")
        chunks=[]
        while True:
            part=os.read(fd, 65536)
            if not part: break
            chunks.append(part)
        return b"".join(chunks)
    finally: os.close(fd)
def canonical(v: object) -> bytes: return (json.dumps(v, ensure_ascii=True, sort_keys=True, separators=(",", ":"))+"\n").encode()
def image_header(data: bytes) -> tuple[str,int,int]:
    if data.startswith(b"\x89PNG\r\n\x1a\n") and len(data)>=24:
        width,height=struct.unpack(">II",data[16:24]); return "PNG",width,height
    if data.startswith(b"\xff\xd8"):
        pos=2
        while pos+4<=len(data):
            if data[pos]!=255: pos+=1; continue
            while pos<len(data) and data[pos]==255: pos+=1
            if pos>=len(data): break
            marker=data[pos]; pos+=1
            if marker in {0xD8,0xD9} or 0xD0<=marker<=0xD7: continue
            if pos+2>len(data): break
            length=struct.unpack(">H",data[pos:pos+2])[0]
            if marker in {0xC0,0xC1,0xC2,0xC3,0xC5,0xC6,0xC7,0xC9,0xCA,0xCB,0xCD,0xCE,0xCF} and pos+7<=len(data):
                height,width=struct.unpack(">HH",data[pos+3:pos+7]); return "JPEG",width,height
            pos+=length
    fail("unrecognized image")
def verify() -> dict[str, object]:
    inventory=json.loads(read_regular(ROOT/"inventory.json",0o600)); seal=json.loads(read_regular(ROOT/"SEAL.json",0o600))
    if inventory.get("schema")!="task26-customer-surface-capture-inventory-v1" or seal.get("schema")!="task26-customer-surface-capture-seal-v1": fail("seal schema mismatch")
    if sha(canonical(inventory))!=seal.get("inventory_sha256"): fail("inventory digest mismatch")
    for entry in inventory["entries"]:
        path=ROOT/entry["path"]; raw=read_regular(path, int(entry["mode"],8))
        if len(raw)!=entry["bytes"] or sha(raw)!=entry["sha256"]: fail(f"sealed artifact mismatch: {entry['path']}")
    contract=json.loads(read_regular(ROOT/"capture-contract.json",0o600))
    if sha(read_regular(ROOT/"capture-contract.json",0o600))!=seal["contract_sha256"]: fail("contract digest mismatch")
    receipt_path=ROOT/"capture-receipt.redacted.json"
    result: dict[str, object]={"schema":"task26-customer-surface-independent-verification-v1","sealed_harness":"PASS","final_capture":"AWAITING_IMAGE","status":"PASS_AWAITING_FINAL_RUN_IMAGE"}
    if receipt_path.exists() or receipt_path.is_symlink():
        receipt=json.loads(read_regular(receipt_path,0o600)); capture=receipt.get("capture",{})
        if receipt.get("binding")!=contract.get("binding") or receipt.get("contract_sha256")!=seal["contract_sha256"]: fail("receipt binding mismatch")
        if receipt.get("privacy")!={"chat_attachment_is_filesystem_evidence":False,"customer_answers_in_json":False,"image_is_protected_evidence":True,"ocr_performed":False,"raw_delivered_text_in_json":False}: fail("privacy receipt mismatch")
        image_path=ROOT/capture.get("vault_path","")
        if image_path.parent!=ROOT/"vault": fail("vault path escape")
        data=read_regular(image_path,0o600)
        fmt,width,height=image_header(data)
        with Image.open(image_path) as image:
            image.load(); decoded=(image.format,image.width,image.height,image.mode)
        if sha(data)!=capture.get("image_sha256") or len(data)!=capture.get("image_bytes") or (fmt,width,height)!= (capture.get("image_format"),capture.get("image_width"),capture.get("image_height")) or decoded!=(fmt,width,height,capture.get("image_mode")): fail("captured image mismatch")
        if receipt.get("operator_attestation",{}).get("exactly_one_visible_message") is not True or receipt["operator_attestation"].get("matches_durable_delivered_text") is not True: fail("attestation missing")
        result.update(final_capture="PASS",status="PASS_CAPTURE_VERIFIED",image_sha256=sha(data))
    return result
if __name__=="__main__":
    try:
        result=verify(); print(json.dumps(result,sort_keys=True,separators=(",",":")))
    except Exception as exc:
        print(f"verification failed: {exc}",file=sys.stderr); raise SystemExit(2)
