"""Reproduce exactly 18 presentation controls from hash-checked public sources.
No credentials, model calls, paid jobs, serving changes or source mutation.
"""
from pathlib import Path, PurePosixPath
import hashlib
import json
import re
import stat
import subprocess
import sys
import tempfile
import urllib.request

ROOT = Path(__file__).resolve().parent
BASE = 'https://huggingface.co/spaces/csoai/meok-oowm-hybrid-lab/resolve/cded7cd8eee2505d6a4a046ae83353432cd4c208/integration-specialist-review/'
MANIFEST_SHA = '46099b7bedeb5f2f6a53af1d1c588b6cd8097276e6f646ea2a5ae0c31fd120ae'
LOCAL_PINS = {
    'specialist_presentation.py': '9c3750812999cd1b022469d95ae6f099cc1b4b2cb81e698a4b18832578aeb47a',
    'specialist_review_ui.py': '8d467fc320d78270c0a30ab17f31162f845379cb1b1af7a6baefa2f3358746da',
    'test_specialist_presentation.py': '23bd379ccc6b0f708054cf5f74d5948378ddd21ef8c7be29498a9c8131ac54ab',
}
MAX_BYTES = 300000
EXPECTED_TESTS = 18


def source_path(name):
    if not isinstance(name, str) or not name or '\\' in name:
        raise ValueError('SOURCE_PATH_REFUSED')
    path = PurePosixPath(name)
    if path.is_absolute() or any(x in ('', '.', '..') for x in name.split('/')):
        raise ValueError('SOURCE_PATH_REFUSED')
    return path


def checked(raw, expected, name):
    if not isinstance(raw, bytes) or len(raw) > MAX_BYTES:
        raise ValueError('SOURCE_SIZE_BOUND: ' + name)
    if not isinstance(expected, str) or not re.fullmatch('[0-9a-f]{64}', expected):
        raise ValueError('SOURCE_PIN_INVALID: ' + name)
    if hashlib.sha256(raw).hexdigest() != expected:
        raise ValueError('SOURCE_DIGEST_MISMATCH: ' + name)
    return raw


def read_local(root):
    """Verify and capture all local code before network access or execution."""
    captured = {}
    for name, expected in LOCAL_PINS.items():
        p = Path(root) / source_path(name)
        if not stat.S_ISREG(p.lstat().st_mode):
            raise ValueError('REGULAR_SOURCE_REQUIRED: ' + name)
        with p.open('rb') as handle:
            raw = handle.read(MAX_BYTES + 1)
        captured[name] = checked(raw, expected, name)
    return captured


def fetch(name):
    source_path(name)
    request = urllib.request.Request(BASE + name, headers={'User-Agent': 'MEOK-public-reproduction/2'})
    with urllib.request.urlopen(request, timeout=30) as response:
        raw = response.read(MAX_BYTES + 1)
    if len(raw) > MAX_BYTES:
        raise ValueError('SOURCE_SIZE_BOUND: ' + name)
    return raw


def parse_manifest(raw):
    checked(raw, MANIFEST_SHA, 'SOURCE_FILES.json')
    def pairs(items):
        out = {}
        for key, value in items:
            if key in out:
                raise ValueError('DUPLICATE_MANIFEST_KEY')
            out[key] = value
        return out
    doc = json.loads(raw.decode('utf-8'), object_pairs_hook=pairs)
    table = doc.get('files_sha256') if isinstance(doc, dict) else None
    if not isinstance(table, dict) or not 1 <= len(table) <= 64:
        raise ValueError('MANIFEST_SHAPE')
    selected = {}
    for name, expected in table.items():
        source_path(name)
        if not isinstance(expected, str) or not re.fullmatch('[0-9a-f]{64}', expected):
            raise ValueError('SOURCE_PIN_INVALID: ' + name)
        if name == 'specialist_review.py' or name.startswith('join_assets/'):
            selected[name] = expected
    if 'specialist_review.py' not in selected:
        raise ValueError('MISSING_ADAPTER_SOURCE')
    return selected


def require_test_result(returncode, output):
    counts = re.findall(r'^Ran (\d+) tests? in ', output, flags=re.MULTILINE)
    if returncode != 0 or counts != [str(EXPECTED_TESTS)]:
        raise ValueError('TEST_RUN_NOT_QUALIFIED')
    if not re.search(r'^OK\s*$', output, flags=re.MULTILINE):
        raise ValueError('TEST_RUN_NOT_QUALIFIED')
    if re.search(r'\b(skipped|expected failures|unexpected successes)\b', output, flags=re.IGNORECASE):
        raise ValueError('TEST_RUN_NOT_QUALIFIED')


def reproduce(root=ROOT):
    captured = read_local(root)
    selected = parse_manifest(fetch('SOURCE_FILES.json'))
    for name, expected in selected.items():
        captured[name] = checked(fetch(name), expected, name)
    # Never re-read mutable local paths after their captured bytes were checked.
    with tempfile.TemporaryDirectory(prefix='receiver-repro-') as temp:
        out = Path(temp)
        for name, raw in captured.items():
            p = out / source_path(name)
            p.parent.mkdir(parents=True, exist_ok=True)
            p.write_bytes(raw)
        run = subprocess.run(
            [sys.executable, '-B', '-m', 'unittest', 'test_specialist_presentation'],
            cwd=out, capture_output=True, text=True, timeout=30,
        )
        output = run.stdout + run.stderr
        print(output)
        require_test_result(run.returncode, output)
    receipt = {
        'status': 'PASSED_PINNED_REPRODUCTION', 'tests': EXPECTED_TESTS,
        'local_sources_verified': len(LOCAL_PINS), 'downloaded_sources_verified': len(selected),
        'source_manifest_sha256': MANIFEST_SHA,
        'executed_source_sha256': {name: hashlib.sha256(raw).hexdigest() for name, raw in sorted(captured.items())},
        'model_calls': 0, 'credentials_used': False, 'source_files_modified': False,
        'limits': 'Hash checks bind selected bytes, not source truth, code safety or independent acceptance.',
    }
    print('REPRODUCTION_RECEIPT ' + json.dumps(receipt, sort_keys=True))
    return receipt


if __name__ == '__main__':
    reproduce()
