"""Synthetic checks for the frozen-prediction / expert-reference boundary."""
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 AssemblyTest(unittest.TestCase):
    def setUp(self):
        self.temp=tempfile.TemporaryDirectory();self.root=Path(self.temp.name)
        protocol={'format':'diatom-frozen-field-protocol-v1','candidate_policy':'all_original_detector_candidates',
                  'development_sample_ids':['train'],'protocol_id':'synthetic','matching_rule_id':'synthetic-rule',
                  'mask_rule_id':'synthetic-mask-rule','taxonomy_version':'synthetic-taxonomy','fields':[{'id':'field','sample_id':'test'}]}
        self.protocol=self.write('protocol.json',protocol)
        predictions={'format':'diatom-frozen-field-predictions-v1','protocol_sha256':sha(self.protocol),
                     'candidate_policy':protocol['candidate_policy'],'field_id':'field','sample_id':'test',
                     'predictions':[{'id':'p1','genus':'A','species':'A one','mask_status':'nonempty'},
                                    {'id':'p2','genus':None,'species':None,'mask_status':'missing'}]}
        self.predictions=self.write('predictions.json',predictions)
        def ref(ident):
            return {'id':ident,'genus':'A','species':'A one','genus_eligible':True,'species_eligible':True,
                    'partial':'yes','overlap_group':'group'}
        self.reference={'format':'diatom-expert-field-reference-v1','protocol_sha256':sha(self.protocol),
            'reference_status':'expert_adjudicated','matching_status':'expert_adjudicated','reviewer_role':'expert',
            'reviewer_id':'synthetic-only','matching_rule_id':'synthetic-rule','taxonomy_version':'synthetic-taxonomy',
            'development_sample_ids':['train'],'fields':[{'id':'field','sample_id':'test','exhaustive':True,
            'predictions_sha256':sha(self.predictions),'references':[ref('r1'),ref('r2')],
            'matches':[{'prediction_id':'p1','reference_id':'r1','mask_assessment':'acceptable'},
                       {'prediction_id':'p2','reference_id':None,'unmatched_type':'duplicate','mask_assessment':'not_applicable'}]}]}

    def tearDown(self):self.temp.cleanup()

    def write(self,name,value):
        path=self.root/name;path.write_text(json.dumps(value));return path

    def assemble(self,extra=()):
        reference=self.write('reference.json',self.reference);output=self.root/'evaluation.json'
        run=subprocess.run([sys.executable,str(ROOT/'diatom_pilot/assemble_instance_evaluation.py'),
                            '--protocol',str(self.protocol),'--predictions',str(self.predictions),
                            '--expert-reference',str(reference),'--output',str(output),*map(str,extra)],capture_output=True,text=True)
        return run,output

    def enable_taxonomy(self):
        taxonomy=self.write('taxonomy.json',{'format':'diatom-taxonomy-map-v1','version':'synthetic-taxonomy','species_to_genus':{'A one':'A'}})
        protocol=json.loads(self.protocol.read_text());protocol['taxonomy_map_sha256']=sha(taxonomy);self.protocol.write_text(json.dumps(protocol))
        predictions=json.loads(self.predictions.read_text());predictions['protocol_sha256']=sha(self.protocol);predictions['predictions'][0]['genus']='B';self.predictions.write_text(json.dumps(predictions))
        self.reference['protocol_sha256']=sha(self.protocol);self.reference['fields'][0]['predictions_sha256']=sha(self.predictions)
        return taxonomy

    def test_missed_overlapping_specimen_and_duplicate_remain(self):
        run,output=self.assemble();self.assertEqual(run.returncode,0,run.stderr)
        sys.path.insert(0,str(ROOT/'diatom_pilot'))
        try:
            from evaluate_instances import evaluate
            result=evaluate(json.loads(output.read_text()))
        finally:sys.path.pop(0)
        self.assertEqual(result['overall']['species']['missed'],1)
        self.assertEqual(result['fields'][0]['unmatched_predictions']['duplicate'],1)
        self.assertEqual(result['overlap_group_summary']['fully_detected'],0)
        self.assertEqual(result['overall']['matched_mask_status']['nonempty'],1)
        self.assertEqual(result['overall']['matched_mask_assessment']['acceptable'],1)
        self.assertEqual(result['overall']['species']['correct_with_acceptable_mask'],1)

    def test_box_matches_do_not_imply_masks(self):
        self.reference['fields'][0]['matches'][1]={'prediction_id':'p2','reference_id':'r2','mask_assessment':'unavailable'}
        run,output=self.assemble();self.assertEqual(run.returncode,0,run.stderr)
        sys.path.insert(0,str(ROOT/'diatom_pilot'))
        try:
            from evaluate_instances import evaluate
            result=evaluate(json.loads(output.read_text()))
        finally:sys.path.pop(0)
        self.assertEqual(result['overall']['detected'],2)
        self.assertEqual(result['overall']['matched_mask_status']['missing'],1)
        self.assertEqual(result['overlap_group_summary']['fully_detected'],1)
        self.assertEqual(result['overlap_group_summary']['fully_detected_with_nonempty_masks'],0)
        self.assertEqual(result['overlap_group_summary']['fully_detected_with_acceptable_masks'],0)

    def test_rejects_missing_or_reused_matches(self):
        matches=self.reference['fields'][0]['matches'];matches.pop()
        run,_=self.assemble();self.assertNotEqual(run.returncode,0)
        self.assertIn('Each prediction requires exactly one expert match',run.stderr)
        matches.append({'prediction_id':'p2','reference_id':'r1'})
        run,_=self.assemble();self.assertNotEqual(run.returncode,0)
        self.assertIn('multiple matches for one reference',run.stderr)

    def test_rejects_changed_prediction_provenance(self):
        self.reference['fields'][0]['predictions_sha256']='0'*64
        run,_=self.assemble();self.assertNotEqual(run.returncode,0)
        self.assertIn('Invalid reference or prediction provenance',run.stderr)

    def test_taxonomy_conflict_is_reported_without_changing_prediction(self):
        taxonomy=self.enable_taxonomy();run,output=self.assemble(extra=('--taxonomy-map',taxonomy));self.assertEqual(run.returncode,0,run.stderr)
        result=json.loads(output.read_text());prediction=result['fields'][0]['predictions'][0]
        self.assertEqual((prediction['genus'],prediction['species'],prediction['taxonomy_status']),('B','A one','conflicting'))
        sys.path.insert(0,str(ROOT/'diatom_pilot'))
        try:
            from evaluate_instances import evaluate
            self.assertEqual(evaluate(result)['prediction_taxonomy_status']['conflicting'],1)
        finally:sys.path.pop(0)

    def test_frozen_taxonomy_rejects_inconsistent_reference(self):
        taxonomy=self.enable_taxonomy();self.reference['fields'][0]['references'][0]['genus']='B'
        run,_=self.assemble(extra=('--taxonomy-map',taxonomy));self.assertNotEqual(run.returncode,0)
        self.assertIn('Reference genus conflicts',run.stderr)

    def test_cannot_mark_a_missing_mask_acceptable(self):
        self.reference['fields'][0]['matches'][1]={'prediction_id':'p2','reference_id':'r2','mask_assessment':'acceptable'}
        run,_=self.assemble();self.assertNotEqual(run.returncode,0)
        self.assertIn('Mask assessment conflicts',run.stderr)

    def test_unreviewed_mask_does_not_yield_a_complete_fraction(self):
        self.reference['fields'][0]['matches'][0]['mask_assessment']='not_reviewed'
        run,output=self.assemble();self.assertEqual(run.returncode,0,run.stderr)
        sys.path.insert(0,str(ROOT/'diatom_pilot'))
        try:
            from evaluate_instances import evaluate
            result=evaluate(json.loads(output.read_text()))
        finally:sys.path.pop(0)
        self.assertFalse(result['overall']['species']['mask_assessment_complete'])
        self.assertIsNone(result['overall']['species']['correct_with_acceptable_mask_fraction'])

    def test_unsure_mask_does_not_yield_a_complete_fraction(self):
        self.reference['fields'][0]['matches'][0]['mask_assessment']='unsure'
        run,output=self.assemble();self.assertEqual(run.returncode,0,run.stderr)
        sys.path.insert(0,str(ROOT/'diatom_pilot'))
        try:
            from evaluate_instances import evaluate
            result=evaluate(json.loads(output.read_text()))
        finally:sys.path.pop(0)
        self.assertEqual(result['overall']['matched_mask_assessment']['unsure'],1)
        self.assertEqual(result['overlap_group_summary']['groups_with_unsure_matched_masks'],1)
        self.assertFalse(result['overall']['species']['mask_assessment_complete'])
        self.assertIsNone(result['overall']['species']['correct_with_acceptable_mask_fraction'])

    def test_merged_mask_is_reported_without_assuming_acceptability(self):
        self.reference['fields'][0]['matches'][0]['mask_assessment']='merged'
        self.reference['fields'][0]['matches'][0]['merged_reference_ids']=['r2']
        run,output=self.assemble();self.assertEqual(run.returncode,0,run.stderr)
        sys.path.insert(0,str(ROOT/'diatom_pilot'))
        try:
            from evaluate_instances import evaluate
            result=evaluate(json.loads(output.read_text()))
        finally:sys.path.pop(0)
        self.assertEqual(result['overall']['matched_mask_assessment']['merged'],1)
        self.assertEqual(result['overlap_group_summary']['groups_with_merged_matched_masks'],1)
        self.assertEqual(result['overlap_group_summary']['groups_with_identified_merged_neighbors'],1)
        self.assertEqual(result['fields'][0]['unmatched_references_in_merged_masks'],1)
        self.assertEqual(result['overall']['species']['missed'],1)
        self.assertIsNone(result['overall']['species']['correct_with_acceptable_mask_fraction'])

    def test_cross_plane_match_is_visible_without_being_marked_wrong(self):
        predictions=json.loads(self.predictions.read_text());predictions['predictions'][0]['plane_z']=1;self.predictions.write_text(json.dumps(predictions))
        self.reference['fields'][0]['predictions_sha256']=sha(self.predictions);self.reference['fields'][0]['references'][0]['z']=0
        run,output=self.assemble();self.assertEqual(run.returncode,0,run.stderr)
        sys.path.insert(0,str(ROOT/'diatom_pilot'))
        try:
            from evaluate_instances import evaluate
            result=evaluate(json.loads(output.read_text()))
        finally:sys.path.pop(0)
        self.assertEqual(result['overall']['matched_plane_relation']['different'],1)
        self.assertEqual(result['overlap_group_summary']['groups_with_cross_plane_matches'],1)
        self.assertEqual(result['overall']['species']['correct'],1)

    def test_merged_neighbors_must_be_distinct_known_references(self):
        item=self.reference['fields'][0]['matches'][0];item['mask_assessment']='merged'
        for bad in (['r1'],['unknown'],['r2','r2']):
            item['merged_reference_ids']=bad;run,_=self.assemble();self.assertNotEqual(run.returncode,0)
            self.assertIn('Invalid additional references',run.stderr)

    def test_taxon_breakdown_and_named_unmatched_predictions(self):
        sys.path.insert(0,str(ROOT/'diatom_pilot'))
        try:
            from evaluate_instances import evaluate
            source=json.loads((ROOT/'diatom_pilot/examples/synthetic-evaluation.json').read_text())
            source['fields'][0]['predictions'][2]['genus']='Invented'
            result=evaluate(source)
        finally:sys.path.pop(0)
        self.assertEqual(result['per_taxon']['species']['GenusA species2']['detected_abstentions'],1)
        self.assertEqual(result['per_taxon']['genus']['GenusB']['missed'],1)
        self.assertEqual(result['unmatched_name_summary']['duplicate']['genus']['named'],1)
        self.assertEqual(result['unmatched_name_summary']['duplicate']['species']['unnamed'],1)
        self.assertIsNone(result['unmatched_name_summary']['other']['genus']['named_fraction'])

    def test_field_overlap_declaration_requires_handling_rule(self):
        sys.path.insert(0,str(ROOT/'diatom_pilot'))
        try:
            from evaluate_instances import evaluate
            source=json.loads((ROOT/'diatom_pilot/examples/synthetic-evaluation.json').read_text())
            source['fields'].append({'field_id':'second','sample_id':'synthetic-test','exhaustive':True,'references':[],'predictions':[]})
            source['overlapping_field_pairs']=[['synthetic-field','second']]
            with self.assertRaisesRegex(ValueError,'handling rule'):evaluate(source)
            source['field_overlap_handling_id']='synthetic-ownership';result=evaluate(source)
            self.assertEqual(result['overlapping_field_pairs'],[['synthetic-field','second']])
        finally:sys.path.pop(0)


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