"""Replay the real Photoshot Mattifier against controlled skin and shine."""
import hashlib
import json
from pathlib import Path
import platform
from types import SimpleNamespace
import sys
import tempfile
from unittest.mock import patch

import cv2 as cv
import numpy as np

from service import engine, tools
from service.regions import blur

LAB = Path(__file__).resolve().parents[1]
INPUT = LAB / "input"
OUT = LAB / "results"
sys.path.insert(0, str(LAB / "start"))
from uniform_baseline import darken_all_skin


def write_png(path, values):
    if values.ndim == 3:
        mode = cv.COLOR_RGB2BGR if values.shape[-1] == 3 else cv.COLOR_RGBA2BGRA
        values = cv.cvtColor(values, mode)
    ok, image = cv.imencode(".png", values)
    assert ok, path
    path.write_bytes(image.tobytes())


def gaussian(x, y, patch):
    u = (x - patch["x"]) / patch["sigma_x"]
    v = (y - patch["y"]) / patch["sigma_y"]
    return patch["peak"] * np.exp(-(u**2 + v**2) / 2)


def create_fixtures(settings):
    y, x = np.mgrid[:settings["height"], :settings["width"]]
    skin = ((x-122)/89)**2 + ((y-98)/83)**2 < 1
    test_roi = {
        "forehead": ((x-112)**2 + (y-49)**2) <= 4**2,
        "nose": ((x-130)**2 + (y-94)**2) <= 3**2,
        "cheek": ((x-74)**2 + (y-107)**2) <= 9**2,
        "background_bright": ((x-232)**2 + (y-91)**2) <= 3**2,
        "offskin": ~skin,
        "painted_mark": ((x-165)**2 + (y-82)**2) <= 3**2,
    }
    texture = np.sin(x*np.pi/2) * np.cos(y*np.pi/2) * .55
    light = 67.0 + .011*(x-122) - .013*(y-98) + texture
    offskin = gaussian(x, y, settings["offskin"])
    shine = gaussian(x, y, settings["forehead"]) + gaussian(x, y, settings["nose"])
    marker = gaussian(x, y, {"x":165,"y":82,"sigma_x":4,"sigma_y":4,"peak":23})
    def encode_light(l, neutral_patch=False):
        a = np.where(skin, 13., 3.)
        b = np.where(skin, 17., 5.)
        if neutral_patch:
            a = a - np.minimum(marker * .5, 11)
            b = b - np.minimum(marker * .55, 12)
        return cv.cvtColor(np.stack([l,a,b],axis=-1).astype(np.float32),cv.COLOR_LAB2RGB)
    fixture = {"shine":encode_light(light+offskin+shine),
               "no_shine":encode_light(light),
               "matte_paint":encode_light(light+marker,True)}
    return fixture, SimpleNamespace(skin=skin.astype(np.float32), scale=settings["face_scale"]), test_roi


def replay(rgb, region, operation=None, blend=.5, depth=8, output="layers", artifacts=None,
           protect_alpha=False):
    values = engine.encode(rgb,depth)
    max_code = 255 if depth==8 else 65535
    dtype = "u1" if depth==8 else "<u2"
    if protect_alpha:
        alpha = np.full(rgb.shape[:2],max_code,dtype)
        alpha[49,112] = max_code // 2
        alpha[94,130] = 0
        values = np.dstack((values,alpha))
    h,w,channels = values.shape
    job = {"width":w,"height":h,"channels":channels,"depth":depth,"output":output,
           "tools":[{"id":"mattifier","parameters":{"blend":blend}}]}
    coverage = np.zeros(rgb.shape[:2],"u1")
    current = values[...,:3].astype(np.float32)/max_code
    with tempfile.TemporaryDirectory(prefix="retouch06-") as tmp:
        folder = Path(tmp)
        source_path = folder/"input.bin"
        values.tofile(source_path)
        before_hash = hashlib.sha256(source_path.read_bytes()).digest()
        spec = {**engine.TOOLS["mattifier"]}
        if operation is not None:
            spec["operation"] = operation
        with patch.object(engine,"Analysis",return_value=region), patch.dict(engine.TOOLS,{"mattifier":spec}):
            result = engine.process(job,folder,None,lambda *args: None)
        assert hashlib.sha256(source_path.read_bytes()).digest()==before_hash
        for layer in result["layers"]:
            assert layer["visible"] and layer["blend"]=="normal"
            x,y,lw,lh=(layer[k] for k in ("x","y","width","height"))
            crop=np.s_[y:y+lh,x:x+lw]
            rgb_bytes=(folder/(layer["asset"]+".rgb")).read_bytes()
            mask_bytes=(folder/(layer["asset"]+".mask")).read_bytes()
            assert len(rgb_bytes)==lw*lh*3*(depth//8) and len(mask_bytes)==lw*lh
            colors=np.frombuffer(rgb_bytes,dtype).reshape(lh,lw,3).astype(np.float32)/max_code
            mask=np.frombuffer(mask_bytes,"u1").reshape(lh,lw)
            if protect_alpha:
                assert np.all(mask[values[crop][...,3]!=max_code]==0)
            coverage[crop]=mask
            dst=current[crop]
            dst += (colors-dst)*(mask[...,None].astype(np.float32)/255)
            if artifacts:
                (OUT/f"{artifacts}.rgb").write_bytes(rgb_bytes)
                (OUT/f"{artifacts}.mask").write_bytes(mask_bytes)
        if artifacts:
            (OUT/f"{artifacts}-manifest.json").write_text(json.dumps(result,indent=2),encoding="utf-8")
    assembled=values.copy()
    assembled[...,:3]=engine.encode(current,depth)
    if artifacts:
        write_png(OUT/f"{artifacts}.png",assembled)
        write_png(OUT/f"{artifacts}-mask.png",coverage)
    return values,assembled,coverage,result


def lab_light(colors,depth):
    maximum = 255 if depth==8 else 65535
    return tools.lab(colors[...,:3].astype(np.float32)/maximum)[...,0]


def measure(before,after,mask,manifest,roi,depth=8):
    a,b = lab_light(before,depth),lab_light(after,depth)
    diff = np.abs(after[...,:3].astype(np.int32)-before[...,:3].astype(np.int32))
    return {
        "layer_count":len(manifest["layers"]), "nonzero_mask_pixels":int(np.count_nonzero(mask)),
        "delta_L":{k:round(float(np.mean((b-a)[v])),4) for k,v in roi.items()},
        "max_RGB_code_change":{k:int(diff[v].max()) for k,v in roi.items()},
        "pixels_changed":int(np.any(diff,axis=-1).sum()),
    }


def main():
    settings = json.loads((LAB/"start"/"settings.json").read_text(encoding="utf-8"))
    fixtures,region,roi=create_fixtures(settings)
    for name,array in fixtures.items():
        write_png(INPUT/f"{name}.png",engine.encode(array,8))
    write_png(INPUT/"skin.png",engine.encode(region.skin,8))
    for name,mask in roi.items():
        write_png(INPUT/f"roi-{name}.png",mask.astype("u1")*255)
    cases={}
    views={}
    for setting in settings["blends"]:
        name=f"mattifier-{setting:g}"
        run=replay(fixtures["shine"],region,blend=setting,artifacts=name)
        cases[name]=measure(*run,roi)
        views[name]=run[1]
    main_control=cases["mattifier-0.5"]
    target = -main_control["delta_L"]["forehead"]
    def uniform(rgb,r,p):
        return darken_all_skin(rgb,r,target)
    uniform_run=replay(fixtures["shine"],region,operation=uniform,artifacts="uniform-baseline")
    cases["uniform-baseline"]=measure(*uniform_run,roi)
    for name in ("no_shine","matte_paint"):
        run=replay(fixtures[name],region,blend=1,artifacts=name)
        cases[name]=measure(*run,roi)
    cases["uniform-baseline"]["requested_delta_L"]=-target
    # Save all outcomes before assertions to expose which condition failed.
    report={
        "checkpoint":"photoshot-retouch-06-mattifier-2026-12-01",
        "runtime":{"python":platform.python_version(),"numpy":np.__version__,"opencv":cv.__version__},
        "synthetic":cases
    }
    report_file=OUT/"mattifier-checks.json"
    report_file.write_text(json.dumps(report,indent=2),encoding="utf-8")
    assert cases["mattifier-0"]["layer_count"]==0 and cases["mattifier-0"]["pixels_changed"]==0
    assert target>2 and main_control["delta_L"]["nose"] < -2
    assert abs(main_control["delta_L"]["cheek"])<.15
    assert main_control["max_RGB_code_change"]["offskin"]==0
    assert cases["mattifier-1"]["delta_L"]["forehead"]<main_control["delta_L"]["forehead"]-.5
    assert abs(cases["uniform-baseline"]["delta_L"]["forehead"]+target)<.35
    assert cases["uniform-baseline"]["delta_L"]["cheek"]<-2
    assert cases["no_shine"]["layer_count"]==0
    assert cases["matte_paint"]["delta_L"]["painted_mark"]<-2
    run16=replay(fixtures["shine"],region,blend=.5,depth=16,output="layers",protect_alpha=True,artifacts="16bit-layers")
    merged16=replay(fixtures["shine"],region,blend=.5,depth=16,output="merged",protect_alpha=True,artifacts="16bit-merged")
    b,a,_,man16=run16
    assert man16["depth"]==16 and man16["layers"]
    same=bool(np.array_equal(b[b[...,3]!=65535],a[b[...,3]!=65535])) and bool(np.array_equal(b[...,3],a[...,3]))
    delta=int(np.abs(a.astype(np.int32)-merged16[1].astype(np.int32)).max())
    assert same and delta<=1
    report["encoded_16bit_layers_merged_max_difference"]=delta
    report["protected_nonopaque_samples_unchanged"]=same
    report_file.write_text(json.dumps(report,indent=2),encoding="utf-8")
    frames=[engine.encode(fixtures["shine"],8),views["mattifier-0.5"],uniform_run[1]]
    write_png(OUT/"comparison.png",np.concatenate(frames,axis=1))
    print(json.dumps(report,indent=2))


if __name__=="__main__":
    main()

