"""Report centroid abstention tradeoffs on saved validation predictions only."""
import argparse
import html
import json
import math
from pathlib import Path

from ingest_review import digest


def tradeoffs(model,thresholds,rank):
    if rank not in {'genus','species'}:raise ValueError('Invalid rank')
    records=model['validation']['records'];labels=model['labels'];mapping=model.get('species_to_genus')
    model_rank=model.get('label_rank','species')
    known=(set(labels) if rank==model_rank else (set(mapping.values()) if rank=='genus' and mapping else set()))
    selected=[]
    for record in records:
        true=record.get('true_'+rank);pred=record.get('predicted_'+rank);score=record.get('similarity')
        if true is None:
            if rank=='species' and model_rank=='species':raise ValueError('Missing validation species')
            continue
        if not isinstance(true,str) or not isinstance(pred,str) or not isinstance(score,(int,float)) or isinstance(score,bool) or not math.isfinite(score) or not -1.001<=score<=1.001:
            raise ValueError('Invalid validation prediction')
        selected.append((true,pred,score))
    unknown=sum(true not in known for true,_,_ in selected);results=[]
    for threshold in thresholds:
        accepted=[x for x in selected if x[2]>=threshold];correct=sum(true==pred for true,pred,_ in accepted)
        unknown_accepted=sum(true not in known for true,_,_ in accepted)
        results.append({'threshold':threshold,'eligible':len(selected),'accepted':len(accepted),'abstained':len(selected)-len(accepted),
                        'correct':correct,'incorrect_accepted':len(accepted)-correct,'unseen_truth':unknown,
                        'unseen_accepted':unknown_accepted,'unseen_abstained':unknown-unknown_accepted,
                        'fraction_correct_all':correct/len(selected) if selected else None,
                        'fraction_correct_accepted':correct/len(accepted) if accepted else None})
    return {'unmapped':len(records)-len(selected),'results':results}


def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--model',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
    p.add_argument('--threshold',type=float,action='append',help='Similarity threshold; repeat to set an explicit grid')
    a=p.parse_args();manifest=a.model/'model.json';model=json.loads(manifest.read_text())
    if model.get('format')!='diatom-centroid-classifier-v1' or model.get('test_status')!='test images not opened or scored':raise ValueError('Invalid model provenance')
    if digest(a.model/'centroids.npz')!=model.get('centroids_sha256'):raise ValueError('Centroid hash mismatch')
    records=model.get('validation',{}).get('records')
    if not isinstance(records,list) or not records:raise ValueError('No saved validation predictions')
    thresholds=a.threshold if a.threshold is not None else [-1.0,0.0,.25,.5,.6,.7,.8,.9,.95,1.0]
    if any(not math.isfinite(x) or not -1<=x<=1 for x in thresholds):raise ValueError('Thresholds must be finite and between -1 and 1')
    thresholds=sorted(set(thresholds));species=tradeoffs(model,thresholds,'species');genus=tradeoffs(model,thresholds,'genus')
    if a.output.exists() and any(a.output.iterdir()):raise FileExistsError('Output directory must be empty')
    a.output.mkdir(parents=True,exist_ok=True)
    result={'format':'diatom-centroid-threshold-report-v1','model_sha256':digest(manifest),'validation_samples':model['validation_samples'],
            'validation_rows':len(records),'provisional_used':model['provisional_used'],'species':species,'genus':genus,
            'warning':'Validation-only development diagnostic on preselected crops; similarities are not probabilities. Threshold selection can overfit; no independent test or end-to-end accuracy is established.'}
    (a.output/'thresholds.json').write_text(json.dumps(result,indent=2)+'\n')
    blocks=[]
    for rank,values in [('Species',species),('Genus',genus)]:
        rows=''.join(f'<tr><td>{x["threshold"]:.2f}</td><td>{x["accepted"]}/{x["eligible"]}</td><td>{x["correct"]}/{x["eligible"]}</td><td>{x["correct"]}/{x["accepted"]}</td><td>{x["unseen_accepted"]}/{x["unseen_truth"]}</td></tr>' for x in values['results'])
        blocks.append(f'<section><h2>{rank}</h2><p>{values["unmapped"]} validation labels lack a {rank.lower()} mapping and are excluded from this table.</p><table><thead><tr><th>Threshold</th><th>Accepted / eligible</th><th>Correct / eligible</th><th>Correct / accepted</th><th>Unseen truth accepted / unseen truth</th></tr></thead><tbody>{rows}</tbody></table></section>')
    (a.output/'index.html').write_text('''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Validation threshold tradeoffs</title><style>body{font:16px/1.5 system-ui;color:#1c3835;max-width:1000px;margin:2em auto;padding:0 1em}table{border-collapse:collapse}td,th{border:1px solid #aaa;padding:.4em}section{overflow:auto;border-top:1px solid #aaa}</style><h1>Validation threshold tradeoffs</h1><p>Development crops only; similarity is not a probability. Every suggestion below the threshold is treated as an abstention. A threshold chosen on these same examples may overfit, and these results do not measure field detection or final accuracy. Unseen truth means the reference species or genus is absent from training; it does not cover debris or every possible unknown.</p><p><a href="thresholds.json">Data and provenance</a></p>'''+''.join(blocks)+'</html>')
    print(f'Wrote validation tradeoffs for {len(records)} crops; no threshold was selected.')


if __name__=='__main__':main()
