from preflight import R, g, api, Manager
import csv
import json
import re
import subprocess
from pathlib import Path

p = json.loads((R / 'plan.json').read_text())
reflection = json.loads((R / 'reflection.json').read_text())
build = json.loads((R / 'build.json').read_text())
once = json.loads((R / 'once-trial.json').read_text())
test = json.loads((R / 'image-verify.json').read_text())
sample = json.loads((R / 'sample01.json').read_text())
c = g.inspect()
assert c['Image'] == build['image_id'] and c['State']['Health']['Status'] == 'healthy'
streams = api('/api/v1/streams')['streams']
assert len(streams) == len(p['streams']) and all(s['state'] == 'stopped' for s in streams)
assert g.sha(Path(p['overlay'])) == p['overlay_hash']
assert all(g.sha(Path(f)) == h for f, h in p['model_hashes'].items())
assert g.sha(g.ENV) == reflection['env_after'] and g.sha(Path(p['active'])) == reflection['active_after']
rows = Manager().status()
row = next(r for r in rows if r['name'] == 'sample01')
assert row['state'] == 'STREAMING' and row['anchor'] and row['executionId'] == sample['current']['executionId']
others = g.others()
assert all(others.get(k) == v for k, v in p['other_containers'].items())
assert set(others) - set(p['other_containers']) == {sample['started']['container']}
assert not Manager(R / 'trial-registry').containers()
paths = ['docs/profiles/ltb1021/topics/runtime-lifecycle/README.ko.md',
    'docs/profiles/ltb1021/topics/runtime-lifecycle/runs/20260914T174625+0900-run-rtsp-swagger-ready.md',
    'tools/RTSP_TEST_GUIDE.ko.md', 'tools/RTSP_SWAGGER_GUIDE.ko.md']
links = 0
for name in paths:
    path = g.REPO / name
    content = path.read_text()
    if name.endswith('README.ko.md'):
        content = content.split('## 실제 공유 송출')[0]
    for target in re.findall(r'\]\(([^)]+)\)', content):
        if target.startswith(('http:', 'https:', '#')):
            continue
        assert (path.parent / target.split('#', 1)[0]).resolve().exists(), (name, target)
        links += 1
subprocess.run(['git', 'diff', '--check'], cwd=g.REPO, check=True)
summary = dict(ready_for_user_swagger=True, ai_start_count=0, test_registration_count=0,
    once=dict(status=once['stage'], terminal=once['terminal']['state'], inactive_anchor_null=once['terminal']['anchor'] is None, remaining=once['remaining']),
    image=dict(tag=build['tag'], id=build['image_id'], build_seconds=build['elapsed_s'], api_tests=test['tests'], api_errors=test['errors'], api_failures=test['failures']),
    analytics=dict(health='healthy', stream_count=len(streams), all_stopped=True, model_versions=reflection['model_versions'], config_preserved=True),
    sender=dict(name='sample01', state=row['state'], mode=row['mode'], anchor_available=True, retained=True,
                receiver=sample['receiver'], access='container verified; Windows/Web not verified', address='current DHCP LAN address; not guaranteed permanent'),
    cleanup=dict(task_senders=0, task_receivers=0, non_target_services_preserved=True),
    capacity_failures=0, documentation=dict(files=4, local_links=links, diff_check='PASS'),
    not_tested=['AI inference and Redis publication', 'Web reception and video synchronization', 'multi-channel throughput'])
(R / 'summary.json').write_text(json.dumps(summary, indent=2))
with (R / 'summary.csv').open('w') as out:
    w = csv.writer(out)
    w.writerow(['boundary', 'result', 'scope'])
    w.writerows([['once', 'PASS', 'natural EOF; inactive anchor null; repeated Stop'],
                 ['image API', 'PASS', '2 tests; image-owned cwd/import/hash'],
                 ['Analytics', 'PASS', 'healthy; existing stream stopped; 3 models version2'],
                 ['sample01', 'PASS_RETAINED', 'SDP and 1330 packets; continuous sender retained'],
                 ['cleanup', 'PASS', 'temporary helpers removed; non-target services preserved'],
                 ['AI/Web', 'NOT_RUN', 'user Start and Web tests pending']])
ledger = json.loads((R / 'ledger.json').read_text())
ledger.update(result='READY_FOR_USER_SWAGGER', task_cleanup='PASS', user_sender='RETAINED',
              original_report_inbox='written; wrapper dedupe check applied')
(R / 'ledger.json').write_text(json.dumps(ledger, indent=2))
for path in R.iterdir():
    if path.is_file():
        path.chmod(0o600)
print(json.dumps(summary))
