"""Check fixed-location feature stability across Z; this is not an identification test."""
import json
import math
import sys
from pathlib import Path

import numpy as np
import torch
from PIL import Image, ImageDraw, ImageFont, ImageOps
from torchvision.models import resnet18

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

torch.set_num_threads(4)
model = resnet18(weights=None)
model.load_state_dict(torch.load('/tmp/resnet18-f37072fd.pth', map_location='cpu', weights_only=True))
model.fc = torch.nn.Identity()
model.eval()
mean = torch.tensor([.485, .456, .406]).view(3, 1, 1)
std = torch.tensor([.229, .224, .225]).view(3, 1, 1)

def feature(crop):
    arr = np.asarray(crop.resize((224, 224), Image.Resampling.LANCZOS).convert('RGB'), dtype=np.float32) / 255
    x = (torch.from_numpy(arr).permute(2, 0, 1) - mean) / std
    with torch.inference_mode():
        return torch.nn.functional.normalize(model(x[None])[0], dim=0).numpy()

def box(x, y):
    left = max(0, min(768 - 96, x - 48))
    top = max(0, min(768 - 96, y - 48))
    return (left, top, left + 96, top + 96)

fields = json.loads((ROOT / 'results/diatom-practice-round1.json').read_text())['fields']
records = json.loads((ROOT / 'results/r6/marked-crossings.json').read_text())
cache = {}
rows = []
for rec in records:
    field = next(f for f in fields if f['slide'] == rec['slide'] and f['field'] == rec['field'])
    x, y = rec['point']
    alternatives = [m for m in field['marks'] if m['kind'] == 'Possible diatom' and m['z'] == rec['z']
                    and math.hypot(m['x'] - x, m['y'] - y) >= 150]
    if not alternatives:
        continue
    other = min(alternatives, key=lambda m: math.hypot(m['x'] - x, m['y'] - y))
    with Stack(ROOT / 'scans' / rec['slide']) as stack:
        z = rec['z']
        neighbor = z + 1 if z + 1 < stack.depth else z - 1
        far = max(range(stack.depth), key=lambda n: abs(n-z))
        planes = {}
        for plane in {z, neighbor, far}:
            key = (rec['slide'], rec['field'], plane)
            if key not in cache:
                cache[key] = stack.field(plane, *field['origin_xy'], 768)
            planes[plane] = cache[key]
    crops = [planes[z].crop(box(x,y)), planes[neighbor].crop(box(x,y)),
             planes[far].crop(box(x,y)), planes[z].crop(box(other['x'],other['y']))]
    vectors = [feature(c) for c in crops]
    rows.append((dict(slide=rec['slide'], field=rec['field'], mark=rec['mark_number'], xy=[x,y],
                      z=z, adjacent_z=neighbor, far_z=far, other_xy=[other['x'],other['y']],
                      same_xy_adjacent=float(vectors[0] @ vectors[1]),
                      same_xy_far=float(vectors[0] @ vectors[2]),
                      other_xy_same_plane=float(vectors[0] @ vectors[3])), crops))

out = ROOT / 'results/l3'
out.mkdir(exist_ok=True)
out.joinpath('focus-feature-results.json').write_text(json.dumps([r for r,_ in rows], indent=2))
font = ImageFont.truetype('DejaVuSans.ttf', 15)
plate = Image.new('RGB', (920, len(rows) * 220), '#f8f8f2')
d = ImageDraw.Draw(plate)
for i, (r, crops) in enumerate(rows):
    y = i * 220
    d.text((8,y+3), f"{r['slide'][:9]} field {r['field']} mark {r['mark']}   z={r['z']}", font=font, fill='#193b36')
    titles = ['Anchor', f"Same XY z={r['adjacent_z']}  {r['same_xy_adjacent']:.3f}",
              f"Same XY z={r['far_z']}  {r['same_xy_far']:.3f}", f"Other XY  {r['other_xy_same_plane']:.3f}"]
    for j, crop in enumerate(crops):
        x=j*230+8
        d.text((x,y+28), titles[j], font=font, fill='#193b36')
        # Autocontrast is for visibility only; features use native intensities.
        plate.paste(ImageOps.autocontrast(crop, cutoff=.25).resize((170,170)), (x,y+48))
plate.save(out/'focus-feature-examples.jpg', quality=90)
for key in ('same_xy_adjacent','same_xy_far','other_xy_same_plane'):
    print(key, 'median', round(float(np.median([r[key] for r,_ in rows])),4))
print('cases',len(rows), 'adjacent beats other',sum(r['same_xy_adjacent'] > r['other_xy_same_plane'] for r,_ in rows),
      'far beats other',sum(r['same_xy_far'] > r['other_xy_same_plane'] for r,_ in rows))
