# -*- coding: utf-8 -*-
"""PIPELINE 2 BƯỚC VỚI AGY (theo luật huấn luyện mới của chủ dự án):
   BƯỚC 1: agy đọc ảnh mẫu + ô zoom + số đo → PHÂN TÍCH ảnh (file PHAN_TICH_...md)
   BƯỚC 2: lấy phân tích đó + GÓI KIẾN THỨC CSDLA đã huấn luyện → QUY TRÌNH ĐỀ NGHỊ CHUẨN (2 phương án, gọn)
Dùng:  python _pipeline_agy_2_buoc.py <ten_mau>        (mặc định: NAU-XAM-TRO)
"""
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] if len(sys.argv) > 1 else 'NAU-XAM-TRO'
B1 = os.path.join(DIR, 'YEU_CAU_BUOC1_phan_tich.txt')
B2 = os.path.join(DIR, 'YEU_CAU_BUOC2_ap_csdl.txt')
KIEN_THUC = os.path.join(DIR, 'CSDLA_KIEN_THUC_HUAN_LUYEN.md')
PT = os.path.join(DIR, 'PHAN_TICH_%s_%s.md' % (MAU, NHAN))
QT = os.path.join(DIR, 'QUY_TRINH_DE_XUAT_%s_%s.md' % (MAU, NHAN))


def chay(prompt, log):
    cmd = [AGY, '-p', prompt, '--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(log, '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 '')[-1200:])
    tok = None
    try:
        j = json.loads(p.stdout)
        tok = (j.get('usage') or {}).get('total_tokens')
        print('   → rc=%s | %.1f s | tokens=%s' % (p.returncode, dt, tok))
    except Exception:
        print('   → rc=%s | %.1f s | (không parse json)' % (p.returncode, dt))
    return dt


print('=== BƯỚC 1: AGY PHÂN TÍCH ẢNH (mẫu %s) ===' % MAU)
p1 = ('Read the instruction file "%s" (UTF-8, Vietnamese) and follow it EXACTLY. This is STEP 1 only: analyse the '
      'sample. Read every image in anh_mau_moi\\ (mau_*.jpg, moc_*.jpg if present, and ALL zoom_*.jpg tiles) plus the '
      'measured colours in anh_mau_moi\\_zoom_do_mau.txt, and report at least 5 colour points, light/dark patches, '
      'colour patches/blocks, the colour technique conclusion with %% confidence (stain mau / lau mau needing a '
      'thinned washcoat / lau glaze long resembling Duro stain / Duro stain), gloss, probable wood species and '
      'product, and the technical requirements to match the sample. Do NOT write the process here. Write the single '
      'output file "%s".' % (B1, PT)).replace('%%', '%')
chay(p1, os.path.join(DIR, '_log_pipeline_b1.txt'))
print('   file bước 1:', os.path.exists(PT), (os.path.getsize(PT) if os.path.exists(PT) else 0), 'byte')
if not os.path.exists(PT):
    sys.exit('DỪNG: bước 1 không tạo được file phân tích')

print('=== BƯỚC 2: ÁP KIẾN THỨC CSDLA → QUY TRÌNH ĐỀ NGHỊ CHUẨN ===')
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))
chay(p2, os.path.join(DIR, '_log_pipeline_b2.txt'))
print('   file bước 2:', os.path.exists(QT), (os.path.getsize(QT) if os.path.exists(QT) else 0), 'byte')
print('HOÀN TẤT PIPELINE 2 BƯỚC')
