"""Build the static monitoring data from explicitly cataloged evaluations.

Inputs are expert-declared instance evaluation manifests, not model result claims.
Only validation/development runs with identical references and rules are compared.
"""
import argparse
import hashlib
import json
import os
from datetime import datetime, timezone
from pathlib import Path
from evaluate_instances import evaluate


def reference_id(data):
    fields=[]
    for f in data['fields']:
        fields.append({'field_id':f['field_id'],'sample_id':f['sample_id'],'exhaustive':f['exhaustive'],
                       'references':sorted(f['references'],key=lambda r:r['id'])})
    payload={'fields':sorted(fields,key=lambda f:f['field_id']),'matching_rule_id':data['matching_rule_id'],
             'mask_rule_id':data.get('mask_rule_id'),'taxonomy_version':data['taxonomy_version'],
             'field_overlap_handling_id':data.get('field_overlap_handling_id'),
             'overlapping_field_pairs':data.get('overlapping_field_pairs')}
    return hashlib.sha256(json.dumps(payload,sort_keys=True,separators=(',',':'),ensure_ascii=False).encode()).hexdigest()


def build(catalog,root):
    if catalog.get('format')!='diatom-performance-catalog-v1' or not isinstance(catalog.get('runs'),list):raise ValueError('Invalid performance catalog')
    records=[];ids=set()
    for row in catalog['runs']:
        if not isinstance(row,dict):raise ValueError('Invalid run entry')
        ident=row.get('id');label=row.get('label');kind=row.get('kind');date=row.get('date');path=row.get('input')
        if (not isinstance(ident,str) or not ident.strip() or ident in ids or not isinstance(label,str) or not label.strip()
            or kind not in {'provisional_development','development','held_out_test','synthetic'} or not isinstance(date,str) or not isinstance(path,str)):
            raise ValueError('Invalid run metadata')
        try:timestamp=datetime.fromisoformat(date.replace('Z','+00:00'))
        except ValueError:raise ValueError('Run date must be ISO 8601')
        if timestamp.tzinfo is None:raise ValueError('Run date must include a timezone')
        source=(root/path).resolve()
        if not source.is_relative_to(root.resolve()) or not source.is_file():raise ValueError('Run input must be an existing project file')
        raw=source.read_bytes();data=json.loads(raw);development=data.get('split')=='development'
        if kind in {'development','provisional_development'} and not development or kind=='held_out_test' and data.get('split')!='held_out_test':raise ValueError('Run kind conflicts with data split')
        if kind=='synthetic' and data.get('split') not in {'development','held_out_test'}:raise ValueError('Invalid synthetic split')
        if kind!='synthetic' and ('synthetic' in str(data.get('protocol_id','')).lower() or 'synthetic' in str(data.get('description','')).lower()):raise ValueError('Synthetic evidence cannot be cataloged as a real run')
        result=evaluate(data,development=development,provisional=kind=='provisional_development');overall=result['overall'];groups=result['overlap_group_summary'];partial=result['strata']['partial_yes']
        report=row.get('report')
        if report is not None:
            if not isinstance(report,str) or not report.startswith('/results/') or '..' in Path(report).parts or not (root/report.lstrip('/')).exists():raise ValueError('Report must be a local results path')
        records.append({'id':ident,'label':label,'kind':kind,'date':timestamp.astimezone(timezone.utc).isoformat(),'input_sha256':hashlib.sha256(raw).hexdigest(),
            'reference_signature':reference_id(data),'protocol_id':data['protocol_id'],'matching_rule_id':data['matching_rule_id'],
            'sample_count':result['test_sample_count'],'field_count':result['field_count'],'report':report,
            'instances':overall['instances'],'detected':overall['detected'],
            'partial_instances':partial['instances'],'partial_detected':partial['detected'],
            'overlap_groups':groups['groups'],'overlap_groups_detected':groups['fully_detected'],
            'mask_assessment':overall['matched_mask_assessment'],
            'genus':{k:overall['genus'][k] for k in ('correct','eligible','missed','detected_abstentions')},
            'species':{k:overall['species'][k] for k in ('correct','eligible','missed','detected_abstentions')}})
        ids.add(ident)
    return {'format':'diatom-performance-monitor-v1','generated_at':datetime.now(timezone.utc).isoformat(),
            'runs':sorted(records,key=lambda r:(r['date'],r['id']))}


def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--catalog',type=Path,required=True);p.add_argument('--output',type=Path,required=True);p.add_argument('--root',type=Path,default=Path(__file__).resolve().parents[1]);a=p.parse_args()
    result=build(json.loads(a.catalog.read_text()),a.root);a.output.parent.mkdir(parents=True,exist_ok=True)
    tmp=a.output.with_name(a.output.name+'.tmp');tmp.write_text(json.dumps(result,indent=2)+'\n');os.replace(tmp,a.output)
    print(f'Published {len(result["runs"])} declared evaluation runs.')

if __name__=='__main__':main()
