"""Render and account for ALPHA changes in the existing MapScene golden catalog."""

from __future__ import annotations

import argparse
import hashlib
import json
import os
from dataclasses import replace
from pathlib import Path
import subprocess
import sys

import numpy as np


def _mode_sites(scene, f3d):
    sites = set()
    for layer in scene.recipe.layers:
        if isinstance(layer, f3d.VectorOverlay):
            from forge3d._map_scene_materials import physical_vector

            sites.add("physical material paint" if physical_vector(layer) else "vector source-over")
        elif isinstance(layer, f3d.RasterOverlay):
            sites.add("terrain UV raster / physical material stack")
        elif isinstance(layer, f3d.LabelLayer):
            sites.add("native label and halo composition")
        elif isinstance(layer, f3d.MapSceneBuildingLayer):
            sites.add("building shadow / landmark texture composition")
        elif isinstance(layer, (f3d.PointCloudLayer, f3d.Tiles3DLayer)):
            sites.add("point-cloud source-over")
    if scene.recipe.map_furniture is not None:
        sites.add("map furniture and image blits")
    return sorted(sites) or ["legacy compatibility control"]


def _digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def _write_json(path, value):
    path.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8")


def _catalog(repo):
    sys.path[:0] = [str(repo / "python"), str(repo), str(repo / "tests")]
    from tests.test_recipe_goldens import RECIPE_GOLDENS

    return RECIPE_GOLDENS


def render(repo, destination, mode, fixture=None):
    catalog = _catalog(repo)
    import forge3d as f3d
    from forge3d._native import get_native_module
    from forge3d.map_scene import _shared_terrain_render_context

    assert Path(f3d.__file__).resolve().is_relative_to(repo)
    adapter = f3d.device_probe()
    assert adapter["status"] == "ok" and not adapter["software_fallback"], adapter
    if mode == "baseline":
        assert not subprocess.check_output(["git", "status", "--porcelain"], cwd=repo, text=True).strip()
    frames = {}
    receipt = {
        "head": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip(),
        "forge3d": f3d.__version__,
        "native_sha256": _digest(Path(get_native_module().__file__)),
        "adapter": adapter,
        "mode": mode,
        "frames": frames,
        "fixtures": {},
        "failures": {},
        "complete": False,
    }
    receipt_path = destination / f"{mode}.json"
    previous = {}
    if (mode == "baseline" or fixture is not None) and receipt_path.is_file():
        saved = json.loads(receipt_path.read_text(encoding="utf-8"))
        same_runtime = all(saved[key] == receipt[key] for key in ("head", "native_sha256", "adapter", "mode"))
        if fixture is not None:
            if not same_runtime:
                raise SystemExit("Fixture reruns require the same revision, native extension, and adapter")
            for key in ("fixtures", "failures"):
                receipt[key].update(saved[key])
            frames.update(saved["frames"])
        elif same_runtime:
            previous = saved["frames"]
    baseline_path = destination / "baseline.json"
    if mode != "baseline" and baseline_path.is_file():
        receipt["fixtures"].update(json.loads(baseline_path.read_text(encoding="utf-8"))["fixtures"])
    selected = False
    with _shared_terrain_render_context():
        for spec in catalog:
            if fixture is not None and spec.scene_id != fixture:
                continue
            fixture_dir = destination / "inputs" / mode / spec.scene_id
            fixture_dir.mkdir(parents=True, exist_ok=True)
            scene = spec.build(fixture_dir)
            sites = _mode_sites(scene, f3d)
            selected = True
            receipt["fixtures"][spec.scene_id] = sites
            if mode != "baseline":
                scene.recipe.output = replace(scene.recipe.output, compositing_mode=mode)
            path = destination / f"{spec.scene_id}-{mode}.png"
            existing = previous.get(spec.scene_id)
            if existing is not None and path.is_file() and _digest(path) == existing["sha256"]:
                assert scene.recipe.reproducibility_profile.seed == existing["seed"]
                frames[spec.scene_id] = {**existing, "sites": sites}
                continue
            frames.pop(spec.scene_id, None)
            receipt["failures"][spec.scene_id] = "native render started without a completion receipt"
            _write_json(receipt_path, receipt)
            print(mode, spec.scene_id, "rendering", flush=True)
            try:
                if spec.warmup_temporal:
                    scene.render(str(path))
                scene.render(str(path))
            except f3d.MapSceneNativeUnavailable as error:
                receipt["failures"][spec.scene_id] = str(error)
                print(mode, spec.scene_id, str(error), flush=True)
                _write_json(receipt_path, receipt)
                continue
            assert scene.last_render_backend == "gpu_terrain", spec.scene_id
            if mode != "baseline":
                assert scene.last_render_metadata["compositing_mode"] == mode
            frames[spec.scene_id] = {
                "sites": sites,
                "bit_depth": spec.bit_depth,
                "sha256": _digest(path),
                "seed": scene.recipe.reproducibility_profile.seed,
                "render_metadata": scene.last_render_metadata,
            }
            receipt["failures"].pop(spec.scene_id)
            print(mode, spec.scene_id, frames[spec.scene_id]["sha256"], flush=True)
            _write_json(receipt_path, receipt)
    if not selected:
        raise SystemExit(f"No recipe fixture named {fixture!r}")
    receipt["complete"] = not receipt["failures"] and set(frames) == set(receipt["fixtures"])
    _write_json(receipt_path, receipt)
    if fixture is not None:
        if failure := receipt["failures"].get(fixture):
            raise SystemExit(f"{mode}: {fixture}: {failure}")
        return
    if receipt["failures"]:
        raise SystemExit(f"{mode}: native frames unavailable for {', '.join(receipt['failures'])}")


def _rgba(image_path):
    from forge3d._png import decode_png

    payload = image_path if isinstance(image_path, bytes) else image_path.read_bytes()
    return decode_png(payload, preserve_bit_depth=True)


def _committed_golden(repo, scene_id, revision):
    relative = f"tests/golden/recipes/{scene_id}.png"
    subprocess.run(
        ["git", "ls-files", "--error-unmatch", "--", relative],
        cwd=repo, stdout=subprocess.DEVNULL, check=True,
    )
    payload = subprocess.check_output(["git", "show", f"{revision}:{relative}"], cwd=repo)
    return relative, payload


def _historical_receipt(directory, baseline, repo):
    saved = json.loads((directory / "baseline.json").read_text(encoding="utf-8"))
    assert saved["mode"] == "baseline" and saved["complete"] and not saved["failures"]
    assert saved["adapter"] == baseline["adapter"]
    assert saved["head"] != baseline["head"]
    subprocess.run(
        ["git", "merge-base", "--is-ancestor", saved["head"], baseline["head"]],
        cwd=repo, check=True,
    )
    return saved


def compare(destination, repo=None, *, catalog=None, historical_baseline=None):
    from forge3d._png import save_png

    receipts = {
        mode: json.loads((destination / f"{mode}.json").read_text(encoding="utf-8"))
        for mode in ("baseline", "legacy", "linear_light")
    }
    baseline = receipts["baseline"]
    if catalog is not None:
        assert set(baseline["fixtures"]) == {item.scene_id for item in catalog}, "Incomplete recipe catalog"
    for mode, receipt in receipts.items():
        assert receipt["mode"] == mode
        assert receipt["adapter"] == baseline["adapter"]
        assert receipt["head"] == baseline["head"]
        assert receipt["fixtures"] == baseline["fixtures"]
    assert receipts["legacy"]["native_sha256"] == receipts["linear_light"]["native_sha256"]
    historical = (
        _historical_receipt(historical_baseline, baseline, repo)
        if historical_baseline is not None else None
    )

    table = {}
    missing = {}
    for scene_id, sites in baseline["fixtures"].items():
        absent = [mode for mode, receipt in receipts.items() if scene_id not in receipt["frames"]]
        if any(mode in absent for mode in ("legacy", "linear_light")):
            missing[scene_id] = {mode: receipts[mode]["failures"].get(scene_id, "no recorded frame")
                                 for mode in absent}
            continue
        frame = receipts["legacy"]["frames"][scene_id]
        paths = {mode: destination / f"{scene_id}-{mode}.png" for mode in receipts}
        for mode, path in paths.items():
            if mode in absent:
                continue
            observed = receipts[mode]["frames"][scene_id]
            assert observed["seed"] == frame["seed"]
            assert observed["sites"] == sites
            assert _digest(path) == observed["sha256"]
        parity = None
        parity_source = None
        if "baseline" not in absent:
            parity = paths["baseline"].read_bytes() == paths["legacy"].read_bytes()
            parity_source = "clean_render"
        before = _rgba(paths["legacy"])
        after = _rgba(paths["linear_light"])
        assert before.dtype == after.dtype and before.shape == after.shape, scene_id
        bit_depth = before.dtype.itemsize * 8
        assert bit_depth == frame.get("bit_depth", bit_depth), scene_id
        delta = np.abs(after.astype(np.int32) - before).astype(before.dtype)
        changed = np.any(delta > 0, axis=-1)
        save_png(destination / f"{scene_id}-difference.png", delta[..., :3])
        if delta[..., 3].any():
            save_png(destination / f"{scene_id}-alpha-difference.png", delta[..., 3])
        table[scene_id] = {
            "sites": sites,
            "bit_depth": bit_depth,
            "pixels": int(changed.size),
            "changed_pixels": int(changed.sum()),
            "max_channel_delta": int(delta.max()),
            "legacy_png_byte_identical": parity,
            "legacy_baseline_source": parity_source,
        }
        clean_failure = baseline["failures"].get(scene_id)
        if clean_failure:
            table[scene_id]["clean_render_failure"] = clean_failure
        if repo is not None:
            reference_path, payload = _committed_golden(repo, scene_id, baseline["head"])
            reference = _rgba(payload)
            assert reference.dtype == before.dtype and reference.shape == before.shape, scene_id
            table[scene_id]["committed_golden"] = {
                "path": reference_path,
                "sha256": hashlib.sha256(payload).hexdigest(),
                "legacy_png_byte_identical": paths["legacy"].read_bytes() == payload,
                "legacy_changed_pixels": int(np.any(reference != before, axis=-1).sum()),
                "linear_light_changed_pixels": int(np.any(reference != after, axis=-1).sum()),
            }
            # A recorded clean-render failure can be resolved by exact equality
            # to the tracked, committed reference for this recipe.
            if "baseline" in absent and clean_failure and paths["legacy"].read_bytes() == payload:
                table[scene_id]["legacy_png_byte_identical"] = True
                table[scene_id]["legacy_baseline_source"] = "committed_golden"
        if (table[scene_id]["legacy_png_byte_identical"] is None and clean_failure
                and historical is not None and scene_id in historical["frames"]):
            observed = historical["frames"][scene_id]
            reference = historical_baseline / f"{scene_id}-baseline.png"
            assert observed["seed"] == frame["seed"] and observed["sites"] == sites
            assert _digest(reference) == observed["sha256"]
            table[scene_id].update(
                legacy_png_byte_identical=paths["legacy"].read_bytes() == reference.read_bytes(),
                legacy_baseline_source="historical_clean_render",
                legacy_baseline_revision=historical["head"],
                historical_reference_sha256=observed["sha256"],
            )
        if table[scene_id]["legacy_png_byte_identical"] is None:
            missing[scene_id] = {"baseline": clean_failure or "no recorded frame"}
        print(scene_id, table[scene_id], flush=True)
    assert table
    _write_json(destination / "comparison.json", table)
    _write_json(destination / "missing.json", missing)
    mismatches = [scene for scene, row in table.items() if row["legacy_png_byte_identical"] is False]
    if missing or mismatches:
        raise SystemExit(f"Incomplete ALPHA accounting. Missing: {list(missing)}. Legacy mismatches: {mismatches}.")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("mode", choices=("baseline", "legacy", "linear_light", "compare"))
    parser.add_argument("--repo", type=Path, default=Path.cwd())
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--fixture", help="Render just one recipe and retain other matching receipts")
    parser.add_argument("--historical-baseline", type=Path,
                        help="Compare unavailable clean fixtures against a verified clean ancestor capture")
    args = parser.parse_args()
    path = args.output.resolve()
    path.mkdir(parents=True, exist_ok=True)
    if args.mode == "compare":
        if args.fixture is not None:
            parser.error("--fixture applies to rendering only")
        repo = args.repo.resolve()
        compare(path, repo, catalog=_catalog(repo), historical_baseline=args.historical_baseline)
    else:
        if args.historical_baseline is not None:
            parser.error("--historical-baseline applies to comparison only")
        assert os.environ.get("WGPU_BACKEND"), "select and record one physical GPU backend"
        render(args.repo.resolve(), path, args.mode, args.fixture)


if __name__ == "__main__":
    main()
