#!/usr/bin/env python3
"""Verify published membership exports with Python 3.9+ (standard library).
CC BY 4.0: credit Deterministic AI and Hallucination-Free; identify changes.
Usage: python3 verify_membership.py SNAPSHOT.json membership.py membership.csv counts.csv REVIEW.json
No network requests. Executes the supplied membership.py; inspect downloaded code before running.
Checks consistency and byte identity, not source truth or production AI behavior.
"""
import csv
import hashlib
import io
import json
import platform
import subprocess
import sys
import tempfile
from collections import Counter
from pathlib import Path


def sha(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def main():
    if len(sys.argv) != 6:
        raise SystemExit(__doc__)
    source, script, published, counts, report_path = map(Path, sys.argv[1:])
    data = json.loads(source.read_bytes())
    members = list(csv.DictReader(io.StringIO(published.read_text())))
    cells = list(csv.DictReader(io.StringIO(counts.read_text())))
    row, column = list(cells[0])[:2]
    records = {r['id']: r for r in data['records']}
    checks = []

    def check(name, passed, detail):
        checks.append(dict(check=name, passed=bool(passed), detail=detail))

    check('membership_identity', len(members) == len(records) == len(data['records'])
          and {r['id'] for r in members} == set(records),
          {'snapshot_records': len(records), 'membership_rows': len(members)})
    check('labels_and_sources', all(m['id'] in records and all(
          m[k] == records[m['id']][k] for k in
          ['title', 'event_date', row, column, 'reviewed_at', 'primary_source_url', 'source_scope'])
          and m['record_url'] == data['url'] + '#' + m['id'].lower()
          and m['snapshot_sha256'] == sha(source) for m in members),
          'Published labels, principal evidence, source limits, anchors and input hashes match the snapshot.')
    actual = Counter((m[row], m[column]) for m in members)
    expected_keys = {(r[row], c[column]) for r in data['records'] for c in data['records']}
    check('all_cells', len(cells) == len(expected_keys)
          and {(c[row], c[column]) for c in cells} == expected_keys
          and all(actual[c[row], c[column]] == int(c['count'])
          and int(c['denominator']) == len(records) for c in cells),
          {'cells_checked_including_zeros': len(cells), 'denominator': len(records)})
    with tempfile.TemporaryDirectory() as folder:
        directory = Path(folder)
        outputs = []
        for n in range(2):
            target = directory / f'fresh-{n}.csv'
            run = subprocess.run([sys.executable, str(script), str(source), str(target)],
                                 capture_output=True, text=True)
            outputs.append(dict(exit_code=run.returncode,
                                sha256=sha(target) if target.exists() else None,
                                stdout=run.stdout.strip(), stderr=run.stderr.strip()))
        check('fresh_exports', all(x['exit_code'] == 0 and x['sha256'] == sha(published)
                                  for x in outputs), outputs)
        altered = directory / 'altered.json'
        altered.write_bytes(source.read_bytes() + b'\n')
        target = directory / 'must-not-exist.csv'
        run = subprocess.run([sys.executable, str(script), str(altered), str(target)],
                             capture_output=True, text=True)
        check('altered_input_rejected', run.returncode != 0 and not target.exists()
              and 'Input hash does not match' in run.stderr,
              {'mutation': 'Appended one newline; parsed JSON values unchanged.',
               'exit_code': run.returncode, 'output_created': target.exists(),
               'stderr': run.stderr.strip()})
    report = dict(scope='Frozen dataset export consistency; no AI system, external action or source-truth test.',
                  dataset=data['title'], version=data['version'],
                  environment=dict(python=platform.python_version(), system=platform.system(),
                                   machine=platform.machine()),
                  inputs={p.name: sha(p) for p in (source, script, published, counts)},
                  verifier_sha256=sha(Path(__file__)), checks=checks,
                  all_checks_passed=all(x['passed'] for x in checks),
                  limits='Same-environment local runs. Matching a hash detects byte changes against a trusted baseline; it does not establish authenticity, factual correctness or protection against an attacker replacing both file and baseline.')
    report_path.write_text(json.dumps(report, indent=2) + '\n')
    print(json.dumps(report, indent=2))
    if not report['all_checks_passed']:
        raise SystemExit(1)


if __name__ == '__main__':
    main()
