"""Prepare traceable, sample-separated taxon crops from reviewed packages."""
import argparse
import json
import shutil
from collections import Counter
from pathlib import Path
from PIL import Image

from ingest_review import digest,inside
from cross_field_review_guard import read_review as read_cross_field_review
from sample_registry_guard import read_registry


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--package',type=Path,action='append',required=True,help='Reviewed specimen package directory; repeat for each package')
    p.add_argument('--split-map',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
    p.add_argument('--allow-provisional',action='store_true',help='Include explicitly labeled unadjudicated examples for development')
    p.add_argument('--rank',choices=('species','genus'),default='species')
    p.add_argument('--taxonomy-map',type=Path,help='Explicit species-to-genus mapping for genus datasets')
    p.add_argument('--sample-registry',type=Path,help='Downloaded scan-to-sample registry')
    p.add_argument('--sample-inventory',type=Path,help='Exact inventory.json used by the registry page')
    for name in ('cross-field-review','cross-field-pairs','cross-field-jobs','cross-field-batch'):
        p.add_argument('--'+name,type=Path,action='append',default=[],help='Cross-field evidence; repeat all four arguments in matching order')
    a=p.parse_args();split_data=json.loads(a.split_map.read_text())
    if bool(a.sample_registry)!=bool(a.sample_inventory):p.error('Provide both sample registry and sample inventory')
    registry,registry_provenance=read_registry(a.sample_registry,a.sample_inventory) if a.sample_registry else (None,None)
    evidence_lists=(a.cross_field_review,a.cross_field_pairs,a.cross_field_jobs,a.cross_field_batch)
    if len({len(x) for x in evidence_lists})!=1:p.error('Provide one review, pairs file, jobs file, and batch directory per cross-field evidence set')
    mapping={}
    if a.taxonomy_map:
        if a.rank!='genus':p.error('taxonomy-map is only used when preparing genus data')
        taxonomy=json.loads(a.taxonomy_map.read_text());mapping=taxonomy.get('species_to_genus')
        if (taxonomy.get('format')!='diatom-taxonomy-map-v1' or not isinstance(taxonomy.get('version'),str) or not taxonomy['version'].strip()
            or not isinstance(mapping,dict) or any(not isinstance(k,str) or not k or k!=k.strip() or not isinstance(v,str) or not v or v!=v.strip() for k,v in mapping.items())):raise ValueError('Invalid taxonomy map')
    if split_data.get('format')!='diatom-sample-splits-v1' or not isinstance(split_data.get('samples'),dict):raise ValueError('Invalid sample split map')
    splits=split_data['samples']
    if not splits or any(not isinstance(k,str) or not k or k!=k.strip() or v not in {'train','validation','test'} for k,v in splits.items()):raise ValueError('Invalid sample or split')
    if len({x.resolve() for x in a.package})!=len(a.package):raise ValueError('Duplicate package path')
    items=[];excluded=Counter();seen_reviews=set();hash_splits={};field_splits={};slide_samples={};package_records=[];global_same_links=[]
    for directory in a.package:
        manifest=directory/'specimens.json';data=json.loads(manifest.read_text())
        if data.get('format')!='diatom-reviewed-specimens-v1' or not isinstance(data.get('specimens'),list):raise ValueError('Invalid specimen package')
        sample=data.get('sample_id');split=splits.get(sample)
        if split is None:raise ValueError(f'Sample has no declared split: {sample}')
        context=data.get('review_context_as_exported') or {}
        if not isinstance(context,dict):raise ValueError('Invalid exported review context')
        development_split=context.get('development_split')
        if development_split is not None:
            if development_split not in {'practice','train','validation'}:raise ValueError('Invalid recorded development split')
            if development_split=='practice':raise ValueError('Practice annotations cannot be used in classifier datasets')
            if split!=development_split:raise ValueError('Recorded development split conflicts with sample split')
        slide=data.get('slide')
        if not isinstance(slide,str) or not slide or Path(slide).name!=slide:raise ValueError('Missing or invalid slide provenance')
        if registry is not None:
            entry=registry.get(slide)
            if not entry or not entry['sample_id']:raise ValueError(f'Slide is absent or unassigned in sample registry: {slide}')
            if entry['sample_id']!=sample:raise ValueError(f'Sample ID conflicts with registry: {slide}')
            if data.get('slide_size_bytes')!=entry['size_bytes']:raise ValueError(f'Slide size missing or conflicts with registry: {slide}; re-ingest the review if necessary')
        if slide in slide_samples and slide_samples[slide]!=sample:raise ValueError('Same slide has different biological sample IDs')
        slide_samples[slide]=sample
        review_hash=data.get('review_source_sha256')
        if not isinstance(review_hash,str) or len(review_hash)!=64 or review_hash in seen_reviews:raise ValueError('Missing or duplicate review provenance')
        seen_reviews.add(review_hash);package_records.append({'manifest_sha256':digest(manifest),'review_source_sha256':review_hash,'sample_id':sample,'split':split})
        ids=set();package_item_start=len(items)
        for specimen in data['specimens']:
            ident=specimen.get('id')
            if not isinstance(ident,str) or not ident or ident in ids:raise ValueError('Invalid or repeated specimen ID')
            ids.add(ident)
            if specimen.get('decision') not in {'possible','countable'}:excluded['decision_not_included']+=1;continue
            label=specimen.get('taxon_text')
            source_rank=specimen.get('taxon_rank')
            if not isinstance(label,str) or not label.strip():excluded['no_usable_taxon']+=1;continue
            source_label=label.strip()
            if a.rank=='species':
                if source_rank!='species':excluded['no_explicit_species']+=1;continue
                label=source_label
            elif source_rank=='genus':label=source_label
            elif source_rank=='species' and source_label in mapping:label=mapping[source_label]
            else:excluded['no_explicit_or_mapped_genus']+=1;continue
            if specimen.get('identification_certainty')=='unresolved':excluded['unresolved_identification']+=1;continue
            adjudication=specimen.get('adjudication') or {}
            is_adjudicated=(specimen.get('adjudicated') is True and data.get('adjudicated') is True
                            and adjudication.get('verdict')=='confirmed' and adjudication.get('reviewer_role')=='expert'
                            and bool(adjudication.get('reviewer_id')) and bool(adjudication.get('protocol_id')))
            if not is_adjudicated and not a.allow_provisional:excluded['not_adjudicated']+=1;continue
            if not is_adjudicated and split=='test':raise ValueError('Provisional specimens cannot be placed in the held-out test split')
            if split=='test' and specimen.get('identification_certainty')!='confident':raise ValueError('Held-out test labels must be explicitly confident')
            crop=specimen.get('crop');geometry=specimen.get('geometry')
            if not isinstance(crop,dict) or not isinstance(geometry,dict) or geometry.get('kind') not in {'reviewer_polygon','model_mask_unverified','model_mask_reviewer_selected'}:
                excluded['no_instance_geometry']+=1;continue
            image=inside(directory,crop.get('image'));mask=inside(directory,crop.get('mask'))
            image_hash=digest(image);mask_hash=digest(mask)
            if image_hash!=crop.get('image_sha256') or mask_hash!=crop.get('mask_sha256'):raise ValueError('Crop or mask hash mismatch')
            with Image.open(image) as im,Image.open(mask) as mk:
                if im.size!=mk.size or mk.convert('L').getbbox() is None:raise ValueError('Empty or mismatched specimen mask')
            if image_hash in hash_splits and hash_splits[image_hash]!=split:raise ValueError('Exact crop occurs across sample splits')
            hash_splits[image_hash]=split
            field_hash=crop.get('source_field_sha256')
            if not isinstance(field_hash,str) or len(field_hash)!=64:raise ValueError('Missing source field hash')
            if field_hash in field_splits and field_splits[field_hash]!=split:raise ValueError('Source field occurs across sample splits')
            field_splits[field_hash]=split
            items.append({'sample_id':sample,'split':split,a.rank:label,'source_taxon':source_label,'source_taxon_rank':source_rank,
                          'certainty':specimen.get('identification_certainty','unknown'),
                          'adjudicated':is_adjudicated,'reviewer_role':data.get('reviewer_role'),
                          'adjudicator_role':adjudication.get('reviewer_role') if is_adjudicated else None,
                          'adjudication_sha256':adjudication.get('decisions_sha256') if is_adjudicated else None,
                          'adjudication_protocol_id':adjudication.get('protocol_id') if is_adjudicated else None,
                          'review_source_sha256':review_hash,
                          'bundle_id':data['bundle_id'],'slide':slide,'source_field_sha256':field_hash,
                          'specimen_id':ident,'geometry_kind':geometry['kind'],
                          'partial':specimen.get('partial','unknown'),'overlap':specimen.get('overlap','unknown'),
                          'overlap_group':specimen.get('overlap_group',''),'image_sha256':image_hash,'mask_sha256':mask_hash,
                          '_image':image,'_mask':mask})
        # Do not silently count two eligible crops as independent specimens when
        # the field reviewer has explicitly raised a possible duplicate.
        relationships=data.get('candidate_relationships',[])
        if not isinstance(relationships,list):raise ValueError('Invalid candidate relationships in specimen package')
        eligible={item['specimen_id'] for item in items[package_item_start:]}
        seen_pairs=set();same_links=[]
        for relation in relationships:
            if not isinstance(relation,dict):raise ValueError('Invalid candidate relationship in specimen package')
            left,right,assessment=relation.get('a'),relation.get('b'),relation.get('relation')
            if (not isinstance(left,str) or not isinstance(right,str) or left>=right
                or not isinstance(assessment,str) or assessment not in {'same','different','unsure'}
                or (left,right) in seen_pairs):raise ValueError('Invalid or duplicate candidate relationship in specimen package')
            seen_pairs.add((left,right))
            expert=relation.get('expert_assessment')
            if expert is not None:
                adjudication=data.get('adjudication') or {}
                if (not isinstance(expert,dict) or data.get('adjudicated') is not True
                    or expert.get('reviewer_role')!='expert' or not expert.get('reviewer_id') or not expert.get('protocol_id')
                    or expert.get('reviewer_id')!=adjudication.get('reviewer_id') or expert.get('protocol_id')!=adjudication.get('protocol_id')
                    or expert.get('decisions_sha256')!=adjudication.get('decisions_sha256')
                    or expert.get('relation') not in {'same','different','unsure'}):
                    raise ValueError('Invalid expert pair assessment provenance')
                assessment=expert['relation']
            if assessment in {'same','unsure'} and left in eligible and right in eligible:
                raise ValueError(f'Possible duplicate eligible specimens in {directory}: {left} and {right} ({assessment}). '
                                 'Review the pair or exclude one candidate, then regenerate the appropriate review package.')
            if assessment=='same':same_links.append((left,right))
        # A noneligible intermediate candidate can still connect two eligible
        # crops through likely-same assessments. Treat the chain as a review
        # warning, not proof that its endpoints are the same specimen.
        parents={}
        def root(ident):
            parents.setdefault(ident,ident)
            while parents[ident]!=ident:
                parents[ident]=parents[parents[ident]];ident=parents[ident]
            return ident
        for left,right in same_links:
            left_root,right_root=root(left),root(right)
            if left_root!=right_root:parents[left_root]=right_root
            global_same_links.append(((data['bundle_id'],left),(data['bundle_id'],right)))
        components={}
        for ident in eligible:
            if ident in parents:components.setdefault(root(ident),[]).append(ident)
        for members in components.values():
            if len(members)>1:
                raise ValueError(f'Possible duplicate eligible specimens in {directory}: {", ".join(sorted(members))} '
                                 '(connected by likely-same assessments). Review the relationships and regenerate the review package.')
    eligible_nodes={}
    for item in items:
        key=(item['bundle_id'],item['specimen_id'])
        if key in eligible_nodes:raise ValueError(f'Duplicate eligible candidate identity across review packages: {key}')
        eligible_nodes[key]=item
    cross_records=[];cross_evidence=[];seen_evidence=set()
    for review_path,pairs_path,jobs_path,batch in zip(*evidence_lists):
        records,provenance=read_cross_field_review(review_path,pairs_path,jobs_path,batch)
        if provenance['pairs_sha256'] in seen_evidence:raise ValueError('Duplicate cross-field evidence source')
        seen_evidence.add(provenance['pairs_sha256']);cross_evidence.append(provenance);cross_records.extend(records)
    for left,right,assessment in cross_records:
        if assessment in {'same','unsure'} and left in eligible_nodes and right in eligible_nodes:
            raise ValueError(f'Possible cross-field duplicate eligible specimens: {left} and {right} ({assessment}). Review the pair or exclude one candidate.')
        if assessment=='same':global_same_links.append((left,right))
    parents={}
    def global_root(ident):
        parents.setdefault(ident,ident)
        while parents[ident]!=ident:
            parents[ident]=parents[parents[ident]];ident=parents[ident]
        return ident
    for left,right in global_same_links:
        left_root,right_root=global_root(left),global_root(right)
        if left_root!=right_root:parents[left_root]=right_root
    components={}
    for ident in eligible_nodes:
        if ident in parents:components.setdefault(global_root(ident),[]).append(ident)
    for members in components.values():
        if len(members)>1:raise ValueError(f'Possible cross-field or within-field duplicates connected by likely-same assessments: {sorted(members)}. Review the links before preparing data.')
    if not items:raise ValueError(f'No eligible {a.rank} crops; exclusions: {dict(excluded)}')
    if not any(x['split']=='train' for x in items):raise ValueError('No eligible training crops')
    if a.output.exists() and any(a.output.iterdir()):raise FileExistsError('Output directory must be empty')
    a.output.mkdir(parents=True,exist_ok=True);(a.output/'images').mkdir();(a.output/'masks').mkdir()
    for i,item in enumerate(items,1):
        image=f'images/{i:06d}.png';mask=f'masks/{i:06d}.png';shutil.copyfile(item.pop('_image'),a.output/image);shutil.copyfile(item.pop('_mask'),a.output/mask)
        item.update(image=image,mask=mask)
    result={'format':'diatom-classifier-data-v1','label_rank':a.rank,'taxonomy_sha256':digest(a.taxonomy_map) if a.taxonomy_map else None,
            'sample_splits_sha256':digest(a.split_map),'packages':package_records,'cross_field_reviews':cross_evidence,'sample_registry':registry_provenance,
            'allow_provisional':a.allow_provisional,'excluded_counts':dict(excluded),'rows':items,
            'warning':'Reviewer labels are not automatically adjudicated; duplicate specimens and sample relationships require human review. Do not use test rows for training or model selection.'}
    (a.output/'dataset.json').write_text(json.dumps(result,indent=2)+'\n')
    print(f'Prepared {len(items)} labeled instance crops; exclusions: {dict(excluded)}')


if __name__=='__main__':main()
