#!/usr/bin/env python3
"""
Trích xuất text RAW từ JSON Cloud Vision → Markdown.
Mỗi file JSON (5 trang) → 1 file .md (5 phần ## PAGE X).

Usage:
  python3 json_to_markdown_raw.py <json_dir> <output_dir>
Example:
  python3 json_to_markdown_raw.py "An Duc Tam Bao/ocr/raw/" "An Duc Tam Bao/extracted/"
"""
import os
import sys
import json
import glob
import re


def json_to_markdown(json_path, output_dir, start_page):
    """Trích xuất text từ 1 file JSON → 1 file Markdown."""
    with open(json_path, 'r', encoding='utf-8') as f:
        data = json.load(f)

    basename = os.path.splitext(os.path.basename(json_path))[0]
    out_path = os.path.join(output_dir, f"{basename}.md")

    lines = []
    for i, response in enumerate(data.get('responses', [])):
        page_num = start_page + i
        fta = response.get('fullTextAnnotation', {})
        text = fta.get('text', '').strip()

        lines.append(f"## PAGE {page_num}")
        lines.append("")
        if text:
            lines.append(text)
        else:
            lines.append("*(trang trống)*")
        lines.append("")

    os.makedirs(output_dir, exist_ok=True)
    with open(out_path, 'w', encoding='utf-8') as f:
        f.write('\n'.join(lines))

    return out_path, len(data.get('responses', []))


def main():
    if len(sys.argv) < 3:
        print("Usage: python3 json_to_markdown_raw.py <json_dir> <output_dir>")
        sys.exit(1)

    json_dir = sys.argv[1]
    output_dir = sys.argv[2]

    json_files = sorted(
        glob.glob(os.path.join(json_dir, '*.json')),
        key=lambda f: int(re.search(r'output-(\d+)-to', os.path.basename(f)).group(1))
    )

    if not json_files:
        print(f"❌ Không tìm thấy file JSON nào trong {json_dir}")
        sys.exit(1)

    print(f"📄 Tìm thấy {len(json_files)} file JSON")
    total_pages = 0

    for jf in json_files:
        out_path, pages = json_to_markdown(jf, output_dir, total_pages + 1)
        total_pages += pages
        print(f"   ✅ {os.path.basename(out_path)} ({pages} trang)")

    print(f"\n🎉 Done! {len(json_files)} file .md → {os.path.abspath(output_dir)}")
    print(f"   Tổng: {total_pages} trang")


if __name__ == '__main__':
    main()
