#!/usr/bin/env python3
"""
Watcher: corre diff_align_surya + build_surya_report en cuanto un libro
gana suficientes páginas OCR nuevas.

Uso:
    python3 surya_watcher.py [--interval 300] [--threshold 20]

Opciones:
    --interval  segundos entre comprobaciones (default: 300 = 5 min)
    --threshold páginas nuevas mínimas para re-correr el diff (default: 20)
               Si el libro llega al 100% se re-corre siempre.

Estado persistente: surya_watcher_state.json (página count en el último diff)
"""
import json, subprocess, sys, time, argparse
from pathlib import Path
from datetime import datetime

HERE = Path(__file__).resolve().parent
CFG = json.loads((HERE / "books.json").read_text())
SURYA = HERE / "surya"
OUT   = HERE / "out_surya"
STATE_FILE = HERE / "surya_watcher_state.json"

def page_count(book):
    bdir = SURYA / book
    if not bdir.exists():
        return 0
    return sum(1 for _ in bdir.rglob("*.surya.txt"))

def max_pages(book):
    """Máximo número de página visto en el OCR (approx total)."""
    bdir = SURYA / book
    if not bdir.exists():
        return None
    nums = []
    for f in bdir.rglob("*.surya.txt"):
        stem = f.stem.replace(".surya", "")   # e.g. "p0123"
        if stem.startswith("p") and stem[1:].isdigit():
            nums.append(int(stem[1:]))
    return max(nums) if nums else None

def load_state():
    if STATE_FILE.exists():
        return json.loads(STATE_FILE.read_text())
    return {}

def save_state(state):
    STATE_FILE.write_text(json.dumps(state, indent=2))

def run_diff(book):
    print(f"[watcher] diff_align_surya --book {book} ...", flush=True)
    r = subprocess.run(
        [sys.executable, str(HERE / "diff_align_surya.py"), "--book", book],
        capture_output=True, text=True, cwd=HERE
    )
    print(r.stderr.strip(), flush=True)

def run_report():
    # --candidates: informe directo del diff local (sin adjudicación LLM)
    print("[watcher] build_surya_report --candidates ...", flush=True)
    r = subprocess.run(
        [sys.executable, str(HERE / "build_surya_report.py"), "--candidates"],
        capture_output=True, text=True, cwd=HERE
    )
    print(r.stderr.strip() or r.stdout.strip(), flush=True)

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--interval",  type=int, default=300,  help="segundos entre polls")
    ap.add_argument("--threshold", type=int, default=20,   help="páginas nuevas mínimas")
    a = ap.parse_args()

    books = list(CFG["books"].keys())
    print(f"[watcher] inicio — interval={a.interval}s threshold={a.threshold}pgs", flush=True)
    print(f"[watcher] {len(books)} libros monitorizados", flush=True)

    while True:
        state = load_state()
        updated = []
        for book in books:
            done = page_count(book)
            if done == 0:
                continue
            prev = state.get(book, {}).get("pages_at_diff", 0)
            mx   = max_pages(book)
            complete = (mx is not None and done >= mx)
            new_pages = done - prev

            should_run = (new_pages >= a.threshold) or (complete and new_pages > 0)
            if not should_run:
                continue

            pct = f"{done}/{mx}" if mx else f"{done}/?"
            print(f"\n[watcher] {datetime.now().strftime('%H:%M:%S')} "
                  f"{book}  {pct} pgs (+{new_pages} nuevas) {'✓ COMPLETO' if complete else ''}", flush=True)
            run_diff(book)
            state.setdefault(book, {})["pages_at_diff"] = done
            state[book]["last_run"] = datetime.now().isoformat(timespec="seconds")
            save_state(state)
            updated.append(book)

        if updated:
            run_report()
            print(f"[watcher] HTML regenerado — libros actualizados: {', '.join(updated)}", flush=True)
        else:
            print(f"[watcher] {datetime.now().strftime('%H:%M:%S')} sin cambios suficientes", flush=True)

        time.sleep(a.interval)

if __name__ == "__main__":
    main()
