"""Mechanical, exact backport to exported AI2 source, without latest app replacement."""
import ast
import hashlib
import json
from pathlib import Path
import shutil
import subprocess

ROOT = Path(__file__).resolve().parent
REPO = Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
FILES = ['app/contracts/frames.py', 'app/frame_time.py', 'app/event_capture.py',
         'app/event_artifact_contract.py', 'app/event_time_fallback.py']
TESTS = ['test_event_time_fallback', 'test_frame_time', 'test_event_artifact',
         'test_result_queue_b', 'test_capture_trial', 'test_event_cooldown',
         'test_crowd_events', 'test_provider_process_group']
BASE = 'sha256:4648079cdd0330f1da5e492b172718e29ad722fb403444bb7ac0241d330fbd9a'
TAG = 'contextra-analytics:ai2-event-time-4894214-20261013-r01'

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

if __name__ == '__main__':
    candidate = ROOT/'candidate'
    diff = subprocess.check_output(['git','diff','--unified=1','--',*FILES[:-1]], cwd=REPO)
    if not candidate.exists():
        shutil.copytree(ROOT/'baseline', candidate)
        (ROOT/'hotfix.patch').write_bytes(diff)
        result = subprocess.run(['patch','--batch','--fuzz=0','-p1'], cwd=candidate,
                                input=diff, capture_output=True, check=True)
        (ROOT/'patch-result.txt').write_bytes(result.stdout)
    else:
        assert (ROOT/'hotfix.patch').read_bytes() == diff
    shutil.copy2(REPO/FILES[-1], candidate/FILES[-1])
    changed = [str(p.relative_to(candidate)) for p in candidate.rglob('*.py')
               if not (ROOT/'baseline'/p.relative_to(candidate)).exists()
               or sha(p) != sha(ROOT/'baseline'/p.relative_to(candidate))]
    assert sorted(changed) == sorted(FILES), changed
    context = ROOT/'build-context'; context.mkdir(mode=0o700,exist_ok=True)
    for name in FILES:
        dest=context/'hotfix'/name;dest.parent.mkdir(parents=True,exist_ok=True)
        shutil.copy2(candidate/name,dest)
    testdir=context/'tests';testdir.mkdir(exist_ok=True)
    needed=set(TESTS); done=set()
    while needed-done:
        name=sorted(needed-done)[0]; path=REPO/'tests'/(name+'.py')
        body=path.read_text();shutil.copy2(path,testdir/path.name);done.add(name)
        for n in ast.walk(ast.parse(body)):
            if isinstance(n,ast.ImportFrom) and n.module:
                if n.module.startswith('tests.'):
                    needed.add(n.module.split('.')[1])
                elif n.module=='tests':needed.update(x.name for x in n.names)
                elif (REPO/'tests'/(n.module+'.py')).is_file():needed.add(n.module)
    args=' '.join('tests/'+x+'.py' for x in TESTS)
    lines=[f'FROM {BASE} AS verify','WORKDIR /opt/contextra',
           'COPY hotfix/app/ /opt/contextra/app/', 'COPY tests/ /opt/contextra/tests/',
           'RUN PYTHONDONTWRITEBYTECODE=1 OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 '+
           'timeout 120 python3 -m pytest -q -p no:cacheprovider '+args+
           ' -k "not test_roi_event_wire_paths_and_sidecar and not test_real_start_projection_skip_recovery_and_no_crowd_process"',
           f'FROM {BASE}']
    for name in FILES:lines.append(f'COPY --from=verify /opt/contextra/{name} /opt/contextra/{name}')
    (context/'Dockerfile').write_text('\n'.join(lines)+'\n')
    manifest={'base_image':BASE,'tag':TAG,'development_head':subprocess.check_output(
        ['git','rev-parse','HEAD'],cwd=REPO,text=True).strip(),'files':{name:{
        'baseline_sha256':sha(ROOT/'baseline'/name) if (ROOT/'baseline'/name).exists() else None,
        'development_sha256':sha(REPO/name),'candidate_sha256':sha(candidate/name)} for name in FILES},
        'tests':sorted(done),'patch_sha256':sha(ROOT/'hotfix.patch')}
    (ROOT/'candidate-manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
    print(json.dumps({'files':changed,'test_files':len(done),'tag':TAG}))
