"""Exercise the compiled production companion's patch preparation boundary.

Requires locally generated original-world fixtures; mutations are rejection-only
copies. This proves no native gameplay or server delivery.
"""
from __future__ import annotations
import argparse
import copy
import hashlib
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
import zipfile

ROOT = Path(__file__).resolve().parents[1]
CLIENT = None
PATCH = None

class ProductionAdapterTests(unittest.TestCase):
    def setUp(self):
        self.temporary = tempfile.TemporaryDirectory(prefix='P2 adapter with spaces ')
        self.addCleanup(self.temporary.cleanup)
        self.root = Path(self.temporary.name)
        self.run = self.root / 'selected run'
        with zipfile.ZipFile(PATCH) as archive:
            self.original = {n: archive.read(n) for n in archive.namelist()}
        self.patch = json.loads(self.original['patch.appik2'])

    def prepare(self, patch=None, save='selected-player-save', endpoint='ws://127.0.0.1:38291', success=True):
        patch = PATCH if patch is None else patch
        result = subprocess.run([str(CLIENT), 'prepare', str(patch), '--endpoint', endpoint,
                                 '--run-dir', str(self.run), '--save', save], capture_output=True, timeout=20)
        if success:
            self.assertEqual(result.returncode, 0, result.stderr.decode(errors='replace'))
        else:
            self.assertNotEqual(result.returncode, 0, result.stdout.decode(errors='replace'))
        return result

    def mutated(self, mutate):
        patch = copy.deepcopy(self.patch)
        mutate(patch)
        path = self.root / 'rejection-only.appik2'
        with zipfile.ZipFile(path, 'w') as archive:
            for name, data in self.original.items():
                archive.writestr(name, json.dumps(patch).encode() if name == 'patch.appik2' else data)
        return path

    def state(self):
        return {str(p.relative_to(self.run)): p.read_bytes() for p in self.run.rglob('*') if p.is_file()}

    def test_original_prepare_and_production_open(self):
        self.prepare()
        config = json.loads((self.run / 'bridge/runtime-config.json').read_text(encoding='utf-8'))
        profile = json.loads((self.run / 'profile.json').read_text(encoding='utf-8'))
        self.assertEqual(config['patch'], self.patch)
        self.assertEqual(config['catalog'], json.loads((ROOT / 'contract.json').read_text(encoding='utf-8')))
        self.assertEqual(profile['locations'], list(range(1, 202)))
        self.assertEqual(len(profile['items']), 238)
        result = subprocess.run([str(CLIENT), str(self.run / 'profile.json'), '--headless', '--ticks', '2'],
                                capture_output=True, timeout=20)
        self.assertEqual(result.returncode, 0, result.stderr.decode(errors='replace'))

    def test_repeat_prepare_preserves_selected_state_and_endpoint_only_update(self):
        self.prepare()
        marker = self.run / 'journal.json'
        marker.write_bytes(b'prepare-preservation-control; not a native save or valid journal')
        before = self.state()
        self.prepare()
        self.assertEqual(self.state(), before)
        self.prepare(endpoint='ws://127.0.0.1:38292')
        after = self.state()
        self.assertEqual({k:v for k,v in after.items() if k != 'profile.json'},
                         {k:v for k,v in before.items() if k != 'profile.json'})
        old, new = json.loads(before['profile.json']), json.loads(after['profile.json'])
        self.assertEqual(new.pop('endpoint'), 'ws://127.0.0.1:38292')
        old.pop('endpoint')
        self.assertEqual(old, new)

    def test_existing_run_rejects_other_selected_save_and_patch_without_mutation(self):
        self.prepare()
        before = self.state()
        self.prepare(save='different-player-save', success=False)
        self.assertEqual(self.state(), before)
        changed = self.mutated(lambda p: p.update(seed='different-original-seed'))
        self.prepare(changed, success=False)
        self.assertEqual(self.state(), before)

    def reject_new(self, mutate):
        result = self.prepare(self.mutated(mutate), success=False)
        self.assertFalse((self.run / 'profile.json').exists())
        self.assertFalse((self.run / 'bridge/runtime-config.json').exists())
        return result.stderr.decode(errors='replace')

    def test_rejects_modified_fixed_titan_pair(self):
        self.reject_new(lambda p: p['items'].update({'DD Shock Therapist': 'Remote'}))

    def test_rejects_duplicate_fixed_titan_weapon(self):
        self.reject_new(lambda p: p['items'].update({'VoR Courage Reactor': 'Shock Therapist'}))

    def test_rejects_starting_inventory(self):
        self.reject_new(lambda p: p.update(starter_items=['Courage Reactor']))

    def test_rejects_shuffled_profile(self):
        self.reject_new(lambda p: p.update(onion_shuffle=1))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--client', type=Path, required=True)
    parser.add_argument('--patch', type=Path, help='external original generated P1 .appik2; private fixtures are not packaged')
    parser.add_argument('--report', type=Path)
    args = parser.parse_args()
    CLIENT = args.client.resolve(strict=True)
    PATCH = args.patch or next((ROOT/'tests/fixtures/pokos280-2026101503/generated').glob('*P1*.appik2'), None)
    if PATCH is None:
        parser.error('supply --patch from an original-world vanilla generated seed')
    PATCH = PATCH.resolve(strict=True)
    report = {'patch_sha256': hashlib.sha256(PATCH.read_bytes()).hexdigest(), 'client': str(CLIENT), 'sha256': hashlib.sha256(CLIENT.read_bytes()).hexdigest(),
              'boundary': 'compiled production patch preparation/open; no native effects asserted'}
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(ProductionAdapterTests)
    report['tests'] = [test.id().split('.')[-1] for test in suite]
    result = unittest.TextTestRunner(verbosity=2).run(suite)
    report.update(tests_run=result.testsRun, passed=result.wasSuccessful(),
                  failures=[str(test) for test, _ in result.failures + result.errors])
    if args.report:
        args.report.parent.mkdir(parents=True, exist_ok=True)
        args.report.write_text(json.dumps(report, indent=2)+'\n', encoding='utf-8')
    print(json.dumps(report, indent=2))
    raise SystemExit(0 if result.wasSuccessful() else 1)
