"""Generate a standalone visual audit. Run python3 experiments/field_baseline.py.

Requires Pillow and libtiff. Inputs are opened read-only. Fields use native pixel
coordinates; segmentation runs at half resolution. See report_template.html for the UI.
"""
import argparse
import base64
from collections import defaultdict
from io import BytesIO
import json
import math
from pathlib import Path
import re
import time
from xml.etree.ElementTree import ParseError

from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageStat

from scan_fields import Stack

HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
SIDE = 768
COLORS = {"Slender": "#126bae", "Elongate": "#00846a", "Compact": "#a04a18"}
RUN = re.compile(b"\xff+")


def encoded(image, fmt, **kwargs):
    stream = BytesIO()
    image.save(stream, fmt, **kwargs)
    return base64.b64encode(stream.getvalue()).decode("ascii")


def components(mask):
    """8-connected components as inclusive horizontal spans."""
    groups = []
    parent = []
    def root(i):
        while i != parent[i]:
            parent[i] = parent[parent[i]]
            i = parent[i]
        return i
    raw = mask.tobytes()
    w, h = mask.size
    prev = []
    for y in range(h):
        curr = []
        start = 0
        for match in RUN.finditer(raw[y*w:(y+1)*w]):
            a, b = match.start(), match.end()-1
            i = len(parent)
            parent.append(i)
            while start < len(prev) and prev[start][1] < a-1:
                start += 1
            for k in range(start, len(prev)):
                l, _, j = prev[k]
                if l > b+1:
                    break
                parent[root(j)] = root(i)
            curr.append((a, b, i))
            groups.append((a, b, y))
        prev = curr
    merged = defaultdict(list)
    for i, span in enumerate(groups):
        merged[root(i)].append(span)
    return merged.values()


def convex_hull(points):
    points = sorted(set(points))
    def half(seq):
        result = []
        for x, y in seq:
            while len(result) >= 2:
                a,b = result[-2:]
                if (b[0]-a[0])*(y-a[1]) > (b[1]-a[1])*(x-a[0]):
                    break
                result.pop()
            result.append((x,y))
        return result
    return half(points)[:-1]+half(reversed(points))[:-1]


def masks(contrast, threshold, sx, sy):
    edges = contrast.point(lambda v: 255 if v >= threshold else 0)
    closed = edges.filter(ImageFilter.MaxFilter(3)).filter(ImageFilter.MinFilter(3))
    shape = closed.width
    for spans in components(closed):
        x0=min(a for a,b,y in spans)
        x1=max(b for a,b,y in spans)
        y0, y1 = spans[0][2], spans[-1][2]
        w,h=x1-x0+1,y1-y0+1
        if w*h < 95 or min(w,h)<4 or max(w,h)<15:
            continue
        if x0==0 or y0==0 or x1==shape-1 or y1==shape-1:
            continue
        mask = Image.new("L",(w+2,h+2))
        draw = ImageDraw.Draw(mask)
        for a,b,y in spans:
            draw.line((a-x0+1,y-y0+1,b-x0+1,y-y0+1),fill=255)
        ImageDraw.floodfill(mask,(0,0),128)
        mask = mask.point(lambda v: 0 if v==128 else 255)
        area = mask.histogram()[255]
        physical_area = area*4*sx*sy
        if not 6 <= physical_area <= 2200:
            continue
        hull = convex_hull([(x-x0+1,y-y0+1) for a,b,y in spans for x in (a,b)])
        if len(hull)<3:
            continue
        hm=Image.new("L",mask.size)
        ImageDraw.Draw(hm).polygon(hull,fill=255)
        solidity = area/hm.histogram()[255]
        if solidity < .82:
            continue
        # Principal-axis lengths of the ellipse with the same second moments.
        coords = [(i%mask.width,i//mask.width) for i,v in enumerate(mask.tobytes()) if v]
        cx=sum(x for x,y in coords)/area
        cy=sum(y for x,y in coords)/area
        xx=sum(((x-cx)*2*sx)**2 for x,y in coords)/area
        yy=sum(((y-cy)*2*sy)**2 for x,y in coords)/area
        xy=sum((x-cx)*(y-cy)*4*sx*sy for x,y in coords)/area
        delta=math.hypot(xx-yy,2*xy)
        major=4*math.sqrt((xx+yy+delta)/2)
        minor=4*math.sqrt(max(1e-12,(xx+yy-delta)/2))
        ratio=major/minor
        if major<6 or minor<0.95 or ratio>35:
            continue
        label = "Slender" if ratio>=4 else "Elongate" if ratio>=1.65 else "Compact"
        # Keep the observed boundary; the hull is only a debris filter.
        large=mask.resize((mask.width*2,mask.height*2),Image.Resampling.NEAREST)
        border=ImageChops.subtract(large,large.filter(ImageFilter.MinFilter(5)))
        xy0=(2*(x0-1),2*(y0-1))
        obj = dict(label=label, center=[round(xy0[0]+2*cx+1),round(xy0[1]+2*cy+1)],
                   box=[2*x0,2*y0,2*(x1+1),2*(y1+1)], area=round(physical_area,2),
                   ratio=round(ratio,2), length=round(major,2), width=round(minor,2),
                   solidity=round(solidity,3))
        yield obj, large, border, xy0


def overlap(a, b):
    return a[0]<b[2] and b[0]<a[2] and a[1]<b[3] and b[1]<a[3]


def iou(a, b):
    intersection = ImageChops.darker(a,b).histogram()[255]
    union = a.histogram()[255]+b.histogram()[255]-intersection
    return intersection / union if union else 0


def segment(im, sx, sy, mode, traces):
    small=im.resize((SIDE//2,SIDE//2),Image.Resampling.BOX)
    if mode=="contrast":
        contrast=ImageChops.difference(small,small.filter(ImageFilter.GaussianBlur(3)))
        thresholds=[max(5,round(ImageStat.Stat(contrast).mean[0]*1.7))]
    else:
        contrast=ImageChops.subtract(small.filter(ImageFilter.GaussianBlur(6)),small)
        thresholds=[4, 8, 14]
    proposals=[p for t in thresholds for p in masks(contrast,t,sx,sy)]
    # Keep the most convex candidate at each overlapping location.
    accepted=[]
    for p in sorted(proposals,key=lambda p:-p[0]["solidity"]):
        box=p[0]["box"]
        duplicate=False
        for prior in accepted:
            other=prior[0]["box"]
            if overlap(box,other):
                w=min(box[2],other[2])-max(box[0],other[0])
                h=min(box[3],other[3])-max(box[1],other[1])
                areas=[(b[2]-b[0])*(b[3]-b[1]) for b in (box,other)]
                if w*h > .65*min(areas):
                    duplicate=True
                    break
        if not duplicate:
            accepted.append(p)
    overlay=Image.new("RGBA",im.size)
    locations=[]
    matches=[dict(iou=0, id=None) for _ in traces]
    for obj,mask,border,xy0 in sorted(accepted,key=lambda p:p[0]["center"][1]):
        obj["id"]=len(locations)+1
        overlay.paste(COLORS[obj["label"]],xy0,border)
        locations.append(obj)
        for i,trace in enumerate(traces):
            if not overlap(trace.getbbox(),obj["box"]):
                continue
            full=Image.new("L",im.size)
            full.paste(mask,xy0)
            score=iou(full,trace)
            if score>matches[i]["iou"]:
                matches[i]=dict(iou=score,id=obj["id"])
    return overlay,locations,matches


def focus_score(im):
    sharp = ImageChops.difference(im, im.filter(ImageFilter.GaussianBlur(1.5)))
    return ImageStat.Stat(sharp).rms[0]


def sample(stack, annotations, directory=None):
    fields=[]
    for n in range(9):
        x=round(stack.width*(n%3+1)/4/stack.tw)*stack.tw-stack.tw
        y=round(stack.height*(n//3+1)/4/stack.th)*stack.th-stack.th
        if min(x,y)<0 or x+SIDE>stack.width or y+SIDE>stack.height:
            raise ValueError("Slide too small for this sampling grid")
        planes=[stack.field(z,x,y,SIDE) for z in range(stack.depth)]
        scores=list(map(focus_score,planes))
        z=scores.index(max(scores))
        best=planes[z]
        # One contrast curve per field, shared by all displayed planes.
        hist=best.histogram()
        clipped=sum(hist)*.0025
        def bound(indices):
            total=0
            for i in indices:
                total+=hist[i]
                if total>clipped:
                    return i
        lo,hi=bound(range(256)),bound(reversed(range(256)))
        table=[round(255*max(0,min(1,(i-lo)/max(1,hi-lo)))) for i in range(256)]
        key=f"{stack.path.name.split('_')[0]}-{n+1}"
        traces=[t for t in annotations if f"{t['slide']}-{t['field']}"==key]
        ref_masks=[]
        for trace in traces:
            ref=Image.new("L",best.size)
            ImageDraw.Draw(ref).polygon([tuple(pt) for pt in trace["points"]],fill=255)
            ref_masks.append(ref)
        variants={}
        for mode in ("dark","contrast"):
            overlay,objects,matches=segment(best,stack.sx,stack.sy,mode,ref_masks)
            variants[mode]=dict(objects=objects,overlay=encoded(overlay,"PNG"),matches=matches)
            if directory:
                overlay.save(directory/(key+'-'+mode+'.png'))
        if directory:
            best.point(table).save(directory/(key+'.png'))
        fields.append(dict(number=n+1,x=x,y=y,z=z,variants=variants,traces=traces,
             images=[encoded(p.point(table),"JPEG",quality=84) for p in planes]))
    return fields


def stamp(p):
    s=p.stat()
    return s.st_size, s.st_mtime_ns


def run(args):
    paths={p:stamp(p) for p in sorted(args.scans.glob("*.tif*")) if p.is_file()}
    time.sleep(2)
    annotations=json.loads((HERE/"visual_traces.json").read_text())
    slides=[]
    for p,initial in paths.items():
        if stamp(p)!=initial:
            print("Deferred growing scan",p.name, flush=True)
            continue
        try:
            with Stack(p) as stack:
                fields=sample(stack,annotations,args.debug_images)
                slide=dict(name=p.name,sx=stack.sx,sy=stack.sy,depth=stack.depth,
                           size=[stack.width,stack.height],fields=fields)
            if stamp(p)!=initial:
                print("Deferred changed scan",p.name, flush=True)
                continue
            slides.append(slide)
            print(p.name, {k: sum(len(f["variants"][k]["objects"]) for f in fields) for k in ("dark","contrast")},flush=True)
        except (OSError, ValueError, ParseError) as e:
            print("Deferred unreadable scan",p.name,e,flush=True)
    if not slides:
        raise SystemExit("No eligible readable scans")
    args.out.parent.mkdir(exist_ok=True,parents=True)
    template=(HERE/"report_template.html").read_text()
    data=json.dumps(slides,separators=(",",":")).replace("<","\\u003c")
    output=template.replace("__SCAN_DATA__",data).replace("__REFERENCE_RESULT__",(HERE/"reference_result.json").read_text())
    if args.debug_images:
        meta=[{**s,"fields":[{k:v for k,v in f.items() if k != "images"} for f in s["fields"]]} for s in slides]
        (args.debug_images/"metadata.json").write_text(json.dumps(meta))
    tmp=args.out.with_suffix(".partial")
    tmp.write_text(output)
    tmp.replace(args.out)

if __name__ == "__main__":
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--scans",type=Path,default=ROOT/"scans")
    parser.add_argument("--out",type=Path,default=ROOT/"results/field-review.html")
    parser.add_argument("--debug-images",type=Path,help="existing directory for working images")
    run(parser.parse_args())
