"""Reference-first extraction checks with a synthetic sparse scan and stack."""
import hashlib
import json
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from PIL import Image

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


class FakeStack:
    def __init__(self,path):self.path=path
    def __enter__(self):self.width=64;self.height=64;self.depth=2;return self
    def __exit__(self,*args):pass
    def field(self,z,x,y,size):return Image.new('L',(size,size),30+z)


class ReferenceFirstTest(unittest.TestCase):
    def setUp(self):
        self.temp=tempfile.TemporaryDirectory();self.root=Path(self.temp.name);self.scan=self.root/'scan.tif'
        with self.scan.open('wb') as f:f.truncate(1_000_000_000)
        proto={'format':'diatom-frozen-field-protocol-v1','candidate_policy':'synthetic','scoring_environment':{'synthetic':True},
               'fields':[{'id':'field','sample_id':'sample','slide':'scan.tif','slide_size_bytes':1_000_000_000,'origin_xy':[2,3],'z':1,'size':16}]}
        self.protocol=self.root/'protocol.json';self.protocol.write_text(json.dumps(proto));self.output=self.root/'reference'
    def tearDown(self):self.temp.cleanup()
    def generate(self):
        argv=['make_reference_from_scan.py','--protocol',str(self.protocol),'--field-id','field','--slide',str(self.scan),'--output',str(self.output)]
        with patch.object(sys,'argv',argv),patch.object(make_reference_from_scan,'Stack',FakeStack),patch.object(make_reference_from_scan,'snapshot',return_value={'synthetic':True}):make_reference_from_scan.main()
    def test_unscored_reference_contains_only_images_and_context(self):
        self.generate();context=json.loads((self.output/'context.json').read_text());self.assertEqual(context['source_kind'],'unscored_scan')
        self.assertEqual([x['z'] for x in context['planes']],[0,1]);self.assertNotIn('bundle_id',context)
        self.assertEqual(context['field_image_sha256'],hashlib.sha256((self.output/'model-plane.png').read_bytes()).hexdigest())
        self.assertFalse((self.output/'bundle.json').exists());self.assertFalse((self.output/'predictions.json').exists())
    def test_small_scan_rejected_before_open(self):
        with self.scan.open('wb') as f:f.write(b'partial')
        with self.assertRaisesRegex(ValueError,'1 GB'):self.generate()
        self.assertFalse(self.output.exists())
    def development(self, split='practice', sample=''):
        plan={'format':'diatom-development-field-plan-v1','fields':[{'id':'field','sample_id':sample,'split':split,
              'slide':'scan.tif','slide_size_bytes':1_000_000_000,'origin_xy':[2,3],'z':1,'size':16}]}
        self.protocol.write_text(json.dumps(plan))
        argv=['make_reference_from_scan.py','--development-plan',str(self.protocol),'--field-id','field','--slide',str(self.scan),'--output',str(self.output)]
        with patch.object(sys,'argv',argv),patch.object(make_reference_from_scan,'Stack',FakeStack):make_reference_from_scan.main()
    def test_practice_does_not_require_classifier_or_sample(self):
        self.development();context=json.loads((self.output/'context.json').read_text())
        self.assertEqual((context['purpose'],context['split'],context['sample_id']),('development','practice',''))
        self.assertFalse((self.output/'predictions.json').exists())
    def test_development_cannot_designate_test_or_anonymous_training(self):
        with self.assertRaisesRegex(ValueError,'never test'):self.development('test','sample')
        with self.assertRaisesRegex(ValueError,'sample ID'):self.development('train','')


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