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

PROJECT = Path('/data/video-pipeline/Youtube-Video-Maker/Project/01062026-001-Pham-Ngu-Lao')
MANIFEST = PROJECT / 'logs/step_07_tts_v2_manifest.json'
LOG = PROJECT / 'logs/step_07_retry_until_complete.log'
MAX_ROUNDS = 12


def read_state():
    if not MANIFEST.exists():
        return None
    doc = json.loads(MANIFEST.read_text(encoding='utf-8'))
    return {
        'status': doc.get('status'),
        'done': int(doc.get('done') or 0),
        'total': int(doc.get('total_voice_segments') or 0),
        'failed': [f.get('voice_segment_id') for f in doc.get('failed', [])],
    }


def log(msg):
    line = time.strftime('%F %T ') + msg
    print(line, flush=True)
    with LOG.open('a', encoding='utf-8') as f:
        f.write(line + '\n')


def main():
    last_done = -1
    stagnant = 0
    for round_no in range(1, MAX_ROUNDS + 1):
        before = read_state()
        log(f'ROUND {round_no} before={before}')
        proc = subprocess.run(['python3', 'scripts_run_step_07_tts_v2.py'], cwd=PROJECT, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        # Preserve a compact per-round tail to avoid huge logs.
        tail = '\n'.join(proc.stdout.splitlines()[-40:])
        log(f'ROUND {round_no} exit={proc.returncode}\n{tail}')
        after = read_state()
        log(f'ROUND {round_no} after={after}')
        if after and after['status'] == 'completed':
            log('COMPLETED')
            return 0
        done = after['done'] if after else 0
        if done <= last_done:
            stagnant += 1
        else:
            stagnant = 0
        last_done = done
        if stagnant >= 2:
            log('STOP stagnant_no_progress')
            return 1
        time.sleep(2)
    log('STOP max_rounds_reached')
    return 1

if __name__ == '__main__':
    raise SystemExit(main())
