"""Generate a static, human-reviewed diatom proposal bundle for one scan field."""
import argparse
import hashlib
import json
import math
import shutil
import sys
from pathlib import Path

import numpy as np
import torch
from PIL import Image
from torchvision.models import resnet18
from ultralytics import SAM, YOLO
from ultralytics.nn.tasks import DetectionModel
from ultralytics.nn.modules import Conv, C2f, Bottleneck, SPPF, Concat, Detect, DFL
from torch.nn import Sequential, Conv2d, BatchNorm2d, SiLU, ModuleList, Identity, MaxPool2d, Upsample

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


def sha256(path):
    digest = hashlib.sha256()
    with path.open('rb') as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b''):
            digest.update(chunk)
    return digest.hexdigest()


def embedding(model, image):
    image = image.convert('L')
    image.thumbnail((224, 224), Image.Resampling.LANCZOS)
    canvas = Image.new('L', (224, 224), int(np.median(np.asarray(image))))
    canvas.paste(image, ((224-image.width)//2, (224-image.height)//2))
    array = np.asarray(canvas.convert('RGB'), dtype=np.float32) / 255
    mean = torch.tensor([.485, .456, .406]).view(3, 1, 1)
    std = torch.tensor([.229, .224, .225]).view(3, 1, 1)
    tensor = (torch.from_numpy(array).permute(2, 0, 1)-mean)/std
    with torch.inference_mode():
        return torch.nn.functional.normalize(model(tensor.unsqueeze(0))[0], dim=0).cpu().numpy()


def load_gallery(manifest, model, output):
    rows = json.loads(manifest.read_text())
    rows = rows if isinstance(rows, list) else rows['rows']
    invalid_species = {'none', 'nan', 'null', 'unknown', 'unidentified', 'n/a', ''}
    selected = [r for r in rows if isinstance(r.get('species'), str)
                and r['species'].strip().casefold() not in invalid_species and r.get('local_file')
                and (not r.get('split') or r['split'] == 'gallery')]
    if not selected:
        raise ValueError('Gallery has no species-labeled images')
    references = []
    (output/'references').mkdir(exist_ok=True)
    for index, row in enumerate(selected):
        source = (manifest.parent / row['local_file']).resolve(strict=True)
        with Image.open(source) as image:
            vector = embedding(model, image)
            name = f'references/{index+1:04d}.png'
            image.convert('RGB').save(output/name)
        references.append({'species': row['species'], 'source_slide': row.get('source_slide'),
                           'annotation_id': row.get('annotation_id'), 'image': name,
                           'source_sha256': sha256(source), 'vector': vector})
    return references


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--slide', type=Path, required=True)
    for name in ('x', 'y', 'z'):
        parser.add_argument('--'+name, type=int, required=True)
    parser.add_argument('--size', type=int, default=768)
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--detector', type=Path, required=True)
    parser.add_argument('--segmenter', type=Path, required=True)
    parser.add_argument('--encoder', type=Path, required=True)
    parser.add_argument('--gallery', type=Path, required=True)
    parser.add_argument('--confidence', type=float, default=.05)
    parser.add_argument('--max-candidates', type=int, default=30)
    parser.add_argument('--split-hypotheses', action='store_true',
                        help='Generate exploratory split alternatives for review')
    args = parser.parse_args()
    if args.size <= 0 or args.size > 2048 or min(args.x, args.y, args.z) < 0:
        parser.error('Invalid coordinates or field size (must be 1–2048 pixels)')
    if not 0 <= args.confidence <= 1 or args.max_candidates <= 0:
        parser.error('Confidence must be between 0 and 1 and max-candidates positive')
    if args.slide.stat().st_size < 1_000_000_000:
        raise ValueError('Scan is below the 1 GB completed-file cutoff')
    if args.output.exists() and any(args.output.iterdir()):
        raise FileExistsError('Output directory must be absent or empty')
    args.output.mkdir(parents=True, exist_ok=True)
    with Stack(args.slide) as stack:
        if args.z >= stack.depth or args.x+args.size > stack.width or args.y+args.size > stack.height:
            raise ValueError('Requested field or Z plane is outside the scan')
        calibration = {'x_um_per_pixel': stack.sx, 'y_um_per_pixel': stack.sy}
        field = stack.field(args.z, args.x, args.y, args.size).convert('RGB')
    field.save(args.output/'field.png')
    torch.set_num_threads(4)
    allowed = [DetectionModel, Conv, C2f, Bottleneck, SPPF, Concat, Detect, DFL,
               Sequential, Conv2d, BatchNorm2d, SiLU, ModuleList, Identity, MaxPool2d, Upsample, set]
    with torch.serialization.safe_globals(allowed):
        checkpoint = torch.load(args.detector, map_location='cpu', weights_only=True)
    detector = YOLO('yolov8n.yaml', task='detect')
    detector.model = checkpoint['model'].float()
    segmenter = SAM(str(args.segmenter))
    encoder = resnet18(weights=None)
    encoder.load_state_dict(torch.load(args.encoder, map_location='cpu', weights_only=True))
    encoder.fc = torch.nn.Identity()
    encoder.eval()
    references = load_gallery(args.gallery, encoder, args.output)
    prediction = detector.predict(np.array(field), imgsz=768, conf=args.confidence,
                                  device='cpu', verbose=False)[0]
    boxes = prediction.boxes.xyxy.cpu().tolist()
    scores = prediction.boxes.conf.cpu().tolist()
    (args.output/'candidates').mkdir(exist_ok=True)
    candidates = []
    for index, (box, confidence) in enumerate(list(zip(boxes, scores))[:args.max_candidates], 1):
        x0, y0, x1, y1 = box
        left, top = max(0, math.floor(x0)), max(0, math.floor(y0))
        right, bottom = min(args.size, math.ceil(x1)), min(args.size, math.ceil(y1))
        if left >= right or top >= bottom:
            continue
        result = segmenter.predict(np.array(field), bboxes=box, imgsz=768, device='cpu',
                                   retina_masks=True, verbose=False)[0]
        mask_path = None
        if result.masks is not None and len(result.masks.data) == 1:
            mask = result.masks.data[0].cpu().numpy().astype(bool)
            if mask.shape != (args.size, args.size):
                raise ValueError('Segmenter returned an unexpected mask size')
            mask_path = f'candidates/{index:03d}-mask.png'
            Image.fromarray(mask.astype('uint8')*255).save(args.output/mask_path)
        crop = field.crop((left, top, right, bottom))
        crop_path = f'candidates/{index:03d}-crop.png'
        crop.save(args.output/crop_path)
        vector = embedding(encoder, crop)
        ranked = sorted(((float(np.dot(vector, r['vector'])), r) for r in references),
                        key=lambda pair: -pair[0])
        suggestions, seen = [], set()
        for similarity, ref in ranked:
            if ref['species'] in seen:
                continue
            seen.add(ref['species'])
            suggestions.append({k: v for k, v in ref.items() if k != 'vector'} | {'similarity': similarity})
            if len(suggestions) == 3:
                break
        candidates.append({'id': f'candidate-{index:03d}', 'box': box, 'detector_score': confidence,
                           'mask': mask_path, 'crop': crop_path, 'suggestions': suggestions,
                           'classification': 'unresolved'})
        print(f'{index}/{min(len(boxes), args.max_candidates)} candidates', flush=True)
    info = {'format': 'diatom-field-bundle-v1', 'slide': args.slide.name,
            'slide_size_bytes': args.slide.stat().st_size, 'origin_xy': [args.x, args.y],
            'z': args.z, 'size': args.size, 'calibration': calibration, 'field_image': 'field.png',
            'models': {'detector_sha256': sha256(args.detector), 'segmenter_sha256': sha256(args.segmenter),
                       'encoder_sha256': sha256(args.encoder), 'gallery_manifest_sha256': sha256(args.gallery)},
            'detector_confidence': args.confidence, 'max_candidates': args.max_candidates,
            'detected_before_limit': len(boxes), 'reference_count': len(references),
            'candidates': candidates}
    info['bundle_id'] = hashlib.sha256(json.dumps(info, sort_keys=True).encode()).hexdigest()
    (args.output/'bundle.json').write_text(json.dumps(info, indent=2)+'\n')
    from focus_planes import add_focus_planes
    add_focus_planes(args.output, args.slide)
    if args.split_hypotheses:
        from split_hypotheses import main as add_splits
        add_splits(['--bundle', str(args.output), '--segmenter', str(args.segmenter),
                    '--encoder', str(args.encoder), '--gallery', str(args.gallery)])
    shutil.copyfile(Path(__file__).with_name('review.html'), args.output/'index.html')
    print('Bundle written:', args.output, flush=True)


if __name__ == '__main__':
    main()
