"""Illustrate one-to-one matching on the crowded GC104889a field."""
import json
import sys
from pathlib import Path

from PIL import ImageDraw,ImageOps

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

fields=json.loads((root/"results/diatom-practice-round1.json").read_text())["fields"]
predictions=json.loads((root/"results/r3/predictions-0.05.json").read_text())
scores=json.loads((root/"results/r1/anchor-matching.json").read_text())["fields"]
field=next(f for f in fields if f["slide"].startswith("GC104889a_") and f["field"]==1)
pred=next(f for f in predictions if f["slide"]==field["slide"] and f["field"]==field["field"])
score=next(f for f in scores if f["slide"]==field["slide"] and f["field"]==field["field"])
with Stack(root/"scans"/field["slide"]) as s:
    image=ImageOps.autocontrast(s.field(pred["z"],*field["origin_xy"],768),cutoff=.25).convert("RGB")
draw=ImageDraw.Draw(image)
for box in pred["boxes"]:
    draw.rectangle(box["xyxy"],outline="#00b99a",width=3)
matched={a["mark_number"] for a in score["assignments"]}
for n,mark in enumerate(field["marks"],1):
    if mark["kind"]!="Possible diatom":continue
    x,y=mark["x"],mark["y"]
    color="#ffc637" if n in matched else "white"
    draw.ellipse((x-6,y-6,x+6,y+6),outline=color,width=3)
image.save(root/"results/r1/crowded-assignment.png")
