# -*- coding: utf-8 -*-
"""Nhờ AGY trích xuất bảng scan 'TỶ LỆ PHA MÀU ĐƠN (NGUYÊN LIỆU NHẬP BÊN NGOÀI)' → file MD nguyên văn."""
import json, os, subprocess, time

AGY = r"C:\Users\admin\AppData\Local\agy\bin\agy.exe"
DIR = r"C:\Claw 2\Nghien cuu\Du-an-A-Quy-trinh-son"
PROJECT = "2f54d0c6-f33f-4dae-b5b7-840339496ec7"
OUT = os.path.join(DIR, 'TLP_MAU_DON_HE_DUNG_MOI_2025_trich-xuat.md')

p = ('Read EVERY image in the folder "nguon_TLP\\anh_trang" (Vietnamese, scanned table): the two full-page renders '
     'trang_1_full.png and trang_2_full.png, plus ALL 18 magnified tiles trang1_o1..o9 and trang2_o1..o9. '
     'This is a BT CHEM internal form named "TỶ LỆ PHA MÀU ĐƠN (NGUYÊN LIỆU NHẬP BÊN NGOÀI)" (Phụ lục 03, mã QT-QC-NLM/01, '
     'ngày 09/09/2025) with TWO tables. Extract it VERBATIM into ONE markdown file with these sections:\n'
     '1. "## THÔNG TIN BIỂU MẪU": company header, document title, phụ lục no., mã quy trình, ngày, page numbers found.\n'
     '2. "## BẢNG 1 — ...": a markdown table with columns: Stt | Tên nguyên liệu | Tên màu đơn | Tỷ lệ pha (nguyên liệu) | '
     'Pha Màu 03/18 | Dung môi Pegasol. Keep EXACTLY the same column structure as the scan; where a cell is blank write "-", '
     'where illegible write "không đọc rõ". Copy every STT row of Table 1 AND every sub-row (a STT may have several colour '
     'variants - list them all, one row each) - do NOT merge or summarise rows.\n'
     '3. "## BẢNG 2 — ...": markdown table with the columns of the second table (Stt | Tên màu đơn | Loại màu đơn sử dụng | '
     'Tỷ lệ | Ghi chú) - all rows.\n'
     '4. "## GHI CHÚ / CHÂN TRANG": any footnotes, notes under the tables, signature blocks (write ONLY the department/role '
     'labels such as "BGĐ xem xét, ký duyệt", "Phòng RD xác nhận", "Phòng QC1 xác nhận" - DO NOT write any personal name).\n'
     '5. "## ĐIỂM CẦN XÁC NHẬN": list cells you are unsure about, with page + tile where you saw them.\n'
     'RULES: keep original spelling/typos exactly as printed (do NOT correct), do NOT invent missing values, do NOT translate '
     'product names. Do not include any personal names. Write the single output file "%s".' % OUT)

cmd = [AGY, '-p', p, '--model', 'gemini-3.8-flash-high', '--project', PROJECT, '--add-dir', DIR,
       '--dangerously-skip-permissions', '--output-format', 'json', '--print-timeout', '0']
t0 = time.time()
r = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='replace', cwd=DIR)
dt = time.time() - t0
with open(os.path.join(DIR, '_log_TLP_trichxuat.txt'), 'w', encoding='utf-8') as f:
    f.write('=== %.1f s | rc=%s ===\n' % (dt, r.returncode))
    f.write((r.stdout or '') + '\n' + (r.stderr or '')[-1500:])
try:
    j = json.loads(r.stdout)
    print('   → rc=%s | %.1f s | tokens=%s' % (r.returncode, dt, (j.get('usage') or {}).get('total_tokens')))
except Exception:
    print('   → rc=%s | %.1f s | (không parse json)' % (r.returncode, dt))
print('   file trích xuất:', os.path.exists(OUT), (os.path.getsize(OUT) if os.path.exists(OUT) else 0), 'byte')
