from pypdf import PdfReader, PdfWriter
import os

files = [
    ("Dieu_gi_that_su_co_gia_tri_51-100.pdf", 51, 100),
    ("Dieu_gi_that_su_co_gia_tri_101-150.pdf", 101, 150),
    ("Dieu_gi_that_su_co_gia_tri_151-166.pdf", 151, 166)
]

batches = []
for start_batch in range(81, 170, 10):
    end_batch = min(start_batch + 9, 166)
    batches.append((start_batch, end_batch))

sh_script = "#!/bin/bash\n\n"
delay = 0

for start_batch, end_batch in batches:
    for f_name, f_start, f_end in files:
        if f_start <= start_batch <= f_end:
            idx_start = start_batch - f_start
            idx_end = min(end_batch, f_end) - f_start
            
            reader = PdfReader(f_name)
            writer = PdfWriter()
            for i in range(idx_start, idx_end + 1):
                writer.add_page(reader.pages[i])
            
            out_pdf = f"tmp_{start_batch}_{end_batch}.pdf"
            with open(out_pdf, "wb") as f_out:
                writer.write(f_out)
            
            phys_start = start_batch - 8
            phys_end = end_batch - 8
            
            msg = f"Vui lòng trích xuất từ file PDF /opt/openclaw/.openclaw/workspace/{out_pdf} (tương ứng với Trang {phys_start} đến Trang {phys_end} của sách gốc) bằng công cụ pdf. Quy tắc BẮT BUỘC: 1. Giữ nguyên văn tuyệt đối (literal transcription). 2. Gộp dòng thành các đoạn văn trọn vẹn, cách nhau 1 dòng trống. 3. Không nhầm ဖ/ဘ, ျ/ြ, ထ/ဌ, ပ/ဘ. Không bỏ sót စ်. 4. Không tự ý viết tắt လည်းကော thành ၎, သုံး thành ၃. 5. Không đổi chính tả: သြ/ဩ, မ်/ံ, ာ/ါ, ယ့်/ဲ့. 6. Giữ nguyên dấu phẩy ၊, không đổi thành ။ hay ... 7. Bỏ header/footer. 8. Thêm chữ 'Trang X' ở đầu mỗi trang sách vật lý. Sau đó dùng logic script /opt/openclaw/.openclaw/workspace/append_doc.sh để append vào Google Doc ID 1xiB5pmqTOSch_VJh735mYHLWzCdBKWNNBFo0VCynBV8. Cuối cùng dùng tool message gửi thông báo qua telegram id: 7795838422."

            sh_script += f"(\n  sleep {delay}\n  openclaw agent --session-id 'extract-{start_batch}-{end_batch}' --message \"{msg}\"\n) &\n\n"
            delay += 900
            break

with open("run_all_batches.sh", "w") as f:
    f.write(sh_script)

os.system("chmod +x run_all_batches.sh")