"""Run Part 2 from a fresh output directory and verify the saved PNGs."""

import argparse
import hashlib
import json
from pathlib import Path
import platform
import subprocess
import sys
import tempfile
from importlib.metadata import version

import numpy as np
from PIL import Image

LAB = Path(__file__).resolve().parent
FILES = ("input.png", "mask.png", "output.png")
EXPECTED_SIZE = (448, 288)


def run_case(folder: Path, *options: str) -> None:
    subprocess.run(
        [sys.executable, str(LAB / "first_retouch.py"), "--out", str(folder), *options],
        check=True, capture_output=True, text=True,
    )


def read_png(path: Path, mode: str) -> np.ndarray:
    with Image.open(path) as image:
        if (image.format, image.mode, image.size) != ("PNG", mode, EXPECTED_SIZE):
            raise AssertionError(f"Unexpected file format, mode, or size for {path.name}")
        return np.array(image)


def check() -> dict:
    with tempfile.TemporaryDirectory(prefix="retouch-02-", dir=Path.cwd()) as tmp:
        root = Path(tmp)
        full, repeat, half, zero, edge, shifted = (root / name for name in
                                         ("full", "repeat", "half", "zero", "edge", "shifted"))
        run_case(full)
        run_case(repeat)
        run_case(half, "--strength", "0.5")
        run_case(zero, "--strength", "0")
        run_case(edge, "--roi", "447", "287", "1", "1", "--lift", "255")
        run_case(shifted, "--roi", "170", "90", "132", "104")

        source = read_png(full / "input.png", "RGB")
        mask = read_png(full / "mask.png", "L")
        output = read_png(full / "output.png", "RGB")
        zero_output = read_png(zero / "output.png", "RGB")
        half_output = read_png(half / "output.png", "RGB")
        edge_mask = read_png(edge / "mask.png", "L")
        edge_output = read_png(edge / "output.png", "RGB")
        shifted_mask = read_png(shifted / "mask.png", "L")
        shifted_output = read_png(shifted / "output.png", "RGB")

        expected_mask = np.zeros((288, 448), dtype=np.uint8)
        expected_mask[90:194, 150:282] = 255
        np.testing.assert_array_equal(mask, expected_mask)

        before = source.astype(np.int16)
        change = output.astype(np.int16) - before
        np.testing.assert_array_equal(change[mask == 0], 0)
        np.testing.assert_array_equal(change[mask == 255], 40)
        np.testing.assert_array_equal(zero_output, source)
        np.testing.assert_array_equal((half_output.astype(np.int16) - before)[mask == 255], 20)
        np.testing.assert_array_equal(half_output[mask == 0], source[mask == 0])
        np.testing.assert_array_equal(source[112, 160], [133, 118, 102])
        np.testing.assert_array_equal(output[112, 160], [173, 158, 142])
        np.testing.assert_array_equal(shifted_mask[112, 160], 0)
        np.testing.assert_array_equal(shifted_output[112, 160], source[112, 160])
        if np.count_nonzero(edge_mask) != 1 or edge_mask[287, 447] != 255:
            raise AssertionError("The bottom-right 1 x 1 ROI must cover one pixel.")
        np.testing.assert_array_equal(edge_output[287, 447], [255, 255, 255])
        np.testing.assert_array_equal(edge_output[edge_mask == 0], source[edge_mask == 0])

        png_sha256 = {}
        for name in FILES:
            first_bytes = (full / name).read_bytes()
            if first_bytes != (repeat / name).read_bytes():
                raise AssertionError(f"Repeated run changed {name}")
            png_sha256[name] = hashlib.sha256(first_bytes).hexdigest()

        rejected = root / "rejected"
        bad_run = subprocess.run(
            [sys.executable, str(LAB / "first_retouch.py"), "--out", str(rejected),
             "--roi", "447", "287", "2", "1"], capture_output=True, text=True,
        )
        if bad_run.returncode != 2 or rejected.exists():
            raise AssertionError("An out-of-bounds ROI must fail before writing any PNGs.")

        return {
            "passed": True,
            "environment": {
                "python": platform.python_version(), "machine": platform.machine(),
                "numpy": version("numpy"), "pillow": version("Pillow"),
                "opencv": version("opencv-python-headless"),
            },
            "settings": {"image_size_wh": list(EXPECTED_SIZE), "roi_xywh": [150, 90, 132, 104],
                         "lift": 40, "default_strength": 1.0},
            "checks": {
                "matching_png_dimensions": True, "expected_mask": True,
                "mask_on_pixels": int(np.count_nonzero(mask)),
                "changed_pixels_outside_mask": int(np.count_nonzero(np.any(change[mask == 0] != 0, axis=1))),
                "zero_strength_matches_input": True, "half_strength_delta_per_channel": 20,
                "full_strength_delta_per_channel": 40, "repeat_pngs_byte_identical": True,
                "edge_pixel_clips_to_255": True, "out_of_bounds_roi_rejected": True,
                "shifting_roi_preserves_sample_outside_new_mask": True,
            },
            "sample_pixel": {
                "xy": [160, 112], "input": source[112, 160].tolist(),
                "half_strength": half_output[112, 160].tolist(), "output": output[112, 160].tolist(),
                "after_shifting_roi_right_20px": shifted_output[112, 160].tolist(),
            },
            "png_sha256": png_sha256,
        }


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--report", type=Path)
    args = parser.parse_args()
    lines = json.dumps(check(), indent=2) + "\n"
    if args.report:
        args.report.write_text(lines, encoding="utf-8")
    print(lines, end="")
