from pathlib import Path
import hashlib
import json
import platform
import tempfile
from unittest.mock import patch

import cv2 as cv
import numpy as np

from service import engine

LAB = Path(__file__).resolve().parents[1]
OUT = LAB / "verification"
FIXTURES = LAB / "fixtures"


def save_png(path, image):
    channels = image.shape[-1] if image.ndim == 3 else 1
    if channels in (3, 4):
        image = cv.cvtColor(image, cv.COLOR_RGB2BGR if channels == 3 else cv.COLOR_RGBA2BGRA)
    ok, encoded = cv.imencode(".png", image)
    if not ok:
        raise ValueError(f"Could not encode {path.name}")
    path.write_bytes(encoded.tobytes())


def definition(operation):
    return {"operation": operation, "label": "Fixture operation", "group": "Fixture"}


def expose(rgb, region, settings):
    mask = np.zeros(rgb.shape[:2], np.float32)
    mask[3:8, 4:10] = settings["weight"]
    return rgb + np.float32(settings["delta"]), mask


def utility(rgb, region, settings):
    mask = np.zeros(rgb.shape[:2], np.float32)
    mask[3:8, 4:10] = 1
    return mask


def study(raw, depth, mode, tasks, keep=None):
    h, w, channels = raw.shape
    maximum = 255 if depth == 8 else 65535
    dtype = "u1" if depth == 8 else "<u2"
    assert raw.dtype == np.dtype(dtype)
    config = dict(width=w, height=h, depth=depth, channels=channels, output=mode,
                  tools=[{"id": tool, "parameters": settings} for tool, settings in tasks])
    with tempfile.TemporaryDirectory(prefix="ret04-engine-") as folder:
        work = Path(folder)
        raw.tofile(work / "input.bin")
        source_bytes = (work / "input.bin").read_bytes()
        trace = []
        manifest = engine.process(config, work, None, lambda index, key: trace.append([index, key]))
        assert source_bytes == (work / "input.bin").read_bytes()
        assert trace == [[index, tool] for index, (tool, _) in enumerate(tasks)] + [[len(tasks), None]]
        current = raw[..., :3].astype(np.float32) / maximum
        records = []
        for layer in manifest["layers"]:
            x, y, lw, lh = (layer[k] for k in ("x", "y", "width", "height"))
            base_slice = np.s_[y:y+lh, x:x+lw]
            root = work / layer["asset"]
            pixels = np.fromfile(root.with_suffix(".rgb"), dtype=dtype).reshape(lh, lw, 3)
            mask = np.fromfile(root.with_suffix(".mask"), dtype="u1").reshape(lh, lw)
            assert len(root.with_suffix(".rgb").read_bytes()) == lw * lh * 3 * (depth // 8)
            assert len(root.with_suffix(".mask").read_bytes()) == lw * lh
            if channels == 4:
                assert np.all(mask[raw[base_slice][..., 3] != maximum] == 0)
            if layer["visible"]:
                target = current[base_slice]
                target += (pixels.astype(np.float32) / maximum - target) * (mask[..., None].astype(np.float32) / 255)
            records.append([layer["tool"], x, y, lw, lh, layer["visible"], int(np.count_nonzero(mask))])
            if keep:
                (OUT / f"{keep}-{layer['asset']}.rgb").write_bytes(root.with_suffix(".rgb").read_bytes())
                (OUT / f"{keep}-{layer['asset']}.mask").write_bytes(root.with_suffix(".mask").read_bytes())
                save_png(OUT / f"{keep}-{layer['asset']}-mask.png", mask)
        if keep:
            (OUT / f"{keep}-manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
        rendered = raw.copy()
        rendered[..., :3] = engine.encode(current, depth)
        return rendered, records, manifest


def run():
    OUT.mkdir(exist_ok=True)
    FIXTURES.mkdir(exist_ok=True)
    config = json.loads((LAB / "start" / "fixture-settings.json").read_text(encoding="utf-8"))
    matrix = []
    sample = None
    tasks = config["matrix_tasks"]
    crop = config["expected_crop"]
    tolerance = config["separate_vs_merged_tolerance"]
    stub_ops = {"heal": definition(expose), "mattifier": definition(expose),
                "skinMask": definition(utility)}
    with patch.dict(engine.TOOLS, stub_ops):
        for depth, dtype, maximum in ((8, "u1", 255), (16, "<u2", 65535)):
            for channels in (3, 4):
                raw = np.full((config["matrix_height"], config["matrix_width"], channels),
                              config["srgb_8bit_base"] * (maximum // 255), dtype=dtype)
                if channels == 4:
                    raw[..., 3] = maximum
                    for (x, y), alpha in zip(config["protected_xy"], (maximum // 2, 0)):
                        raw[y, x, 3] = alpha
                target = f"{depth}bit-{channels}ch"
                save_png(FIXTURES / f"{target}.png", raw)
                layered, layers, _ = study(raw, depth, "layers", tasks, target + "-layers")
                merged, combined, _ = study(raw, depth, "merged", tasks, target + "-merged")
                delta = np.abs(layered.astype(np.int32) - merged.astype(np.int32))
                assert delta.max() <= tolerance
                assert [[t[0], *t[1:5], t[5]] for t in layers] == [
                    ["heal", *crop, True],
                    ["skinMask", *crop, False],
                    ["mattifier", *crop, True],
                ]
                assert [t[0] for t in combined] == ["skinMask", "merged"]
                roi = np.zeros(raw.shape[:2], dtype=bool)
                x, y, w, h = crop
                roi[y:y+h, x:x+w] = True
                assert np.array_equal(layered[~roi], raw[~roi])
                assert np.array_equal(merged[~roi], raw[~roi])
                if channels == 4:
                    protected = raw[..., 3] != maximum
                    assert np.array_equal(layered[protected], raw[protected])
                    assert np.array_equal(merged[protected], raw[protected])
                    assert np.array_equal(layered[..., 3], raw[..., 3])
                    assert np.array_equal(merged[..., 3], raw[..., 3])
                    save_png(FIXTURES / f"{target}-protected.png", protected.astype("u1") * 255)
                save_png(FIXTURES / f"{target}-roi.png", roi.astype("u1") * 255)
                save_png(OUT / f"{target}-from-layers.png", layered)
                save_png(OUT / f"{target}-from-merged.png", merged)
                unchanged, empty, _ = study(raw, depth, "merged", [("heal", {"delta": .15, "weight": 0})])
                assert empty == [] and np.array_equal(unchanged, raw)
                unchanged, empty, _ = study(raw, depth, "layers", [("heal", {"delta": .0005, "weight": 1})])
                assert empty == [] and np.array_equal(unchanged, raw)
                hidden, hidden_info, _ = study(raw, depth, "merged", [("skinMask", {})])
                assert len(hidden_info) == 1 and hidden_info[0][5] is False and np.array_equal(hidden, raw)
                matrix.append({"file": target, "max_encoded_error": int(delta.max()),
                               "layers": layers, "merged": combined,
                               "protected_pixels": int((raw[..., 3] != maximum).sum()) if channels == 4 else 0,
                               "expected_no_change_trials": 3})
        def ramp(rgb, region, settings):
            mask = np.zeros(rgb.shape[:2], np.float32)
            mask[1, 1:3] = [.5, 1]
            return rgb + np.float32(40 / 255), mask

        with patch.dict(engine.TOOLS, {"heal": definition(ramp)}):
            raw = np.full((16, 16, 3), 80, dtype="u1")
            rendered, _, _ = study(raw, 8, "layers", [("heal", {})])
            sample = rendered[1, :3, 0].tolist()
            assert sample == [80, 100, 120]

    detail_keys = ("eyeVessels", "eyeBrilliance", "fabric", "strayHairs", "glassesGlare")
    shape_log = {}
    def observe(key):
        def op(rgb, region, settings):
            shape_log[key] = {"working_base": list(rgb.shape), "analysis": list(region.rgb.shape)}
            return rgb, np.zeros(rgb.shape[:2], np.float32)
        return op

    native_shape = [config["proxy_height"], config["proxy_width"], 3]
    long_edge = config["proxy_long_edge"]
    proxy_shape = [round(native_shape[0] * long_edge / native_shape[1]), long_edge, 3]
    with patch.dict(engine.TOOLS, {key: definition(observe(key)) for key in (*detail_keys, "heal")}):
        raw = np.zeros(native_shape, "u1")
        unchanged, empty, _ = study(raw, 8, "layers", [(key, {}) for key in ("heal", *detail_keys)])
        assert empty == [] and np.array_equal(raw, unchanged)
        assert shape_log["heal"]["working_base"] == proxy_shape
        assert all(shape_log[key] == {"working_base": native_shape, "analysis": proxy_shape}
                   for key in detail_keys)

    with patch.dict(engine.TOOLS, {"heal": definition(expose)}):
        def proxy_patch(rgb, region, settings):
            mask = np.zeros(rgb.shape[:2], np.float32)
            mask[99:150, 270:460] = .6
            return rgb + np.float32(.1), mask
        with patch.dict(engine.TOOLS, {"heal": definition(proxy_patch)}):
            raw = np.full(native_shape, config["srgb_8bit_base"], "u1")
            layered, bounds, _ = study(raw, 8, "layers", [("heal", {})], "large-proxy")
            merged, _, _ = study(raw, 8, "merged", [("heal", {})])
            assert np.max(np.abs(layered.astype(np.int32) - merged.astype(np.int32))) <= tolerance
            _, x, y, w, h, visible, count = bounds[0]
            assert visible and 307 <= x <= 309 and 111 <= y <= 113 and 216 <= w <= 220 and 58 <= h <= 61
            assert np.array_equal(raw[0, 0], layered[0, 0])
            save_png(OUT / "large-proxy-render.png", layered)
    metrics = {
        "runtime": {"python": platform.python_version(), "opencv": cv.__version__, "numpy": np.__version__,
                    "platform": platform.platform()},
        "patched_service_engine_sha256": hashlib.sha256(Path(engine.__file__).read_bytes()).hexdigest(),
        "table_columns": ["tool", "x", "y", "width", "height", "visible", "nonzero_mask_pixels"],
        "8bit_sample_reconstructed_codes": sample,
        "matrix": matrix,
        "analysis_runtime_shapes": shape_log,
        "large_proxy_patch_output": bounds[0],
        "tolerance_in_final_integer_codes": tolerance,
    }
    (OUT / "engine-checks.json").write_text(json.dumps(metrics, indent=2), encoding="utf-8")
    print(json.dumps(metrics, indent=2))


if __name__ == "__main__":
    run()

