# -*- coding: utf-8 -*-
"""Chạy BƯỚC 2 bản ÉP CHUẨN NHÁNH 2 (id 118) cho mẫu Oak/Veneer có ghim sớ tương phản — để so với bản chuẩn chung.
Dùng: python _run_buoc2_nhanh2.py <TEN_MAU_RA> <file_phan_tich.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]
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))
print('đầu ra       :', os.path.basename(QT))
p2 = ('Read the instruction file "%s" (UTF-8, Vietnamese) and follow it EXACTLY, with ONE OVERRIDE: this lot is confirmed '
      'to be the CONTRASTING-GRAIN type, so PHƯƠNG ÁN 1 MUST be the BRANCH-2 standard (quy_trinh id 118) - the one built '
      'from the REAL sample sheet PT-008H (quy_trinh id 117) that the owner sent as "how the sample is really made". '
      'Follow the BRANCH 2 chain exactly: WIPE-APPLIED COLOUR THAT CREATES THE HIGHLIGHT EFFECT (luật #28 - apply the colour '
      'with a cloth and rub harder on the zones that must be LIGHT so the colour is wiped back and fades lighter = highlight, '
      'while the grain/pores stay dark; dry ~1 h) -> spray stain (dry ~30 min) -> '
      'SPRAY OIL PENETRATING AGENT + additive (dry ~2 h) -> spray CLEAR primer (dry ~2 h) -> spray stain touch-up '
      '(dry ~15 min) + BRUSH-APPLIED dark glaze layer 1 (dry ~15 min) -> spray CLEAR gloss coat 1 (dry ~2 h) -> '
      'BRUSH-APPLIED dark glaze layer 2 applied ON TOP of the gloss film (dry ~15 min) -> spray CLEAR gloss coat 2 '
      '(finish). Because the oil penetrating agent is used, DO NOT use any washcoat. Keep the dark glaze as the '
      'TRANSPARENT-COLOUR layer that stays in the grain/pores while the flat face stays clean. PHƯƠNG ÁN 2 is the '
      'alternative WITHOUT the penetrating agent (washcoat route, id 116 style chain) - one line of key difference. '
      'Read the analysis from step 1 (file "%s") and the trained knowledge in "%s" (27 rules, both standards, 34 steps, '
      'QT_ library) and apply them; state the reason for choosing branch 2 in one line. Each PA: one table of max 8 rows, '
      'coating steps only, no commercial product names, mandatory colour-check/touch-up row after every sanding. '
      'IMPORTANT: do NOT mention any paint SYSTEM (NC/PU/water/UV/2K) - classify every layer by COLOUR TYPE only '
      '(clear/colourless, pigmented, transparent colour, other). The document must contain ONLY: short title, sample '
      'image, missing-raw-wood note, two tables, 3-5 mandatory notes. 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')
