#!/usr/bin/env python3
import hashlib
import subprocess
import sys
import time
from pathlib import Path

PROJECT = Path(__file__).resolve().parents[1]
PLAN = __import__("json").loads((PROJECT / "script/production-plan.json").read_text())
CHAPTERS = [PROJECT / "story/chapters" / f"chapter-{index:02d}.txt" for index in range(1, int(PLAN["expected_chapters"]) + 1)]
REQUIRED = CHAPTERS + [
    PROJECT / "story/spoken-narration.txt",
    PROJECT / "story/story-canon.txt",
    PROJECT / "story/draft-report.json",
]


def snapshot():
    rows = []
    for path in REQUIRED:
        if not path.exists() or path.stat().st_size == 0:
            return None
        rows.append((str(path), path.stat().st_size, hashlib.sha256(path.read_bytes()).hexdigest()))
    return tuple(rows)


def main():
    prior = None
    stable = 0
    deadline = time.time() + 3 * 60 * 60
    while time.time() < deadline:
        current = snapshot()
        if current is not None and current == prior:
            stable += 1
        else:
            stable = 0
        prior = current
        if stable >= 2:
            result = subprocess.run([sys.executable, "-B", "script/promote-story.py"], cwd=PROJECT)
            return result.returncode
        time.sleep(20)
    print("Story watcher timed out before stable complete draft", file=sys.stderr)
    return 2


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