"""Export and verify Photoshot's region masks on the Part 3 example."""
import argparse
import hashlib
import json
import tempfile
from pathlib import Path

import cv2 as cv
import mediapipe as mp
import numpy as np
from PIL import Image, ImageDraw, ImageFont

from service import models, regions

LABELS = ("background", "hair", "body-skin", "face-skin", "clothes", "accessories")


def read_rgb(path):
    with Image.open(path) as image:
        return np.asarray(image.convert("RGB"), np.float32) / 255


def mask_image(mask):
    return Image.fromarray(np.uint8(np.rint(np.clip(mask, 0, 1) * 255)))


def skin_mask(region, selected="all", sensitivity=1, refine=True):
    """Same selection and math as service/tools.py:skin_mask."""
    part = {"face": region.parts[3], "body": region.parts[2], "all": region.skin}[selected]
    if refine:
        part = regions.blur(part, max(0.5, region.scale * 0.006))
    return np.clip(part * sensitivity, 0, 1)


def protection(region, group):
    radius = max(1, round(region.scale * 0.009))
    return cv.dilate(region.feature(group), regions.ellipse(radius))


def export(rgb, out, vision):
    region = regions.Analysis(rgb, vision)
    parts = region.parts
    masks = {name: skin_mask(region, name, refine=False) for name in ("face", "body", "all")}
    eyes = protection(region, regions.EYES)
    lips = protection(region, [regions.LIPS])
    protected = np.maximum(eyes, lips)
    refined = skin_mask(region)
    assert parts.shape == (len(LABELS), *rgb.shape[:2])
    assert np.isfinite(parts).all() and parts.min() >= -1e-6 and parts.max() <= 1.000001
    assert region.data is region.data
    assert np.allclose(masks["all"], np.clip((parts[2] + parts[3]) * (1 - protected), 0, 1))
    assert np.array_equal(skin_mask(region, sensitivity=0), np.zeros_like(refined))
    assert np.array_equal(skin_mask(region, sensitivity=2), np.clip(refined * 2, 0, 1))

    out.mkdir(parents=True, exist_ok=True)
    np.save(out / "confidence.npy", parts, allow_pickle=False)
    (out / "landmarks.json").write_text(json.dumps([face.tolist() for face in region.faces]), encoding="utf-8")
    for label, plane in zip(LABELS, parts):
        mask_image(plane).save(out / f"confidence-{label}.png")
    for name, mask in masks.items():
        mask_image(mask).save(out / f"mask-{name}-unrefined.png")
    mask_image(refined).save(out / "mask-all-refined.png")
    mask_image(protected).save(out / "protection.png")

    portrait = Image.fromarray(np.uint8(np.rint(rgb * 255)))
    overlay = Image.blend(portrait, Image.new("RGB", portrait.size, "#f85678"), 0.48)
    overlay = Image.composite(overlay, portrait, mask_image(protected))
    marks = ImageDraw.Draw(overlay)
    for face in region.faces:
        for group in [*regions.EYES, regions.LIPS]:
            points = [tuple(p) for p in face[group]]
            marks.line([*points, points[0]], fill="#fff7a3", width=1)
    overlay.save(out / "landmark-overlay.png")

    panels = [
        ("Source RGB", portrait), ("Eye and lip landmarks", overlay),
        ("Face skin confidence", mask_image(parts[3])), ("Body skin confidence", mask_image(parts[2])),
        ("Protected areas", mask_image(protected)), ("All skin, before refinement", mask_image(masks["all"])),
    ]
    size, gap, caption = 270, 12, 29
    figure = Image.new("RGB", (3 * size + 4 * gap, 2 * (size + caption) + 3 * gap), "#f1f4ee")
    draw = ImageDraw.Draw(figure)
    font = ImageFont.load_default(size=15)
    for index, (label, panel) in enumerate(panels):
        y, x = divmod(index, 3)
        left, top = gap + x * (size + gap), gap + y * (size + caption + gap)
        thumb = panel.convert("RGB")
        thumb.thumbnail((size, size), Image.Resampling.LANCZOS)
        figure.paste(thumb, (left + (size - thumb.width) // 2, top + (size - thumb.height) // 2))
        draw.text((left, top + size + 5), label, font=font, fill="#1f2d27")
    figure.save(out / "skin-mask-comparison.png")
    return region, masks, refined, eyes, lips


def measured_samples(region, masks, refined, eye_protection, lip_protection):
    samples = {}
    for name, indices, protection_map in (
        ("eye", regions.EYES[0], eye_protection), ("lip", regions.LIPS, lip_protection)
    ):
        x, y = np.rint(region.faces[0][indices].mean(axis=0)).astype(int)
        samples[name] = {
            "xy": [int(x), int(y)],
            "face_score": float(region.parts[3, y, x]),
            "body_score": float(region.parts[2, y, x]),
            "protection": float(protection_map[y, x]),
            "all_unrefined": float(masks["all"][y, x]),
            "all_refined": float(refined[y, x]),
        }
    return samples


def verify_fixtures(rgb, vision, region, masks, refined, eyes, lips):
    assert len(region.faces) == 1 and region.faces[0].shape == (478, 2)
    assert all(np.count_nonzero(mask >= 0.5) > 0 for mask in masks.values())
    assert np.max(np.abs(refined - masks["all"])) > 0
    samples = measured_samples(region, masks, refined, eyes, lips)
    for point in samples.values():
        assert point["protection"] >= 0.99
        assert point["all_unrefined"] < point["face_score"]

    blank = regions.Analysis(np.zeros_like(rgb), vision)
    assert len(blank.faces) == 0
    assert not blank.feature([*regions.EYES, regions.LIPS]).any()
    assert np.array_equal(blank.skin, np.clip(blank.parts[2] + blank.parts[3], 0, 1))
    full_pair = regions.Analysis(np.concatenate((rgb, rgb), axis=1), vision)
    portrait_crop = rgb[20:220, 100:320]
    dual = regions.Analysis(np.concatenate((portrait_crop, portrait_crop), axis=1), vision)
    assert len(dual.faces) == 2
    midpoint = portrait_crop.shape[1]
    assert any(face[:, 0].mean() < midpoint for face in dual.faces)
    assert any(face[:, 0].mean() > midpoint for face in dual.faces)
    dual_guard = dual.feature([*regions.EYES, regions.LIPS])
    assert dual_guard[:, :midpoint].max() > 0.9 and dual_guard[:, midpoint:].max() > 0.9

    with tempfile.TemporaryDirectory() as folder:
        folder = Path(folder)
        for expected_error in (FileNotFoundError, ValueError):
            try:
                verify_model_files(folder)
            except expected_error:
                pass
            else:
                raise AssertionError(f"Expected {expected_error.__name__}")
            if expected_error is FileNotFoundError:
                (folder / "face.task").write_bytes(b"damaged")
    return {
        "passed": True,
        "environment": {"mediapipe": mp.__version__, "opencv": cv.__version__, "numpy": np.__version__},
        "image_width_height": list(reversed(rgb.shape[:2])),
        "confidence_channels": list(LABELS),
        "landmark_counts": [len(face) for face in region.faces],
        "mask_pixels_at_or_above_half": {name: int(np.count_nonzero(mask >= 0.5)) for name, mask in masks.items()},
        "samples": samples,
        "blank_face_count": len(blank.faces),
        "two_full_portrait_face_count": len(full_pair.faces),
        "two_cropped_portrait_face_count": len(dual.faces),
        "both_portrait_copies_have_feature_masks": True,
        "sensitivity_zero_yields_empty_mask": True,
        "missing_model_rejected": True,
        "incorrect_model_hash_rejected": True,
        "model_sha256": models.CHECKSUMS,
    }


def verify_model_files(folder):
    for name, checksum in models.CHECKSUMS.items():
        path = folder / name
        if not path.is_file():
            raise FileNotFoundError(f"Missing {name}. Run python -m service.models from the exercise folder.")
        if hashlib.sha256(path.read_bytes()).hexdigest() != checksum:
            raise ValueError(f"Model integrity check failed: {name}")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--input", type=Path, default=Path(__file__).parent / "fixtures/astronaut.png")
    parser.add_argument("--out", type=Path, default=Path("out"))
    parser.add_argument("--verify", action="store_true", help="check the supplied portrait and the edge cases")
    args = parser.parse_args()
    verify_model_files(models.DIRECTORY)
    rgb = read_rgb(args.input)
    vision = regions.Vision()
    try:
        result = export(rgb, args.out, vision)
        if args.verify:
            checks = verify_fixtures(rgb, vision, *result)
            (args.out / "verification.json").write_text(json.dumps(checks, indent=2) + "\n", encoding="utf-8")
            print("Portrait, mask settings, zero/two landmarks sets and model-file checks passed.")
    finally:
        vision.close()


if __name__ == "__main__":
    main()
