"""Synthetic checks for declaring held-out fields without labeled crop rows."""
import hashlib
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path

ROOT=Path(__file__).resolve().parents[2]
def sha(path):return hashlib.sha256(path.read_bytes()).hexdigest()


class FieldSplitTest(unittest.TestCase):
    def setUp(self):
        self.temp=tempfile.TemporaryDirectory();self.root=Path(self.temp.name);self.model=self.root/'model';self.model.mkdir();(self.model/'centroids.npz').write_bytes(b'synthetic')
        model={'format':'diatom-centroid-classifier-v1','label_rank':'genus','test_status':'test images not opened or scored','held_out_test_rows':0,
               'train_samples':['train'],'validation_samples':['validation'],'held_out_test_samples':[],'encoder_sha256':'e'*64,
               'dataset_sha256':'d'*64,'centroids_sha256':sha(self.model/'centroids.npz')};(self.model/'model.json').write_text(json.dumps(model))
        crop={'format':'diatom-centroid-frozen-protocol-v1','rank':'genus','threshold':0.0,'threshold_rule':'accept if cosine similarity >= threshold',
              'threshold_source':'declared_validation_report','model_sha256':sha(self.model/'model.json'),'centroids_sha256':model['centroids_sha256'],
              'dataset_sha256':model['dataset_sha256'],'encoder_sha256':model['encoder_sha256']};self.crop=self.write('crop.json',crop)
        hashes={k:'a'*64 for k in ('detector_sha256','segmenter_sha256','encoder_sha256','gallery_manifest_sha256')}
        self.dev=self.write('dev.json',{'format':'diatom-field-bundle-v1','slide':'development.tif','size':16,'models':hashes,'detector_confidence':.05,'max_candidates':30})
        self.fields=self.write('fields.json',{'format':'diatom-held-out-fields-v1','fields':[{'id':'field','sample_id':'test','slide':'unread-test.tif','origin_xy':[0,0],'z':0,'size':16}]})
        self.splits={'format':'diatom-sample-splits-v1','samples':{'train':'train','validation':'validation','test':'test'}}
    def tearDown(self):self.temp.cleanup()
    def write(self,name,value):
        path=self.root/name;path.write_text(json.dumps(value));return path
    def freeze(self,split=True,extra=()):
        args=[sys.executable,str(ROOT/'diatom_pilot/freeze_field_protocol.py'),'--development-bundle',str(self.dev),'--test-fields',str(self.fields),
              '--protocol-id','synthetic','--matching-rule-id','synthetic','--taxonomy-version','synthetic','--genus-model',str(self.model),'--genus-protocol',str(self.crop),'--output',str(self.root/'out.json')]
        if split:args+=['--sample-splits',str(self.write('splits.json',self.splits))]
        args+=list(extra)
        return subprocess.run(args,capture_output=True,text=True)
    def test_predeclared_test_sample_without_crop_rows(self):
        result=self.freeze();self.assertEqual(result.returncode,0,result.stderr)
        out=json.loads((self.root/'out.json').read_text());self.assertEqual(out['fields'][0]['sample_id'],'test');self.assertEqual(out['sample_splits_sha256'],sha(self.root/'splits.json'))
    def test_missing_split_or_train_collision_is_rejected(self):
        result=self.freeze(split=False);self.assertNotEqual(result.returncode,0);self.assertIn('sample split',result.stderr)
        self.splits['samples']['test']='train';result=self.freeze();self.assertNotEqual(result.returncode,0);self.assertIn('declared test',result.stderr)
    def test_overlapping_fields_require_explicit_handling_even_across_planes(self):
        data=json.loads(self.fields.read_text());data['fields'].append({'id':'field2','sample_id':'test','slide':'unread-test.tif','origin_xy':[8,0],'z':1,'size':16});self.fields.write_text(json.dumps(data))
        result=self.freeze();self.assertNotEqual(result.returncode,0);self.assertIn('overlap-handling rule',result.stderr)
        result=self.freeze(extra=['--overlap-handling-id','synthetic-ownership']);self.assertEqual(result.returncode,0,result.stderr)
        out=json.loads((self.root/'out.json').read_text());self.assertEqual(out['overlapping_field_pairs'],[['field','field2']]);self.assertEqual(out['overlap_handling_id'],'synthetic-ownership')
    def test_same_slide_cannot_be_assigned_to_different_samples(self):
        data=json.loads(self.fields.read_text());data['fields'].append({'id':'field2','sample_id':'another','slide':'unread-test.tif','origin_xy':[32,0],'z':0,'size':16});self.fields.write_text(json.dumps(data))
        result=self.freeze();self.assertNotEqual(result.returncode,0);self.assertIn('different sample IDs',result.stderr)
    def test_practice_and_unlabeled_development_plans_are_not_held_out(self):
        plan={'format':'diatom-development-field-plan-v1','fields':[{'slide':'other.tif','sample_id':'','split':'practice'}]}
        path=self.write('dev-plan.json',plan);result=self.freeze(extra=['--development-plan',str(path)])
        self.assertEqual(result.returncode,0,result.stderr)
        self.assertEqual(json.loads((self.root/'out.json').read_text())['development_plan_sha256'],[sha(path)])
        (self.root/'out.json').unlink();plan['fields'][0]['slide']='unread-test.tif';path.write_text(json.dumps(plan))
        result=self.freeze(extra=['--development-plan',str(path)]);self.assertNotEqual(result.returncode,0);self.assertIn('plan scan is declared held out',result.stderr)
        plan['fields'][0].update(slide='another.tif',sample_id='test');path.write_text(json.dumps(plan))
        result=self.freeze(extra=['--development-plan',str(path)]);self.assertNotEqual(result.returncode,0);self.assertIn('plan sample is declared held out',result.stderr)
    def test_taxonomy_map_is_frozen_and_version_checked(self):
        taxonomy=self.write('taxonomy.json',{'format':'diatom-taxonomy-map-v1','version':'synthetic','species_to_genus':{'A one':'A'}})
        result=self.freeze(extra=['--taxonomy-map',str(taxonomy)]);self.assertEqual(result.returncode,0,result.stderr)
        self.assertEqual(json.loads((self.root/'out.json').read_text())['taxonomy_map_sha256'],sha(taxonomy))
        (self.root/'out.json').unlink();taxonomy.write_text(json.dumps({'format':'diatom-taxonomy-map-v1','version':'wrong','species_to_genus':{'A one':'A'}}))
        result=self.freeze(extra=['--taxonomy-map',str(taxonomy)]);self.assertNotEqual(result.returncode,0);self.assertIn('mismatched frozen taxonomy',result.stderr)
    def test_registry_detects_related_development_and_test_slides(self):
        dev=json.loads(self.dev.read_text());dev['slide_size_bytes']=1_000_000_000;self.dev.write_text(json.dumps(dev))
        fields=json.loads(self.fields.read_text());fields['fields'][0]['slide_size_bytes']=1_100_000_000;self.fields.write_text(json.dumps(fields))
        inventory={'format':'diatom-scan-inventory-v1','slides':[{'name':'development.tif','size_bytes':1_000_000_000},{'name':'unread-test.tif','size_bytes':1_100_000_000}]}
        inv=self.write('inventory.json',inventory)
        registry={'format':'diatom-sample-registry-v1','inventory':inventory,'inventory_sha256':sha(inv),'reviewer_id':'synthetic','reviewer_role':'nonexpert',
                  'slides':[{'name':'development.tif','size_bytes':1_000_000_000,'sample_id':'train','confidence':'reported','note':''},
                            {'name':'unread-test.tif','size_bytes':1_100_000_000,'sample_id':'test','confidence':'reported','note':''}]}
        reg=self.write('registry.json',registry);args=['--sample-registry',str(reg),'--sample-inventory',str(inv)]
        result=self.freeze(extra=args);self.assertEqual(result.returncode,0,result.stderr)
        self.assertEqual(json.loads((self.root/'out.json').read_text())['sample_registry']['registry_sha256'],sha(reg))
        (self.root/'out.json').unlink();registry['slides'][0]['sample_id']='test';reg.write_text(json.dumps(registry))
        result=self.freeze(extra=args);self.assertNotEqual(result.returncode,0);self.assertIn('same biological sample',result.stderr)
        registry['slides'][0]['sample_id']='train';registry['slides'][1]['sample_id']='train';reg.write_text(json.dumps(registry))
        result=self.freeze(extra=args);self.assertNotEqual(result.returncode,0);self.assertIn('conflicts with registry',result.stderr)


if __name__=='__main__':unittest.main()
