#!/usr/bin/env python3
import json
from pathlib import Path

PROJECT = Path('/data/video-pipeline/Youtube-Video-Maker/Project/01072026-001-Nha-Tay-Son')
check_path = PROJECT / 'checklist_19_steps.json'
md_path = PROJECT / 'checklist_19_steps.md'

def read_status(step):
    p = PROJECT / f'logs/step{step:02d}_character_refs_manifest.json'
    if step == 6:
        p = PROJECT / 'logs/step06_images_manifest.json'
    if not p.exists():
        return 'pending'
    try:
        data = json.loads(p.read_text(encoding='utf-8'))
    except Exception:
        return 'in_progress'
    status = data.get('status')
    if step == 5 and status == 'approved_for_scene_generation':
        return 'completed'
    if step == 6 and status == 'completed':
        return 'completed'
    return 'in_progress'

data = json.loads(check_path.read_text(encoding='utf-8'))
for item in data.get('steps', []):
    if item.get('step') == 5:
        item['status'] = read_status(5)
    if item.get('step') == 6:
        item['status'] = read_status(6)
check_path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding='utf-8')
md = '# Checklist 19 Steps\n\nProject ID: ' + PROJECT.name + '\n\n'
for s in data.get('steps', []):
    md += f"## Step {s['step']:02d} - {s['name']}\nStatus: {s['status']}\n\n"
md_path.write_text(md, encoding='utf-8')
print(json.dumps({s['step']: s['status'] for s in data.get('steps', []) if s.get('step') in (5,6)}, ensure_ascii=False))

if read_status(5) != 'completed' or read_status(6) != 'completed':
    raise SystemExit(1)
