"""Reuse the bounded CPU controller, with writes confined to this run."""
import concurrent.futures
import csv
import hashlib
import json
from pathlib import Path
import sys

LOCAL = Path(__file__).resolve().parent.parent
BASE = LOCAL.parent
SOURCE = BASE / '2026-10-30_contextra-fight-integrated-37clips_r01'
SPACE = BASE / '2026-10-30_contextra-fight-space-29clips_r01'
SELF = BASE / '2026-10-29_contextra-self-filming-l01-pose-cache_r01'
sys.path.insert(0, str(BASE / '2026-10-29_contextra-fight-b-refine_r01/helpers'))
import control_refine as c
c.LOCAL = LOCAL
c.REMOTE = c.old.RB + '/' + LOCAL.name
c.PREFIX = 'contextra-robust-1030-r01-'
c.REPORT = LOCAL / 'reports'


def write(name, value):
    (LOCAL / name).write_text(json.dumps(value, ensure_ascii=False, indent=2))


def sync():
    for p in [LOCAL / 'helpers', *sorted(LOCAL.glob('*.json')), LOCAL / 'checkpoint.ko.md']:
        c.old.scp(str(p), 'si@58.233.207.31:' + c.REMOTE + '/')


def setup():
    c.REPORT.mkdir(exist_ok=True)
    c.checked_resources()
    assert c.old.checked(['docker','image','inspect',c.old.IMAGE,'--format','{{.Id}}']).decode().strip() == c.old.IMAGE
    c.old.checked(['test','!','-e',c.REMOTE])
    all_specs = c.read(SOURCE / 'specs.json')
    excluded = [n for n in all_specs if n[:3] in ('05_','10_','11_','12_','13_','15_')]
    specs = {k:v for k,v in all_specs.items() if k not in excluded}
    maps = {k:v for k,v in c.read(SOURCE / 'self_maps.json').items() if k in specs}
    old_space = c.read(SPACE / 'specs.json')
    specs['SELF_L02'] = old_space['SELF_L01_P02']
    maps['SELF_L02'] = c.read(SPACE / 'self_maps.json')['SELF_L01_P02']
    assert len(specs) == 32 and len(excluded) == 6
    assert len(specs['SELF_L02']['selected_samples']) == 7261
    plan = {}
    for name in specs:
        l02 = name == 'SELF_L02'
        run = SPACE if l02 else SOURCE
        key = 'SELF_L01_P02' if l02 else name
        diagnostic = ('download/SELF_L01/data/SELF_L01_P02' if l02 else 'download/'+name+'/data')
        local_diag = (SPACE/'Contextra_Fight_Space_Review_20261030/SELF_L01/data/SELF_L01_P02' if l02
                      else SOURCE/'Contextra_Fight_Integrated_Review_20261030'/name/'data')
        s = c.read(local_diag/'summary.json')
        assert c.digest(local_diag/'B_Integrated_diagnostics.jsonl') == s['sha256']
        plan[name] = dict(source_run=run.name, source_key=key, feature='work/'+key+'/enriched.jsonl',
            diagnostic=diagnostic+'/B_Integrated_diagnostics.jsonl', baseline_sha256=s['sha256'],
            feature_sha256=s['feature_sha256'], displayed=len(specs[name]['selected_samples']),
            l02_frame_offset=2542 if l02 else 0, l02_pts_offset=105.352669 if l02 else 0)
    overlays=[]
    feedback=[('C11',558,641,'hair_adjustment'),('C15',251,298,'high_five'),
              ('C16',55,281,'walking_hand_in_hand'),('C17',543,685,'natural_group_walk'),
              ('C19',169,250,'passing_each_other')]
    for cid,lo,hi,description in feedback:
        m=maps['SELF_'+cid][0]
        offset=int(m['review_frame_1based'])-int(m['clip_frame_1based'])
        overlays.append(dict(id=cid+'_'+description,review_bounds=[lo+offset,hi+offset],
            source_clip=cid,source_bounds=[lo,hi],precision='approximate user range'))
    for lo,hi,desc in [(8100,8193,'shoulder_embrace'),(8263,8300,'release_embrace'),
                       (8393,8500,'two_hand_high_five'),(18451,18451,'daily_document_hair_anchor')]:
        overlays.append(dict(id='L01_'+desc,review_bounds=[lo+11962,hi+11962],
            source_clip='L01',source_bounds=[lo,hi],precision='single anchor' if lo==hi else 'approximate user range'))
    for name,value in [('specs.json',specs),('self_maps.json',maps),('sources.json',plan),
                       ('feedback.json',dict(negative_overlays=overlays,C22='whole_clip_negative_desired',
                                            excluded=excluded,independent_cases=False)),
                       ('cases.json',c.read(SOURCE/'cases.json'))]:
        write(name,value)
    contract=c.read(SOURCE/'execution_contract.json')
    contract.update(candidate='B_Refined',frozen=False,baseline_read_only=True,baseline_reexecution=False,
        models_reexecuted=False,expected_videos=32,cpus=2,memory_gib=8,max_workers=2,
        L02='reuse P02 with explicit old/new frame and actual PTS mapping',
        interpretation='No exact GT, no model superiority or production FPS claim')
    write('execution_contract.json',contract)
    frozen={str(p.relative_to(BASE)):c.digest(p) for p in
        [SOURCE/'candidates.json',SOURCE/'helpers/integrated.py',SOURCE/'helpers/evaluate_integrated.py',
         BASE/'2026-10-29_contextra-fight-b-refine_r01/helpers/geometry.py',
         BASE/'2026-10-29_contextra-fight-b-refine_r01/helpers/motion.py']}
    write('baseline_fingerprints.json',frozen)
    c.snapshot('before')
    c.old.checked(['mkdir',c.REMOTE],sudo=True)
    c.old.checked(['chown','si:si',c.REMOTE],sudo=True)
    c.old.checked(['chmod','700',c.REMOTE])
    c.old.checked(['mkdir','-p',c.REMOTE+'/work',c.REMOTE+'/download/validation',c.REMOTE+'/reports'])
    sync()
    print('SETUP_PASS 31 clips + L02/7261 observations; baseline reused',flush=True)


def many(stage):
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
        for future in concurrent.futures.as_completed([pool.submit(c.run_job,stage,n) for n in c.read(LOCAL/'specs.json')]):
            future.result()


if __name__ == '__main__':
    action=sys.argv[1]
    if action=='setup':setup()
    elif action=='sync':sync()
    elif action=='one':c.run_job(sys.argv[2],sys.argv[3] if len(sys.argv)>3 else 'all')
    elif action=='many':many(sys.argv[2])
    elif action=='pull-reports':c.old.scp('si@58.233.207.31:'+c.REMOTE+'/reports/.',str(c.REPORT))
    elif action=='pull':c.old.scp('si@58.233.207.31:'+c.REMOTE+'/download/.',str(LOCAL/'Contextra_Fight_Refined_Review_20261030'))
    elif action=='finish':c.finish()
    else:raise ValueError(action)
