"""Inspect downloaded browser outputs; never runs the conversions under test."""

import hashlib
import json
from pathlib import Path

from PIL import Image
from pypdf import PdfReader

ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / "public/evidence/2026-09-06"
MARKER = "PRIVCONVERT-PUBLIC-SAMPLE-20260906"


def file_info(path):
    content = path.read_bytes()
    return {
        "file": path.name,
        "bytes": len(content),
        "sha256": hashlib.sha256(content).hexdigest(),
    }


def inspect_pdf(path):
    reader = PdfReader(path)
    text = [page.extract_text() or "" for page in reader.pages]
    return {
        **file_info(path),
        "pages": len(reader.pages),
        "textCharacters": sum(len(page) for page in text),
        "pagesWithMarker": sum(MARKER in page for page in text),
        "formFields": len(reader.get_fields() or {}),
    }


def inspect_animation(path):
    with Image.open(path) as animation:
        width, height = animation.size
        duration = 0
        for index in range(animation.n_frames):
            animation.seek(index)
            animation.load()
            duration += animation.info.get("duration", 0)
        return {
            **file_info(path),
            "width": width,
            "height": height,
            "encodedFrames": animation.n_frames,
            "durationMs": duration,
        }


results = {
    "date": "2026-09-06",
    "operator": "PrivConvert (first-party test)",
    "site": "https://privconvert.app",
    "testedCommit": "8f7181b",
    "environment": "Chrome 150.0.0.0 on macOS 15.3; one desktop browser",
    "method": "Public generated inputs selected in the live tool UI; downloaded outputs inspected with pypdf and Pillow. Native FFmpeg generated input clips only, not benchmark outputs.",
    "pdfSettings": {
        "modes": ["lossless", "images", "balanced"],
        "stripMetadata": False,
        "onlyIfSmaller": False,
        "defaultCheck": "pc-text-default.pdf used balanced with onlyIfSmaller true",
        "balancedRasterDpi": 150,
        "balancedJpegQuality": 0.8,
    },
    "animationSettings": {
        "startSeconds": 0,
        "durationSeconds": 6,
        "width": 480,
        "fps": 10,
        "webpQuality": 80,
        "note": "Same source, dimensions, requested timing, and frame rate. Not a perceptual-quality match or a comparison of every encoder. Identical frames may be combined in the encoded output.",
    },
    "pdf": [inspect_pdf(path) for path in sorted(EVIDENCE.glob("*.pdf"))],
    "animations": [
        inspect_animation(path)
        for path in sorted(EVIDENCE.iterdir())
        if path.suffix in (".webp", ".gif")
    ],
}

(EVIDENCE / "results.json").write_text(json.dumps(results, indent=2) + "\n")
print(json.dumps(results, indent=2))
