import os
import json
import urllib.request
import urllib.error
import sys

def load_env():
    env_path = "/home/tuan-nguyen/.openclaw/workspace/.env"
    if os.path.exists(env_path):
        with open(env_path, "r") as f:
            for line in f:
                if "=" in line and not line.startswith("#"):
                    k, v = line.strip().split("=", 1)
                    os.environ[k] = v.strip('"\'')

def edit_text(input_file, output_file):
    load_env()
    api_key = os.environ.get("OPENROUTER_API_KEY")
    if not api_key:
        print("OPENROUTER_API_KEY not found in environment.")
        return

    with open(input_file, "r", encoding="utf-8") as f:
        content = f.read()

    prompt = """Hãy đóng vai học giả Phật học Nguyên thủy thông thạo tiếng Myanmar và Pali. Hãy hiệu đính (proofread) văn bản tiếng Myanmar sau đây. 
Văn bản này được trích xuất (OCR) từ sách "Chuẩn Mục Sa Di", có thể chứa các lỗi sai chính tả, sai thuật ngữ Pali, lỗi dấu phụ, lỗi nhầm chữ (ví dụ nhầm số `၈` thành `ဂ`, `ဥုး` thành `ဦး`, v.v.). 
Hãy sửa lại cho ĐÚNG chuẩn chính tả tiếng Myanmar và thuật ngữ Pali. 
ĐẶC BIỆT LƯU Ý:
- Giữ NGUYÊN VẸN định dạng markdown gốc (các tiêu đề như "## Trang 226", ngắt đoạn, v.v.).
- Không thêm bớt văn bản ngoài phần nội dung hiệu đính. Trả về TOÀN BỘ văn bản đã hiệu đính từ đầu đến cuối.
- TUYỆT ĐỐI KHÔNG bỏ sót bất kỳ dòng nào.

VĂN BẢN CẦN HIỆU ĐÍNH:
""" + content

    data = {
        "model": "qwen/qwen3.5-397b-a17b",
        "messages": [
            {"role": "system", "content": "You are a meticulous scholar of Theravada Buddhism, fluent in Pali and Myanmar language."},
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.2
    }

    req = urllib.request.Request(
        "https://openrouter.ai/api/v1/chat/completions",
        data=json.dumps(data).encode("utf-8"),
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
            "HTTP-Referer": "https://openclaw.ai",
            "X-Title": "OpenClaw OCR"
        }
    )

    print("Gửi yêu cầu tới OpenRouter (Qwen 3.5 397B)...")
    try:
        with urllib.request.urlopen(req) as response:
            result = json.loads(response.read().decode("utf-8"))
            edited_text = result["choices"][0]["message"]["content"]
            
            if edited_text.startswith("```markdown"):
                edited_text = edited_text[11:]
                if edited_text.endswith("```"):
                    edited_text = edited_text[:-3]
            elif edited_text.startswith("```"):
                edited_text = edited_text[3:]
                if edited_text.endswith("```"):
                    edited_text = edited_text[:-3]
                    
            with open(output_file, "w", encoding="utf-8") as f:
                f.write(edited_text.strip() + "\n")
            print(f"✅ Đã lưu kết quả hiệu đính vào {output_file}")
    except urllib.error.HTTPError as e:
        print(f"HTTP Lỗi: {e.code} - {e.read().decode('utf-8')}")
    except Exception as e:
        print(f"Lỗi: {e}")

if __name__ == "__main__":
    input_path = "/home/tuan-nguyen/.openclaw/workspace/Chuan Muc Sadi/extracted/Sadi-226-230-gemini.md"
    output_path = "/home/tuan-nguyen/.openclaw/workspace/Chuan Muc Sadi/extracted/Sadi-226-230-gemini-edited.md"
    edit_text(input_path, output_path)
