#!/usr/bin/env python3
"""
Batch processor for themdongtrong.md rules.
Processes ONE batch per run, updates progress.
Designed for cron: runs isolated, handles one batch, updates progress.json.

Usage: python3 run_next_batch.py
"""

import json
import os
import subprocess
import sys
from datetime import datetime, timezone

WORKSPACE = "/home/tuan-nguyen/.openclaw/workspace"
FINAL_DIR = os.path.join(WORKSPACE, "Chuan Muc Sadi", "extracted", "final")
PROGRESS_PATH = os.path.join(WORKSPACE, "Chuan Muc Sadi", "progress.json")
SCRIPT_PATH = os.path.join(WORKSPACE, "scripts", "add_blank_lines.py")

# Mapping: progress list name → actual filename (where they differ)
FILENAME_OVERRIDES = {
    "Sadi-131-135-final.md": "Sadi-131-135-gemini-final.md",
    "Sadi-221-225-gemini-final.md": "Sadi-221-225-final.md",
    "Sadi-226-230-qwen-final.md": "Sadi-226-230-gemini-final.md",
    "Sadi-231-235-final.md": "Sadi-231-235-gemini-final.md",
    "Sadi-236-240-qwen-final.md": "Sadi-236-240-gemini-final.md",
    "Sadi-241-245-qwen-final.md": "Sadi-241-245-gemini-final.md",
    "Sadi-246-250-qwen-final.md": "Sadi-246-250-gemini-final.md",
    "Sadi-251-255-qwen-final.md": "Sadi-251-255-gemini-final.md",
    "Sadi-256-260-qwen-final.md": "Sadi-256-260-gemini-final.md",
}


def load_progress():
    with open(PROGRESS_PATH, 'r', encoding='utf-8') as f:
        return json.load(f)


def save_progress(prog):
    with open(PROGRESS_PATH, 'w', encoding='utf-8') as f:
        json.dump(prog, f, indent=2, ensure_ascii=False)
        f.write('\n')


def get_next_batch(prog):
    idx = prog["currentIndex"]
    batches = prog["batches"]
    if idx + 1 >= len(batches):
        return None
    next_idx = idx + 1
    list_name = batches[next_idx]
    actual_name = FILENAME_OVERRIDES.get(list_name, list_name)
    actual_path = os.path.join(FINAL_DIR, actual_name)
    if not os.path.exists(actual_path):
        print(f"❌ File not found: {actual_path}")
        return None
    return (next_idx, list_name, actual_path)


def process_batch(filepath):
    result = subprocess.run(
        [sys.executable, SCRIPT_PATH, filepath],
        capture_output=True, text=True, timeout=60
    )
    print(result.stdout.strip())
    if result.stderr:
        print(f"STDERR: {result.stderr.strip()}", file=sys.stderr)
    return result.returncode == 0


def main():
    prog = load_progress()
    next_batch = get_next_batch(prog)
    
    if next_batch is None:
        print("✅ ALL BATCHES COMPLETE! No more batches to process.")
        print("🎉 Total batches processed: {}".format(prog["currentIndex"] + 1))
        return
    
    next_idx, list_name, actual_path = next_batch
    total = len(prog["batches"])
    
    print(f"📦 Processing batch [{next_idx+1}/{total}]: {list_name}")
    
    success = process_batch(actual_path)
    
    if success:
        prog["currentIndex"] = next_idx
        prog["currentFile"] = os.path.basename(actual_path)
        prog["completedAt"] = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
        save_progress(prog)
        print(f"✅ Done! Progress: batch {next_idx+1}/{total}, file: {prog['currentFile']}")
        
        # Check if last batch
        if next_idx >= len(prog["batches"]) - 1:
            print("\n" + "="*60)
            print("🏁 ALL 37 BATCHES COMPLETED! 🏁")
            print("="*60)
    else:
        print(f"❌ FAILED to process {list_name}")
        sys.exit(1)


if __name__ == '__main__':
    main()
