# -*- coding: utf-8 -*-
"""PIPELINE 2 BƯỚC cho PHIẾU LÀM MẪU MÀU thật (PT-008H):
   BƯỚC 1: AGY đọc phiếu (ảnh toàn bộ + 12 ô zoom) → trích xuất NGUYÊN VĂN từng bước/tỉ lệ/cách thi công/thời gian khô
   BƯỚC 2: đối chiếu với quy trình đã đề xuất cho lô 08 + gói kiến thức CSDLA → BÀI HỌC & ĐIỀU CHỈNH (học hỏi)
Dùng: python _pipeline_phieu.py
"""
import json, os, subprocess, time

AGY = r"C:\Users\admin\AppData\Local\agy\bin\agy.exe"
D = r"C:\Claw 2\Nghien cuu\Du-an-A-Quy-trinh-son"
PROJECT = "2f54d0c6-f33f-4dae-b5b7-840339496ec7"
PHIEU = os.path.join(D, 'phieu_mau', 'PT-008H')
KIEN_THUC = os.path.join(D, 'CSDLA_KIEN_THUC_HUAN_LUYEN.md')
DEXUAT08 = os.path.join(D, 'QUY_TRINH_DE_XUAT_OAK-TRANG-BAC_2026-10-06.md')
OUT1 = os.path.join(D, 'PHIEU_PT-008H_trich-xuat_2026-10-06.md')
OUT2 = os.path.join(D, 'BAI_HOC_PT-008H_so-voi-de-xuat_2026-10-06.md')


def chay(prompt, log):
    cmd = [AGY, '-p', prompt, '--model', 'gemini-3.8-flash-high', '--project', PROJECT, '--add-dir', D,
           '--dangerously-skip-permissions', '--output-format', 'json', '--print-timeout', '0']
    t0 = time.time()
    p = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='replace', cwd=D)
    dt = time.time() - t0
    open(log, 'w', encoding='utf-8').write((p.stdout or '') + '\n' + (p.stderr or '')[-800:])
    try:
        j = json.loads(p.stdout)
        print('   → rc=%s | %.1f s | tokens=%s' % (p.returncode, dt, (j.get('usage') or {}).get('total_tokens')))
    except Exception:
        print('   → rc=%s | %.1f s' % (p.returncode, dt))
    return dt


print('=== BƯỚC 1: AGY ĐỌC PHIẾU LÀM MẪU MÀU (PT-008H) ===')
p1 = ('Read ALL images in the folder "phieu_mau\\PT-008H" (Vietnamese): the full sheet PT-008H_toan-bo.jpg and the 12 '
      'magnified tiles phieu_o01..phieu_o12. This is a HANDWRITTEN Vietnamese "PHIẾU LÀM MẪU MÀU" (colour sample record). '
      'Extract it VERBATIM into a markdown file: header (sample code, wood type, paint system, date, person if any) then '
      'EVERY table row as: STT | tên hoá chất / nguyên liệu (nguyên văn) | tỉ lệ pha | cách thi công (vải/súng/cọ/lau/nhúng...) '
      '| thời gian khô | ghi chú. Read the handwriting carefully from the magnified tiles; where a cell is illegible write '
      '"không đọc rõ" - do NOT guess and do NOT invent. Keep original wording and spelling (even typos). Also list the '
      'separate sections if the sheet has them (e.g. Stain, chất ngấm, Diluen, các bước 1..n). Add a short section '
      '"ĐIỂM CẦN XÁC NHẬN" listing the cells you are unsure about. Write the single output file "%s".' % OUT1)
chay(p1, os.path.join(D, '_log_phieu_b1.txt'))
print('   file bước 1:', os.path.exists(OUT1), (os.path.getsize(OUT1) if os.path.exists(OUT1) else 0), 'byte')

print('=== BƯỚC 2: HỌC HỎI — ĐỐI CHIẾU PHIẾU THẬT VỚI QUY TRÌNH ĐÃ ĐỀ XUẤT + KIẾN THỨC CSDLA ===')
p2 = ('Read these three inputs (UTF-8, Vietnamese): (1) the verbatim extraction of the real sample sheet "%s"; '
      '(2) the process I proposed for the same looking sample (whitewashed OAK) "%s"; (3) the trained knowledge pack '
      '"%s" (owner training rules, approved standard process, 34 standard steps, company QT_ library). '
      'Write a LESSONS-LEARNED document that compares the REAL sheet with my proposal: which steps match, which differ '
      '(order, systems, number of colour coats, soak/bleach steps, chemicals, ratios, application methods, drying times), '
      'and what I must CHANGE in the standard proposal so it matches how the sample is really made (especially if the real '
      'sheet uses a WATER-BASED system, a soaking/penetrating agent, or different order). Also list 3-8 concrete LESSONS to '
      'store in the database, and state clearly which cells of the sheet are uncertain. Be concise, use tables and bullets, '
      'and do NOT mention KPH cases. Write the single output file "%s".' % (OUT1, DEXUAT08, KIEN_THUC, OUT2))
chay(p2, os.path.join(D, '_log_phieu_b2.txt'))
print('   file bước 2:', os.path.exists(OUT2), (os.path.getsize(OUT2) if os.path.exists(OUT2) else 0), 'byte')
print('HOÀN TẤT PIPELINE PHIẾU')
