"""Compare a 448px frozen ResNet representation with a consumed 224px baseline."""
import ctypes
import json
import os
import signal
import time
from pathlib import Path

import numpy as np
import torch
from PIL import Image
from torchvision.models import resnet18

from diatom_pilot.ude_scaleup_dataset import UDEScaleupDataset, sha256

R = Path(__file__).resolve().parents[1]
O = R / 'results/r119'
B = R / 'results/r112/species-scaleup/real-crop-baseline'
W = Path('/tmp/resnet18-f37072fd.pth')
SIZE, CHUNK = 448, 200


def embedding(model, image):
    image = image.convert('L')
    image.thumbnail((SIZE, SIZE), Image.Resampling.LANCZOS)
    canvas = Image.new('L', (SIZE, SIZE), int(np.median(np.asarray(image))))
    canvas.paste(image, ((SIZE-image.width)//2, (SIZE-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 features(dataset, label, model):
    expected = [x['annotation_id'] for x in dataset.entries]
    chunks = []
    for start in range(0, len(dataset), CHUNK):
        stop = min(start + CHUNK, len(dataset))
        path = O / 'chunks' / f'{label}-{start:04d}.npz'
        if path.exists():
            with np.load(path, allow_pickle=False) as z:
                arr, ids = z['features'], z['annotation_ids'].tolist()
            if ids != expected[start:stop] or arr.shape != (stop-start, 512) or not np.isfinite(arr).all() or not np.allclose(np.linalg.norm(arr, axis=1), 1, atol=1e-5):
                raise ValueError('Invalid existing feature chunk: ' + str(path))
        else:
            arr = np.stack([embedding(model, dataset[i]['image']) for i in range(start, stop)])
            assert arr.shape == (stop-start, 512) and np.isfinite(arr).all()
            tmp = path.with_suffix('.npz.tmp')
            with tmp.open('wb') as f:
                np.savez_compressed(f, features=arr, annotation_ids=np.array(expected[start:stop]))
            tmp.replace(path)
        chunks.append({'path': str(path.relative_to(O)), 'sha256': sha256(path), 'start': start, 'stop': stop})
        print(label, stop, '/', len(dataset), flush=True)
    arrays = []
    for chunk in chunks:
        with np.load(O / chunk['path'], allow_pickle=False) as z:
            arrays.append(z['features'].copy())
    return np.concatenate(arrays), chunks


def main():
    parent = os.getppid()
    assert ctypes.CDLL(None, use_errno=True).prctl(1, signal.SIGTERM) == 0
    if parent != os.getppid():
        raise RuntimeError('Parent exited')
    torch.set_num_threads(2)
    O.mkdir(exist_ok=True)
    (O / 'chunks').mkdir(exist_ok=True)
    assert not (O / 'results.json').exists()
    files = ['results/r112/species-scaleup/assets.json', 'results/r112/species-scaleup/verify.json',
             'results/r112/species-scaleup/location-partitions.json', 'results/r112/species-scaleup/partition-verify.json',
             'results/r112/species-scaleup/real-crop-baseline/protocol.json',
             'results/r112/species-scaleup/real-crop-baseline/results.json',
             'results/r112/species-scaleup/real-crop-baseline/verify.json',
             'results/r112/species-scaleup/real-crop-baseline/training-features.npz',
             'results/r112/species-scaleup/real-crop-baseline/tuning-features.npz',
             'diatom_pilot/ude_scaleup_dataset.py', 'diatom_pilot/run_field.py',
             'research/r119_high_resolution_classifier.py']
    train, tune = UDEScaleupDataset('training'), UDEScaleupDataset('tuning')
    assert len(train) == 2830 and len(tune) == 604
    assert not {x['source_site_component'] for x in train.entries} & {x['source_site_component'] for x in tune.entries}
    protocol = {'format': 'r119-high-resolution-classifier-protocol-v1',
                'inputs_sha256': {f: sha256(R / f) for f in files}, 'encoder_sha256': sha256(W),
                'selection': 'Same 2,830 training and 604 previously consumed tuning crops as R112; no check-partition pixels opened. Source location components are disjoint only within this development partition and do not prove biological independence.',
                'preprocessing': 'Compare saved baseline 224px versus new 448px median-padded grayscale aspect-preserving canvases, using LANCZOS thumbnail without upscaling, ImageNet normalization, the same frozen pretrained ResNet-18 and L2-normalized pooled 512-vector. Small source images remain native size on a larger canvas; larger canvas changes relative occupancy and receptive-field context, so this is not an isolated resolution effect.',
                'training': 'For 448 features, fit the same 80-class zero-initialized linear head as baseline: inverse-class-count weighted full-batch cross-entropy, Adam 0.05, 300 updates, 0.0001 squared-weight penalty. No tuning or early stopping.',
                'outcomes': 'Compare paired top-1/top-5 exact source-name and top-1 source-genus matches, transitions, and source-image-size strata. Names are source metadata, not independently reconciled taxonomy.',
                'warning': 'Reused, correlated development data; source identity, sample/site independence, label correctness and model exposure uncertain. Crops have oracle source locations and may include neighbors. No unknown rejection, segmentation, overlapping-instance recovery, Academy accuracy or synthetic-training gain is measured.'}
    pp = O / 'protocol.json'
    if pp.exists():
        if json.loads(pp.read_text()) != protocol:
            raise ValueError('Frozen protocol differs')
    else:
        pp.write_text(json.dumps(protocol, indent=2) + '\n')
    start = time.monotonic()
    model = resnet18(weights=None)
    model.load_state_dict(torch.load(W, map_location='cpu', weights_only=True))
    model.fc = torch.nn.Identity()
    model.eval()
    x, chunks_train = features(train, 'training', model)
    y_features, chunks_tune = features(tune, 'tuning', model)
    labels = sorted({r['source_species'] for r in train.entries})
    assert len(labels) == 80 and {r['source_species'] for r in tune.entries} == set(labels)
    baseline = json.loads((B / 'results.json').read_text())
    assert baseline['labels'] == labels and baseline['training_count'] == len(train) and baseline['tuning_count'] == len(tune)
    old_train = np.load(B / 'training-features.npz', allow_pickle=False)
    old_tune = np.load(B / 'tuning-features.npz', allow_pickle=False)
    assert old_train['annotation_ids'].tolist() == [r['annotation_id'] for r in train.entries]
    assert old_tune['annotation_ids'].tolist() == [r['annotation_id'] for r in tune.entries]
    target = torch.tensor([labels.index(r['source_species']) for r in train.entries], dtype=torch.long)
    class_counts = torch.bincount(target, minlength=len(labels)).float()
    sample_weights = 1/class_counts[target]
    sample_weights /= sample_weights.sum()
    linear = torch.nn.Linear(512, len(labels))
    torch.nn.init.zeros_(linear.weight)
    torch.nn.init.zeros_(linear.bias)
    optimizer = torch.optim.Adam(linear.parameters(), lr=.05)
    X = torch.from_numpy(x)
    for step in range(300):
        optimizer.zero_grad()
        losses = torch.nn.functional.cross_entropy(linear(X), target, reduction='none')
        objective = (losses * sample_weights).sum() + .0001 * linear.weight.square().sum()
        objective.backward()
        optimizer.step()
    with torch.no_grad():
        scores = linear(torch.from_numpy(y_features)).numpy()
        weights, bias = linear.weight.detach().numpy(), linear.bias.detach().numpy()
    np.savez_compressed(O/'models.npz', weight=weights, bias=bias)
    order = np.argsort(-scores, axis=1, kind='stable')
    old = baseline['methods']['linear']
    cases = []
    for i, entry in enumerate(tune.entries):
        pred = [labels[k] for k in order[i, :5]]
        cases.append({'annotation_id': entry['annotation_id'], 'source_name': entry['source_species'],
                      'source_genus': entry['source_genus'], 'source_slide_group': entry['source_slide_group'],
                      'source_site_component': entry['source_site_component'], 'source_image': entry['source_crop'],
                      'source_sha256': entry['source_sha256'], 'source_dimensions_px': entry['source_dimensions_px'],
                      'long_side_le_224': max(entry['source_dimensions_px']) <= 224,
                      'long_side_gt_448': max(entry['source_dimensions_px']) > 448,
                      'top5_224': old['top5_names'][i], 'top5_448': pred})
    out = {'format': 'r119-high-resolution-classifier-results-v1', 'protocol_sha256': sha256(pp),
           'model_sha256': sha256(O/'models.npz'), 'labels': labels, 'genera': baseline['genera'],
           'training_chunks': chunks_train, 'tuning_chunks': chunks_tune,
           'training_count': len(train), 'tuning_count': len(tune), 'elapsed_seconds': round(time.monotonic()-start, 2),
           'warning': protocol['warning'], 'records': cases}
    (O/'results.json').write_text(json.dumps(out, indent=2) + '\n')
    print('complete; 448 top-1', sum(x['top5_448'][0] == x['source_name'] for x in cases), '/', len(cases), flush=True)


if __name__ == '__main__':
    main()
