"""Exercise the actual preservation comparator with real public bytes and tampered responses."""
import ast, datetime, hashlib, json, re, types
from pathlib import Path
import requests

root = Path(__file__).resolve().parents[1]
tree = ast.parse((root / 'tools/publish_review.py').read_text())
outer = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == 'fresh_live_preservation')
fn = next(n for n in outer.body if isinstance(n, ast.FunctionDef) and n.name == 'compare')
module = ast.fix_missing_locations(ast.Module(body=[fn], type_ignores=[]))
code = compile(module, 'actual-production-preservation-comparator', 'exec')
slug = 'komplex-rita-funnel-2026-09-26-v1'
path = slug + '/index.html'
mirror = root / 'private/mirror-recovery/verified-host-snapshot'
source = (mirror / path).read_bytes()
prior = json.loads(sorted((root / 'evidence').glob('publication-20*.json'))[-1].read_text())
live = requests.get('https://review.clientsflow.hu/' + path, timeout=35)
live.raise_for_status()
pinned = requests.get(prior['deployment'].rstrip('/') + '/' + path, timeout=35)
pinned.raise_for_status()

class Response:
    def __init__(self, data): self.content = data
    def raise_for_status(self): pass

class Transport:
    def __init__(self, stable, pin): self.stable, self.pin = stable, pin
    def get(self, url, **kwargs):
        return Response(self.pin if '.pages.dev/' in url else self.stable)

def run(stable, pin):
    env = dict(root=root, host=types.SimpleNamespace(SITE_ROOT=mirror),
               requests=Transport(stable, pin), hashlib=hashlib, json=json, re=re, headers={})
    exec(code, env)
    return env['compare'](slug)

actual = run(live.content, pinned.content)
changed = run(live.content.replace(b'Komplex', b'Konplex', 1), pinned.content)
changed_pin = run(live.content, pinned.content + b' ')
raw = run(source, source)
receipt = dict(at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
    tested_actual_production_compare_function=True, actual_live_transform=actual,
    source_change_rejected=not changed['same'], pinned_source_change_rejected=not changed_pin['same'],
    exact_raw_source_passes=raw['same'] and raw['raw_byte_identical'], request_methods=['GET'],
    canonical_skill_changed=False, prior_failed_publication_staged=False)
(root / 'evidence/owned-email-transform-preflight-tests.json').write_text(json.dumps(receipt, indent=2) + '\n')
print(json.dumps(receipt, indent=2))
assert actual['same'] and not actual['raw_byte_identical']
assert not changed['same'] and not changed_pin['same'] and raw['same']
