import hashlib
import json
import sys
import tempfile
import unittest
from pathlib import Path

sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from import_development_points import convert


class ImportTest(unittest.TestCase):
    def setUp(self):
        self.tmp=tempfile.TemporaryDirectory();self.root=Path(self.tmp.name)
        (self.root/'field.png').write_bytes(b'field');(self.root/'plane.png').write_bytes(b'plane')
        def sha(name):return hashlib.sha256((self.root/name).read_bytes()).hexdigest()
        bundle={'slide':'s.tif','slide_size_bytes':1_000_000_000,'origin_xy':[0,0],'size':10,'z':0,'field_image':'field.png','candidates':[]}
        bundle['bundle_id']=hashlib.sha256(json.dumps(bundle,sort_keys=True).encode()).hexdigest()
        (self.root/'bundle.json').write_text(json.dumps(bundle))
        (self.root/'focus-planes.json').write_text(json.dumps({'format':'diatom-focus-planes-v1','bundle_id':bundle['bundle_id'],'planes':[{'z':0,'image':'plane.png','sha256':sha('plane.png')}]}))
        self.source={'format':'diatom-provisional-development-annotations-v1','annotation_status':'provisional','context':{'purpose':'development','source_kind':'unscored_scan','split':'practice','sample_id':'','slide':'s.tif','slide_size_bytes':1_000_000_000,'origin_xy':[0,0],'size':10,'model_z':0,'field_image_sha256':sha('field.png'),'planes':[{'z':0,'sha256':sha('plane.png')}]},'state':{'reviewer_id':'learner','reviewer_role':'nonexpert','references':[{'id':'r-1','field_xy':[2,3],'z':0,'partial':'yes','overlap_group':'g','genus':'Navicula','species':''}]}}
        self.path=self.root/'source.json'
    def tearDown(self):self.tmp.cleanup()
    def run_convert(self):
        self.path.write_text(json.dumps(self.source));return convert(self.path,self.root)
    def test_preserves_provisional_point(self):
        result=self.run_convert();point=result['review']['manual'][0]
        self.assertEqual((point['x'],point['partial'],point['overlap'],point['decision']),(2,'yes','yes','possible'))
        self.assertEqual(result['review']['context']['development_split'],'practice')
    def test_changed_plane_is_rejected(self):
        (self.root/'plane.png').write_bytes(b'changed')
        with self.assertRaisesRegex(ValueError,'Focal plane'):self.run_convert()
    def test_test_split_is_rejected(self):
        self.source['context']['split']='test'
        with self.assertRaisesRegex(ValueError,'provisional development'):self.run_convert()

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