# -*- coding: utf-8 -*-
"""Chạy CHỈ BƯỚC 2 (áp kiến thức CSDLA → quy trình đề xuất) cho một lô đã có bản phân tích.
Dùng: python _run_buoc2_only.py <TEN_MAU_RA> <file_phan_tich_dau_vao.md>
"""
import json, os, subprocess, sys, 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"
NHAN = time.strftime('%Y-%m-%d')
MAU = sys.argv[1]
PT = sys.argv[2] if len(sys.argv) > 2 else os.path.join(DIR, 'PHAN_TICH_%s_%s.md' % (MAU.replace('-v3', '-v2'), NHAN))
B2 = os.path.join(DIR, 'YEU_CAU_BUOC2_ap_csdl.txt')
KIEN_THUC = os.path.join(DIR, 'CSDLA_KIEN_THUC_HUAN_LUYEN.md')
QT = os.path.join(DIR, 'QUY_TRINH_DE_XUAT_%s_%s.md' % (MAU, NHAN))

print('phân tích vào:', os.path.basename(PT), os.path.exists(PT))
print('đầu ra       :', os.path.basename(QT))
p2 = ('Read the instruction file "%s" (UTF-8, Vietnamese) and follow it EXACTLY. This is STEP 2: take the analysis '
      'from step 1 (file "%s") and apply ALL the trained knowledge in "%s" (the 27 owner training rules, the TWO approved '
      'standard processes - id 116 GENERAL for even-tone samples and id 118 BRANCH-2 for oak/veneer samples with '
      'contrasting dark grain/pores built like the REAL sample sheet PT-008H - the 34 standard steps and the company QT_ '
      'library) to produce the FINAL proposed painting process. PA 1 MUST be the standard matching the sample TYPE: '
      'even tone -> id 116 chain (stain base -> washcoat -> colour check/touch-up without sanding -> wipe colour into the '
      'pores -> clear lock coat >=100-120 um -> sanding -> colour check/touch-up -> matt topcoat); contrasting dark grain '
      'lines -> BRANCH 2 chain (wipe-effect colour -> spray stain -> SPRAY OIL PENETRATING AGENT (no washcoat!) -> clear '
      'primer -> spray stain touch-up + BRUSH-APPLIED dark glaze layer 1 -> clear gloss coat 1 -> BRUSH-APPLIED dark glaze '
      'layer 2 on the gloss film -> clear gloss coat 2). PA 2 is the alternative with one line of key difference. Each PA: '
      'one table of max 8 rows, coating steps only, no commercial product names, a mandatory colour-check/touch-up row '
      'after every sanding. IMPORTANT: do NOT mention any paint SYSTEM (NC/PU/water/UV/2K) anywhere - classify every layer '
      'by COLOUR TYPE only (clear/colourless, pigmented, transparent colour, other). The document must contain ONLY: short '
      'title, sample image, the missing-raw-wood note if applicable, the two tables and 3-5 mandatory notes - NO analysis '
      'data, NO traceability, NO KPH mentions. Write the single output file "%s".' % (B2, PT, KIEN_THUC, QT))

cmd = [AGY, '-p', p2, '--model', 'gemini-3.8-flash-high', '--project', PROJECT, '--add-dir', DIR,
       '--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=DIR)
dt = time.time() - t0
with open(os.path.join(DIR, '_log_buoc2_%s.txt' % MAU), 'w', encoding='utf-8') as f:
    f.write('=== %.1f s | rc=%s ===\n' % (dt, p.returncode))
    f.write((p.stdout or '') + '\n' + (p.stderr or '')[-1500:])
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 | (không parse json)' % (p.returncode, dt))
print('   file bước 2:', os.path.exists(QT), (os.path.getsize(QT) if os.path.exists(QT) else 0), 'byte')
