"""Show examples of local versus field-wide focus using native TIFF data."""
import csv
import sys
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont, ImageOps

root = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(root / "experiments"))
from scan_fields import Stack

with (root / "results/l2/focus-scores.csv").open(newline="") as handle:
    rows = list(csv.DictReader(handle))
examples = []
for slide in dict.fromkeys(row["slide"] for row in rows):
    candidates = [r for r in rows if r["slide"] == slide and abs(int(r["field_best_z"])-int(r["local_best_z"])) > 1]
    if candidates:
        examples.append(candidates[0])
font = ImageFont.truetype("DejaVuSans.ttf", 17)
out = Image.new("RGB", (1020, len(examples)*285), "#f8f8f2")
draw = ImageDraw.Draw(out)
for index, row in enumerate(examples):
    with Stack(root / "scans" / row["slide"]) as stack:
        # The CSV stores field coordinates. Locate the original field origin from the practice export.
        import json
        source = json.loads((root / "results/diatom-practice-round1.json").read_text())
        field = next(f for f in source["fields"] if f["slide"] == row["slide"] and f["field"] == int(row["field"]))
        x = max(0, min(stack.width-256, field["origin_xy"][0] + int(row["x"]) - 128))
        y = max(0, min(stack.height-256, field["origin_xy"][1] + int(row["y"]) - 128))
        for col, (key, label) in enumerate((("field_best_z", "Field contrast peak"), ("local_best_z", "Local contrast peak"))):
            z = int(row[key])
            im = ImageOps.autocontrast(stack.field(z, x, y, 256), cutoff=.25).convert("RGB")
            d = ImageDraw.Draw(im)
            px = field["origin_xy"][0] + int(row["x"]) - x
            py = field["origin_xy"][1] + int(row["y"]) - y
            d.ellipse((px-5, py-5, px+5, py+5), outline="#ffc000", width=2)
            out.paste(im, (col*330+4, index*285+24))
            draw.text((col*330+4, index*285+2), f"{label} · plane {z+1}", fill="#173830", font=font)
        draw.text((665, index*285+50), row["slide"][:9], fill="#173830", font=font)
        draw.text((665, index*285+78), "Field " + row["field"], fill="#173830", font=font)
        draw.text((665, index*285+106), "Mark " + row["mark_number"], fill="#173830", font=font)
out.save(root / "results/l2/focus-examples.jpg", quality=92)
