#!/usr/bin/env python3
"""Read-only package verification independent of the mesh generation steps."""
from pathlib import Path
import argparse
import hashlib
import json
import xml.etree.ElementTree as ET


def digest(p):
    return hashlib.sha256(p.read_bytes()).hexdigest()


def verify(out, hash_only=False):
    manifest = json.loads((out / "MANIFEST.json").read_text())
    assert manifest["status"] == "PROPOSED_DESIGN_CANDIDATE_NOT_ENGINE_VERIFIED"
    assert manifest["blender_executed"] is False and manifest["unreal_executed"] is False
    assert manifest["issue_gate_issuable"] is False
    present = {p.relative_to(out).as_posix() for p in out.rglob("*") if p.is_file() and p.name != "MANIFEST.json"}
    assert present == set(manifest["files"]), "Manifest file-set mismatch"
    for rel, rec in manifest["files"].items():
        p = out / rel
        assert p.resolve().is_relative_to(out.resolve()), "Escaping manifest path"
        assert p.stat().st_size == rec["bytes"] and digest(p) == rec["sha256"], rel
        assert p.stat().st_size < 25 * 1024 * 1024, "Static-host limit: " + rel
    obj = next(out.glob("*.obj"))
    vertices, faces, objects = [], 0, 0
    for line in obj.read_text().splitlines():
        if line.startswith("v "):
            p = [float(v) for v in line.split()[1:]]
            assert len(p) == 3
            vertices.append(p)
        elif line.startswith("o "):
            objects += 1
        elif line.startswith("f "):
            ids = [int(v) for v in line.split()[1:]]
            assert len(ids) == 3 and min(ids) >= 1 and max(ids) <= len(vertices)
            faces += 1
    checks = json.loads((out / "GEOMETRY_CHECKS.json").read_text())
    assert checks["verification"] == "PASS", "Generated geometry check failed"
    assert checks["objects"] == objects and checks["triangles"] == faces
    for axis in range(3):
        assert abs(min(p[axis] for p in vertices) - checks["mesh_extent_m"]["min"][axis]) < .00001
        assert abs(max(p[axis] for p in vertices) - checks["mesh_extent_m"]["max"][axis]) < .00001
    for p in (out / "drawings").glob("*.svg"):
        assert ET.parse(p).getroot().tag.endswith("svg")
    if hash_only:
        print(json.dumps({"out":str(out),"manifest_files":len(present),"obj_vertices":len(vertices),"obj_triangles":faces,"verification":"PASS","mode":"stdlib_hash_obj_xml_only","pdf_png_visual_checks":"not_run_in_this_mode"}))
        return
    import fitz
    from PIL import Image
    pdf = fitz.open(next(out.glob("*.pdf")))
    assert len(pdf) == len(manifest["drawing_sheets"])
    assert all(page.get_text().strip() for page in pdf)
    cameras = json.loads((out / "SAVED_CAMERAS.json").read_text())
    assert cameras["model_sha256"] == digest(obj)
    assert cameras["stamp"]["contract_sha256"] == manifest["contract_sha256"]
    for camera in cameras["views"]:
        p = out / "neutral-views" / camera["render_file"]
        assert digest(p) == camera["render_sha256"]
        with Image.open(p) as im:
            assert list(im.size) == camera["resolution_px"]
            assert any(hi - lo > 20 for lo, hi in im.getextrema()), "Blank neutral render"
    print(json.dumps({"out": str(out), "manifest_files": len(present), "obj_vertices": len(vertices),
                      "obj_triangles": faces, "pdf_sheets": len(pdf), "saved_cameras": len(cameras["views"]), "verification": "PASS"}))


if __name__ == "__main__":
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("output_directories", type=Path, nargs="+")
    ap.add_argument("--hash-only", action="store_true", help="stdlib manifest/hash, OBJ and XML checks for CI; skips PDF/PNG parsing")
    a=ap.parse_args()
    for path in a.output_directories:
        verify(path,a.hash_only)
