"""Render a static, descriptive report from an instance-evaluation result."""
import argparse
import html
import json
import math
import shutil
from pathlib import Path

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from ingest_review import digest


def frac(value):
    return 'Not available' if value is None else f'{value:.1%}'


def counts(rank,record):
    keys=('eligible','correct','accepted','detected_abstentions','missed')
    if any(type(record.get(k)) is not int or record[k]<0 for k in keys):raise ValueError(f'Invalid {rank} counts')
    eligible,correct,accepted,abstain,missed=(record[k] for k in keys)
    if correct>accepted or accepted+abstain+missed!=eligible:raise ValueError(f'Inconsistent {rank} counts')
    value=record.get('end_to_end_fraction');expected=correct/eligible if eligible else None
    if (value is None)!=(expected is None) or (expected is not None and (not isinstance(value,(int,float)) or not math.isfinite(value) or abs(value-expected)>1e-9)):
        raise ValueError(f'Invalid {rank} identification fraction')
    return [correct,accepted-correct,abstain,missed]


def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--input',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
    p.add_argument('--demonstration',action='store_true',help='Prominently mark this report as synthetic practice')
    a=p.parse_args();data=json.loads(a.input.read_text());overall=data.get('overall');per_taxon=data.get('per_taxon');groups=data.get('overlap_group_summary')
    if (data.get('format')!='diatom-instance-evaluation-result-v1' or not isinstance(overall,dict) or not isinstance(per_taxon,dict)
        or not isinstance(groups,dict) or not isinstance(data.get('fields'),list) or not isinstance(data.get('per_sample'),dict)):
        raise ValueError('Expected a current instance-evaluation result')
    if data.get('test_sample_count')!=len(data['per_sample']) or data.get('field_count')!=len(data['fields']):raise ValueError('Sample or field count does not match the detail records')
    rankings={rank:counts(rank,overall[rank]) for rank in ('genus','species')}
    for rank in ('genus','species'):
        if not isinstance(per_taxon.get(rank),dict):raise ValueError('Invalid per-taxon results')
        for name,row in per_taxon[rank].items():
            if not isinstance(name,str) or not name or not isinstance(row,dict):raise ValueError('Invalid taxon result')
            counts(rank,row)
    for sample,row in data['per_sample'].items():
        if not isinstance(sample,str) or not sample or not isinstance(row,dict):raise ValueError('Invalid sample result')
        for rank in ('genus','species'):counts(rank,row[rank])
    for rank in ('genus','species'):
        for key in ('eligible','correct','accepted','detected_abstentions','missed'):
            if sum(row[rank][key] for row in data['per_sample'].values())!=overall[rank][key]:raise ValueError(f'{rank} sample counts do not add up to the overall result')
    for key in ('groups','members','fully_detected','fully_detected_with_nonempty_masks','fully_detected_with_acceptable_masks','groups_with_unreviewed_matched_masks','groups_with_unsure_matched_masks','groups_with_merged_matched_masks','groups_with_identified_merged_neighbors','groups_with_cross_plane_matches'):
        if type(groups.get(key)) is not int or groups[key]<0:raise ValueError('Invalid overlap-group summary')
    if any(groups[x]>groups['groups'] for x in ('fully_detected','fully_detected_with_nonempty_masks','fully_detected_with_acceptable_masks','groups_with_unreviewed_matched_masks','groups_with_unsure_matched_masks','groups_with_merged_matched_masks','groups_with_identified_merged_neighbors','groups_with_cross_plane_matches')):raise ValueError('Invalid overlap-group counts')
    if a.output.exists() and any(a.output.iterdir()):raise FileExistsError('Output directory must be empty')
    a.output.mkdir(parents=True,exist_ok=True)
    fig,ax=plt.subplots(figsize=(9,3.4),layout='constrained');colors=['#19765f','#c46a42','#e5b14f','#8a9a9a'];names=['Correct name','Incorrect name','Detected; abstained','Not matched']
    if a.demonstration:ax.set_title('SYNTHETIC EXAMPLE — NOT PERFORMANCE',fontsize=11,color='#a34f28',weight='bold')
    for y,rank in enumerate(('genus','species')):
        denominator=overall[rank]['eligible'];left=0
        for i,n in enumerate(rankings[rank]):
            width=n/denominator if denominator else 0
            ax.barh(y,width,left=left,color=colors[i],edgecolor='white',label=names[i] if y==0 else None)
            if width>=.07:ax.text(left+width/2,y,str(n),ha='center',va='center',fontsize=10,color='white' if i in (0,1) else '#18332e')
            left+=width
        ax.text(1.02,y,f'n = {denominator}',va='center',fontsize=10)
    ax.set_yticks([0,1],['Genus','Species']);ax.invert_yaxis();ax.set_xlim(0,1.2);ax.set_xticks([0,.25,.5,.75,1],['0%','25%','50%','75%','100%']);ax.set_xlabel('Fraction of eligible reference specimens');ax.legend(loc='upper center',bbox_to_anchor=(.5,-.28),ncol=2,frameon=False,fontsize=9);ax.spines[['top','right']].set_visible(False)
    fig.savefig(a.output/'identification-breakdown.svg');fig.savefig(a.output/'identification-breakdown.png',dpi=150);plt.close(fig)
    def esc(x):return html.escape(str(x),quote=True)
    def table(rank):
        rows=[]
        for name,r in sorted(per_taxon[rank].items()):
            rows.append('<tr>'+''.join(f'<td>{esc(v)}</td>' for v in (name,r.get('sample_count'),r['eligible'],r['correct'],r['missed'],r['detected_abstentions'],frac(r['end_to_end_fraction'])))+'</tr>')
        return '<table><thead><tr><th>Reference '+rank+'</th><th>Samples</th><th>Eligible</th><th>Correct</th><th>Missed</th><th>Abstained</th><th>Correct / eligible</th></tr></thead><tbody>'+(''.join(rows) or '<tr><td colspan="7">No eligible references.</td></tr>')+'</tbody></table>'
    summaries=[]
    for rank in ('genus','species'):
        x=overall[rank];mask_fraction=frac(x.get('correct_with_acceptable_mask_fraction'))
        summaries.append(f'<article><h3>{rank.title()}</h3><p><strong>{x["correct"]} / {x["eligible"]}</strong> eligible references correctly named ({frac(x["end_to_end_fraction"])}).</p><p>With a mask declared acceptable: {mask_fraction}; mask assessment complete: {"yes" if x.get("mask_assessment_complete") else "no"}.</p></article>')
    warning='<p class="notice"><strong>Invented demonstration:</strong> The samples, taxon names, references, and expert declarations in this report are synthetic. This is not evidence of diatom performance.</p>' if a.demonstration else ''
    if data.get('reference_status')=='provisional':warning+='<p class="notice"><strong>Provisional development review:</strong> References and matches are not expert-adjudicated; these results are not expert-validated performance.</p>'
    field_overlaps=data.get('overlapping_field_pairs')
    if field_overlaps is None:field_overlap_note='Field-overlap declarations are not recorded in this result.'
    elif not isinstance(field_overlaps,list):raise ValueError('Invalid field overlap declarations')
    elif field_overlaps:field_overlap_note=f'{len(field_overlaps)} overlapping field pairs were declared; handling rule: {esc(data.get("field_overlap_handling_id") or "missing")}. The program does not verify unique specimen assignment.'
    else:field_overlap_note='The declared field plan recorded no overlapping field pairs.'
    mask=overall.get('matched_mask_assessment',{});unmatched=data.get('unmatched_name_summary',{})
    mask_text=', '.join(f'{esc(k)}: {esc(mask.get(k,0))}' for k in ('acceptable','unacceptable','merged','unsure','unavailable','not_reviewed'))
    planes=overall.get('matched_plane_relation',{});plane_text=', '.join(f'{esc(k)}: {esc(planes.get(k,0))}' for k in ('same','different','unknown'))
    unmatched_rows=''.join(f'<tr><td>{esc(kind)}</td><td>{esc(item.get("proposals",0))}</td><td>{esc(item.get("genus",{}).get("named",0))}</td><td>{esc(item.get("species",{}).get("named",0))}</td></tr>' for kind,item in sorted(unmatched.items()))
    sample_rows=[]
    for sample,row in sorted(data['per_sample'].items()):
        genus=row['genus'];species=row['species']
        sample_rows.append('<tr>'+''.join(f'<td>{esc(x)}</td>' for x in (sample,f'{genus["correct"]} / {genus["eligible"]}',frac(genus['end_to_end_fraction']),
                                                                              f'{species["correct"]} / {species["eligible"]}',frac(species['end_to_end_fraction'])))+'</tr>')
    sample_section='<section class="scroll"><h2>By declared biological sample</h2><p>Fractions include detection misses and abstentions among eligible references. Sample IDs and biological independence require verification.</p><table><thead><tr><th>Sample</th><th>Genus correct / eligible</th><th>Genus fraction</th><th>Species correct / eligible</th><th>Species fraction</th></tr></thead><tbody>'+(''.join(sample_rows) or '<tr><td colspan="5">No sample records.</td></tr>')+'</tbody></table></section>'
    taxonomy=data.get('prediction_taxonomy_status')
    if taxonomy is None:taxonomy_section='<section><h2>Prediction taxonomy consistency</h2><p>No taxonomy-consistency summary was supplied.</p></section>'
    else:
        keys=('consistent','conflicting','unmapped','not_applicable','not_checked')
        if not isinstance(taxonomy,dict) or any(type(taxonomy.get(k)) is not int or taxonomy[k]<0 for k in keys):raise ValueError('Invalid prediction taxonomy summary')
        details=', '.join(f'{esc(k.replace("_"," "))}: {taxonomy[k]}' for k in keys)
        taxonomy_section='<section><h2>Prediction taxonomy consistency</h2><p>'+details+'. A consistent pair of names can still be wrong; this only reports agreement with the supplied frozen map. Unmapped, unassigned or unchecked predictions are not assumed consistent.</p></section>'
    bootstrap=data.get('sample_cluster_bootstrap')
    if bootstrap is None:uncertainty='<p>No sample-cluster uncertainty interval was supplied. A point estimate alone does not establish a target.</p>'
    else:
        if (not isinstance(bootstrap,dict) or bootstrap.get('method')!='sample-cluster percentile bootstrap of pooled correct/eligible'
            or bootstrap.get('confidence_level')!=.95 or type(bootstrap.get('replicates')) is not int or bootstrap['replicates']<1
            or bootstrap.get('sample_count')!=len(data['per_sample']) or not isinstance(bootstrap.get('ranks'),dict)):
            raise ValueError('Invalid sample-cluster bootstrap')
        intervals=[]
        for rank in ('genus','species'):
            record=bootstrap['ranks'].get(rank)
            if not isinstance(record,dict):raise ValueError('Invalid bootstrap rank')
            lower,upper=record.get('lower'),record.get('upper');valid=record.get('valid_replicates');zero=record.get('zero_denominator_replicates')
            if (type(valid) is not int or type(zero) is not int or min(valid,zero)<0 or valid+zero!=bootstrap['replicates']
                or (lower is None)!=(upper is None) or (lower is None)!=(valid==0) or (lower is not None and (type(lower) not in (int,float) or type(upper) not in (int,float)
                    or not math.isfinite(lower) or not math.isfinite(upper) or not 0<=lower<=upper<=1))):raise ValueError('Invalid bootstrap interval')
            interval='Not available' if lower is None else f'{frac(lower)} to {frac(upper)}'
            intervals.append(f'<li>{rank.title()}: {interval}; {valid} valid resamples, {zero} with no eligible specimens.</li>')
        uncertainty=f'<p>95% sample-cluster percentile intervals from {bootstrap["replicates"]} resamples (seed {esc(bootstrap.get("seed"))}).</p><ul>'+''.join(intervals)+'</ul><p>Intervals depend on independent sample IDs and can be unstable or spuriously narrow with few samples or rare errors. They do not establish target attainment.</p>'
    uncertainty_section='<section><h2>Uncertainty</h2>'+uncertainty+'</section>'
    page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Instance evaluation</title><style>body{font:16px/1.5 system-ui;background:#f4f6ef;color:#1c3835;margin:0}main{max-width:1100px;margin:auto;padding:24px}section,article{background:white;border:1px solid #d1dfd6;border-radius:5px;padding:16px;margin:12px 0}.notice{border-left:5px solid #b77b19}img{max-width:100%;height:auto}table{border-collapse:collapse;width:100%}td,th{border:1px solid #cad8d0;text-align:left;padding:6px}.scroll{overflow:auto}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:12px}</style><main><h1>Instance evaluation</h1>'''+warning+f'''<p>Protocol: {esc(data.get("protocol_id"))}; matching rule: {esc(data.get("matching_rule_id"))}; mask rule: {esc(data.get("mask_rule_id") or "not configured")}; taxonomy: {esc(data.get("taxonomy_version"))}.</p><p class="notice">These calculations rely on declared expert references, matches, eligibility, and independent samples. They do not verify those declarations or establish that the project’s accuracy targets have been met. A nonempty mask is not necessarily a correct mask.</p><section><h2>Identification across eligible specimens</h2><p>{esc(data.get("test_sample_count"))} declared test samples; {esc(data.get("field_count"))} fields. Missed specimens remain in the denominator; ineligible specimens are excluded under the declared protocol.</p><img src="identification-breakdown.svg" alt="Stacked bars showing correct names, incorrect names, abstentions, and missed specimens for genus and species"><div class="grid">{''.join(summaries)}</div></section><section><h2>Overlap and mask review</h2><p>{groups['fully_detected']} / {groups['groups']} overlap groups have every member matched; {groups['fully_detected_with_nonempty_masks']} have a nonempty mask for every member; {groups['fully_detected_with_acceptable_masks']} have every matched mask declared acceptable.</p><p>Groups with unreviewed matched masks: {groups['groups_with_unreviewed_matched_masks']}; with unsure matched masks: {groups['groups_with_unsure_matched_masks']}; with a mask marked merged: {groups['groups_with_merged_matched_masks']}; with an additional same-group reference named in a merged mask: {groups['groups_with_identified_merged_neighbors']}. Cross-plane matched groups: {groups['groups_with_cross_plane_matches']}. These categories may overlap. Additional references inside a merged mask are not counted as separate matched proposals. Matched-mask assessments: {mask_text}.</p><p>Matched focal-plane relationships: {plane_text}. Different recorded planes do not establish a mismatch, and equal plane numbers do not prove spatial registration.</p></section><section class="scroll"><h2>By reference genus</h2>{table('genus')}<h2>By reference species</h2>{table('species')}<p>Small taxon and sample counts are descriptive; they do not establish population-level accuracy.</p></section><section class="scroll"><h2>Unmatched proposals</h2><p>Categories are declared by the matcher; an unmatched proposal is not automatically a false positive or an unseen taxon.</p><table><thead><tr><th>Category</th><th>Proposals</th><th>Named genus</th><th>Named species</th></tr></thead><tbody>{unmatched_rows}</tbody></table></section><p><a href="evaluation.json">Evaluation data</a> · Source SHA-256: {digest(a.input)}</p></main></html>'''
    page=page.replace('<h2>Overlap and mask review</h2>','<h2>Overlap and mask review</h2><p>'+field_overlap_note+'</p>')
    page=page.replace('<section><h2>Overlap and mask review</h2>',sample_section+uncertainty_section+taxonomy_section+'<section><h2>Overlap and mask review</h2>')
    shutil.copyfile(a.input,a.output/'evaluation.json');(a.output/'index.html').write_text(page)
    print(f'Wrote a descriptive report to {a.output}; input declarations remain unverified.')


if __name__=='__main__':main()
