"""Synthetic checks for the descriptive evaluation report."""
import copy
import json
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path

ROOT=Path(__file__).resolve().parents[2];sys.path.insert(0,str(ROOT/'diatom_pilot'))
from evaluate_instances import evaluate,cluster_bootstrap


class ReportTest(unittest.TestCase):
    def setUp(self):
        self.temp=tempfile.TemporaryDirectory();self.root=Path(self.temp.name)
        source=json.loads((ROOT/'diatom_pilot/examples/synthetic-evaluation.json').read_text());self.data=evaluate(source)
    def tearDown(self):self.temp.cleanup()
    def render(self):
        source=self.root/'data.json';source.write_text(json.dumps(self.data));env=os.environ.copy();env['MPLCONFIGDIR']=str(self.root/'mpl')
        return subprocess.run([sys.executable,str(ROOT/'diatom_pilot/render_instance_report.py'),'--input',str(source),'--output',str(self.root/'report'),'--demonstration'],capture_output=True,text=True,env=env)
    def test_synthetic_warning_and_figure(self):
        result=self.render();self.assertEqual(result.returncode,0,result.stderr)
        page=(self.root/'report/index.html').read_text();svg=(self.root/'report/identification-breakdown.svg').read_text()
        self.assertIn('Invented demonstration',page);self.assertIn('SYNTHETIC EXAMPLE',svg);self.assertIn('2 / 3',page)
    def test_inconsistent_counts_rejected(self):
        self.data['overall']['genus']['correct']=99;result=self.render();self.assertNotEqual(result.returncode,0)
        self.assertIn('Inconsistent genus counts',result.stderr);self.assertFalse((self.root/'report').exists())
    def test_sample_level_results_and_bootstrap_are_visible(self):
        source=json.loads((ROOT/'diatom_pilot/examples/synthetic-evaluation.json').read_text());second=copy.deepcopy(source['fields'][0]);second.update(field_id='field-2',sample_id='sample-2');source['fields'].append(second)
        self.data=evaluate(source);self.data['sample_cluster_bootstrap']=cluster_bootstrap(self.data['per_sample'],replicates=100,seed=3)
        result=self.render();self.assertEqual(result.returncode,0,result.stderr)
        page=(self.root/'report/index.html').read_text();self.assertIn('sample-2',page);self.assertIn('100 resamples',page);self.assertIn('spuriously narrow',page)
    def test_sample_totals_must_match_overall(self):
        self.data['per_sample']['synthetic-test']['genus']['correct']=1
        self.data['per_sample']['synthetic-test']['genus']['end_to_end_fraction']=1/3
        result=self.render();self.assertNotEqual(result.returncode,0);self.assertIn('sample counts do not add up',result.stderr)


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