#!/usr/bin/env python3
"""
Phase 1 cho Cron Job Translator (015-phu_de_video / 002): chọn batch → đọc source + guide + glossary
In ra stdout để LLM đọc trong Phase 2.
"""
import json, os, sqlite3, glob
from datetime import datetime, timezone, timedelta

PROJ = "/home/tuan-nguyen/.openclaw/workspace/015-phu_de_video/output"
GUIDE = "/home/tuan-nguyen/.openclaw/workspace/015-phu_de_video/scripts/GUIDE-TRANSLATION.md"
tz = timezone(timedelta(hours=7))

# ── Đọc Guide ──
with open(GUIDE) as f:
    guide = f.read()

# ── Progress ──
with open(f"{PROJ}/translation_progress.json") as f:
    data = json.load(f)

# Check completed batches
vi_files = set()
for fn in glob.glob(f"{PROJ}/batches/*_vi.txt"):
    vi_files.add(os.path.basename(fn).replace("_vi.txt", ""))

# Recover in_progress → done if output exists
for b in data["batches"]:
    if b["status"] == "in_progress" and b["name"] in vi_files:
        b["status"] = "done"
        b["completed_at"] = datetime.now(tz).isoformat()
        print(f"RECOVER:{b['name']}", flush=True)

# Unstuck: in_progress > 15min → reset
for b in data["batches"]:
    if b["status"] == "in_progress":
        started = datetime.fromisoformat(b.get("started_at", "2000-01-01T00:00:00+07:00"))
        if (datetime.now(tz) - started).total_seconds() > 900:
            b["status"] = "pending"
            print(f"UNSTUCK:{b['name']}", flush=True)

# Find next pending
target = None
for b in data["batches"]:
    if b["status"] == "pending":
        target = b
        break

if target is None:
    done_count = sum(1 for b in data["batches"] if b["status"] == "done")
    print(f"ALL_DONE:{done_count}/{data['total_batches']}", flush=True)
    with open(f"{PROJ}/translation_progress.json", "w") as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
    print("CRON_SHOULD_STOP", flush=True)
    exit(0)

# Mark in_progress
target["status"] = "in_progress"
target["started_at"] = datetime.now(tz).isoformat()
BATCH = target["name"]

with open(f"{PROJ}/translation_progress.json", "w") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

# ── Đọc source ──
source_path = f"{PROJ}/batches/{BATCH}_my.txt"
with open(source_path) as f:
    source = f.read()

# ── Đọc Glossary từ SQLite ──
glossary_lines = []
try:
    conn = sqlite3.connect("/home/tuan-nguyen/.openclaw/workspace/data/myanmar_pali_viet_terms_vec.db")
    cur = conn.cursor()
    cur.execute("SELECT pali, myanmar, vietnamese, desc_vi, category FROM terms ORDER BY category, id")
    for r in cur.fetchall():
        glossary_lines.append(f"  [{r[4]}] {r[0]} | {r[1]} | {r[2]} | {r[3]}")
    conn.close()
except Exception as e:
    glossary_lines.append(f"ERROR loading glossary: {e}")

print(f"BATCH:{BATCH}", flush=True)
print(f"GUIDE:{len(guide)} chars", flush=True)
print(f"SOURCE:{len(source)} chars, {source.count(chr(10))} lines", flush=True)
print(f"GLOSSARY:{len(glossary_lines)} terms", flush=True)
print("---GUIDE_START---", flush=True)
print(guide, flush=True)
print("---GUIDE_END---", flush=True)
print("---SOURCE_START---", flush=True)
print(source, flush=True)
print("---SOURCE_END---", flush=True)
print("---GLOSSARY_START---", flush=True)
for line in glossary_lines:
    print(line, flush=True)
print("---GLOSSARY_END---", flush=True)
