import importlib.util
import json
import os
from pathlib import Path
import shutil
import subprocess
import urllib.request

os.umask(0o077)
R = Path(__file__).parent
HEAD = 'bc70f1d407cdecb442c35891a9a0c612b2521e80'
s = importlib.util.spec_from_file_location('gate', '/tmp/codex/ltb1021/2026-09-11_service-stop_r01/gate.py')
g = importlib.util.module_from_spec(s)
s.loader.exec_module(g)


def main():
    assert not (R/'plan.json').exists()
    assert g.sh(['git', '-C', str(g.REPO), 'rev-parse', 'HEAD']).strip() == HEAD
    c = g.inspect()
    assert c['State']['Health']['Status'] == 'healthy'
    assert c['Image'] == 'sha256:46f5c223b6e2de940dc275cdfcf4bcfe247abdbae55f91d024bcb301bb9dd08d'
    env = g.load_env_file(str(g.ENV))
    overlay = Path(env['CONTEXTRA_RUNTIME_STATE_ROOT'])/'streams_runtime.yaml'
    specs = g.yaml.safe_load(overlay.read_text())['added']
    assert len(specs) == 1 and specs[0]['scenarios'] == 'off'
    assert all(specs[0][k] is False for k in ('store', 'active_learning', 'autostart'))
    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
    with opener.open('http://127.0.0.1:'+env['FASTAPI_HOST_PORT']+'/api/v1/streams', timeout=3) as f:
        states = json.load(f)['streams']
    assert len(states) == 1 and states[0]['state'] == 'stopped'
    assert g.sha(g.CFG) == '5e5a4d22786f8b5218ac821379fbec091d9e3006f62c880ee3e3da5ced2f0e0b'
    assert g.sha(g.CFG.parent/'2/model.plan') == '5fdf1e9c55ab947a3b7d5f7f6bdceaf1e36a9e52efdf86f5a15d3b99b8631d1e'
    active = g.ENV.parent/'metadata-active/compose.yaml'
    cfg = g.yaml.safe_load(active.read_text())
    actual = dict(x.split('=', 1) for x in c['Config']['Env'])
    for k in ('REDIS_URL', 'CONTEXTRA_METADATA_REDIS_URL', 'CONTEXTRA_METADATA_ENABLED'):
        assert actual[k] == cfg['services']['analytics']['environment'][k]
    for name, path in [('env.before', g.ENV), ('overlay.before', overlay), ('active-compose.before', active)]:
        (R/name).write_bytes(path.read_bytes())
    for name in ('visual', 'diagnostics', 'samples'):
        (R/name).mkdir(mode=0o700)
    root = g.sh(['docker', 'info', '--format', '{{.DockerRootDir}}']).strip()
    plan = dict(analytics=c, env_hash=g.sha(g.ENV), overlay_hash=g.sha(overlay), active_hash=g.sha(active),
                config_hash=g.sha(g.CFG), plan_hash=g.sha(g.CFG.parent/'2/model.plan'),
                other_containers=g.others(), gpu_mib=g.gpu(), disk_free=shutil.disk_usage(root).free,
                overlay=str(overlay), controls=str(active.parent), started='2026-09-13T14:45:18+09:00')
    assert plan['disk_free'] >= 15*1024**3
    (R/'plan.json').write_text(json.dumps(plan, indent=2))
    print(json.dumps(dict(healthy=True, stopped=True, disk_gib=round(plan['disk_free']/1024**3, 2), gpu_mib=plan['gpu_mib'])))
    find_input(4)


def find_input(depth, large=False):
    # Recover only a byte-identical first recorded Frame of the already approved clip.
    recorded = Path('/tmp/codex/ltb1021/2026-09-09_contextra-medium-video_r01/frames.rgb')
    with recorded.open('rb') as f:
        expected = g.hashlib.sha256(f.read(1280*720*3)).hexdigest()
    command = ['find', '/data', '-maxdepth', str(depth), '-type', 'f',
        '(', '-iname', '*.mp4', '-o', '-iname', '*.avi', '-o', '-iname', '*.mkv', ')']
    if large:
        command += ['-size', '+10M', '-size', '-500M']
    files = subprocess.check_output(command, text=True, timeout=10).splitlines()
    assert len(files) <= 100, 'INPUT_INVENTORY_CAP'
    matches = []
    for path in files:
        p = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries',
            'stream=width,height:format=duration', '-of', 'json', path], capture_output=True, timeout=5)
        if p.returncode:
            continue
        data = json.loads(p.stdout)
        if not data.get('streams') or data['streams'][0] != {'width':1280,'height':720}:
            continue
        if abs(float(data.get('format', {}).get('duration', 0))-121.8) > .3:
            continue
        p = subprocess.run(['ffmpeg', '-v', 'error', '-ss', '20', '-i', path, '-frames:v', '1',
            '-f', 'rawvideo', '-pix_fmt', 'rgb24', 'pipe:1'], capture_output=True, timeout=15)
        if p.returncode == 0 and g.hashlib.sha256(p.stdout).hexdigest() == expected:
            matches.append(path)
    (R/'input.json').write_text(json.dumps(dict(matches=matches, recorded_frame_hash=expected), indent=2))
    print(json.dumps(dict(approved_input_matches=len(matches), inventory_count=len(files))))


if __name__ == '__main__':
    main()
