"""Checks for average_conductances.py. Run from this directory with the sibling packages
run-011, benchmark-004 and protocol-007 next to it:  python3 -m unittest -v test_average_conductances
"""
import json, shutil, subprocess, sys, tempfile, unittest
from pathlib import Path

HERE = Path(__file__).resolve().parent
RESEARCH = HERE.parent
INPUTS = ['run-011/analysis/analysis-parity.json', 'benchmark-004/reference-means.csv', 'protocol-007/model/visualization_functions.py']


def run(research, output):
    return subprocess.run([sys.executable, str(HERE / 'average_conductances.py'), '--research', str(research), '--output', str(output)],
                          capture_output=True, text=True, cwd=str(research))


class AverageConductances(unittest.TestCase):
    def test_rerun_reproduces_packaged_output(self):
        with tempfile.TemporaryDirectory() as tmp:
            r = run(RESEARCH, tmp)
            self.assertEqual(r.returncode, 0, r.stderr)
            self.assertEqual((Path(tmp) / 'conductance-averages.json').read_bytes(), (HERE / 'conductance-averages.json').read_bytes())

    def test_result(self):
        out = json.loads((HERE / 'conductance-averages.json').read_text())
        self.assertEqual(out['matches_both_text_values'], ['recorded_pooled', 'unweighted'])
        size = next(r for r in out['rules'] if r['rule'] == 'size_weighted')
        self.assertFalse(size['exc']['run_011_rounds_to_text_value'] or size['inh']['run_011_rounds_to_text_value'])

    def test_modified_input_is_rejected(self):
        with tempfile.TemporaryDirectory() as tmp:
            for rel in INPUTS:
                (Path(tmp) / rel).parent.mkdir(parents=True, exist_ok=True)
                shutil.copyfile(RESEARCH / rel, Path(tmp) / rel)
            parity = Path(tmp) / INPUTS[0]
            parity.write_text(parity.read_text().replace('"independent": 3.05', '"independent": 3.15', 1))
            r = run(tmp, Path(tmp) / 'out')
            self.assertNotEqual(r.returncode, 0)
            self.assertIn('SHA-256 mismatch for', r.stderr + r.stdout)
            self.assertFalse((Path(tmp) / 'out').exists())


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