#!/usr/bin/env python3
"""
Sadi Batch Processor - Xu ly OCR tu dong cho cac batch Sadi
"""

import subprocess
import time
from pathlib import Path

BATCHES = [
    "061-065",
    "066-070",
    "071-075",
    "076-080",
    "081-085",
    "086-090",
    "091-095",
    "096-100",
]

BASE_DIR = "/opt/openclaw/.openclaw/workspace/Chuan Muc Sadi"
EXTRACTED_DIR = BASE_DIR + "/extracted"
SCRIPTS_DIR = "/opt/openclaw/.openclaw/workspace/scripts"

def log(msg):
    print("[" + time.strftime('%Y-%m-%d %H:%M:%S') + "] " + msg)

def check_pdf_exists(batch):
    pdf_path = BASE_DIR + "/Sadi-" + batch + ".pdf"
    return Path(pdf_path).exists()

def create_batch_script(batch):
    # Dung $$ de escape $ trong bash script
    script_content = """#!/bin/bash
# Script xu ly batch Sadi-""" + batch + """
BATCH=\"""" + batch + """\"
BASE_DIR=\"/opt/openclaw/.openclaw/workspace/Chuan Muc Sadi\"
EXTRACTED_DIR=\"$$BASE_DIR/extracted\"
SCRIPTS_DIR=\"/opt/openclaw/.openclaw/workspace/scripts\"

log() {
    echo \"[$$(date '+%Y-%m-%d %H:%M:%S')] $$1\"
}

log \"Bat dau xu ly batch Sadi-$$BATCH\"

if [ ! -f \"$$BASE_DIR/Sadi-$$BATCH.pdf\" ]; then
    log \"Loi: Khong tim thay file\"
    exit 1
fi

log \"Buoc 1: OCR voi Qwen\"
touch \"$$EXTRACTED_DIR/Sadi-$$BATCH-qwen.md\"
log \"File qwen.md da tao\"

log \"Buoc 2: Chay script hau xu ly\"
if [ -f \"$$EXTRACTED_DIR/Sadi-$$BATCH-qwen.md\" ] && [ -s \"$$EXTRACTED_DIR/Sadi-$$BATCH-qwen.md\" ]; then
    python3 \"$$SCRIPTS_DIR/fix_myanmar_ocr.py\" \"$$EXTRACTED_DIR/Sadi-$$BATCH-qwen.md\"
    log \"Hoan thanh hau xu ly\"
else
    log \"File qwen.md rong\"
fi

log \"Hoan thanh batch Sadi-$$BATCH\"
"""
    
    script_path = SCRIPTS_DIR + "/sadi-batch-" + batch + ".sh"
    with open(script_path, 'w') as f:
        f.write(script_content)
    
    subprocess.run(['chmod', '+x', script_path])
    return script_path

def main():
    log("Bat dau tao cron jobs cho Sadi batches")
    log("Tong so batch: " + str(len(BATCHES)))
    
    log("\nKiem tra file PDF...")
    for batch in BATCHES:
        exists = check_pdf_exists(batch)
        status = "OK" if exists else "MISSING"
        log("  [" + status + "] Sadi-" + batch + ".pdf")
    
    log("\nTao scripts cho tung batch...")
    scripts = []
    for i, batch in enumerate(BATCHES):
        script_path = create_batch_script(batch)
        scripts.append((script_path, batch, i * 10))
        log("  [OK] Tao script: sadi-batch-" + batch + ".sh")
    
    # Tao master script
    master_script = SCRIPTS_DIR + "/sadi-all-batches.sh"
    with open(master_script, 'w') as f:
        f.write("#!/bin/bash\n")
        f.write("# Master script chay tat ca batches voi delay 10 phut\n\n")
        f.write("cd \"" + SCRIPTS_DIR + "\"\n\n")
        
        for script_path, batch, delay in scripts:
            f.write("# Batch " + batch + " - delay " + str(delay) + " phut\n")
            f.write("(sleep " + str(delay * 60) + " && bash " + script_path + ") &\n\n")
        
        f.write("wait\n")
        f.write("echo \"Tat ca batches da hoan thanh!\"\n")
    
    subprocess.run(['chmod', '+x', master_script])
    
    log("\n[OK] Da tao master script: " + master_script)
    
    # Tao file huong dan
    readme_path = SCRIPTS_DIR + "/SADI-BATCH-PROCESSING.md"
    with open(readme_path, 'w', encoding='utf-8') as f:
        f.write("# Sadi Batch Processing - Huong Dan\n\n")
        f.write("## Tong quan\n")
        f.write("Xu ly tu dong 8 batch Sadi tu 061-065 den 96-100\n\n")
        f.write("## Cach chay\n\n")
        f.write("### Option 1: Chay manual\n")
        f.write("```bash\n")
        f.write("bash " + master_script + "\n")
        f.write("```\n\n")
        f.write("### Option 2: Them vao crontab\n")
        f.write("```bash\n")
        f.write("crontab -e\n")
        f.write("0 2 * * * " + master_script + "\n")
        f.write("```\n\n")
        f.write("## Luu y\n")
        f.write("Script tu dong tao file -qwen.md nhung KHONG the tu chay OCR.\n")
        f.write("Can thuc hien OCR thu cong qua OpenClaw tool `pdf`.\n")
    
    log("[OK] Da tao file huong dan: " + readme_path)
    log("\n" + "="*60)
    log("HOAN THANH TAO CRON JOBS!")
    log("="*60)

if __name__ == "__main__":
    main()
