# -*- coding: utf-8 -*-
"""Chạy AGY (model MẠNH) cho LÔ 10 — bước 1: phân tích MÀU gỗ mộc + màu mẫu.
   Dùng:  python _run_agy_lo10_b1.py
"""
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"
MODEL = sys.argv[2] if len(sys.argv) > 2 else 'gemini-3.1-pro-high'
BUOC = sys.argv[1] if len(sys.argv) > 1 else '1'

if BUOC == '1':
    YC = os.path.join(DIR, 'YEU_CAU_L010_B1_phan_tich_mau.txt')
    OUT = os.path.join(DIR, 'lo10-0710', 'PHAN_TICH_MAU_L010.md')
    EXTRA = ('Read the instruction file "%s" (UTF-8, Vietnamese) and follow it EXACTLY. Read the images with your OWN '
             'vision: lo10-0710\\anh_mau\\moc_01.jpg (raw wood) and mau_01.jpg (finished colour sample), plus ALL 8 zoom '
             'tiles zoom_1..zoom_8 and the measured colours in lo10-0710\\anh_mau\\_zoom_do_mau.txt — use those measured '
             'numbers as the colour data (do NOT invent new numbers). This is a COLOUR ANALYSIS task only: sections A, B, '
             'C, D of the instruction file. The most important judgement is C: is the colour DYE (penetrating stain) or '
             'PIGMENT (film colour) or DYE + PIGMENT, with visible evidence and %% confidence. Do NOT write any painting '
             'process here. Write the single output file "%s" and end it with the line HOAN TAT.' % (YC, OUT))
else:
    YC = os.path.join(DIR, 'YEU_CAU_L010_B2_quytrinh_congthuc.txt')
    OUT = os.path.join(DIR, 'lo10-0710', 'QUY_TRINH_VA_CONG_THUC_PHA_MAU_L010.md')
    EXTRA = ('Read the instruction file "%s" (UTF-8, Vietnamese) and follow it EXACTLY. Read your own colour analysis in '
             'lo10-0710\\PHAN_TICH_MAU_L010.md, the owner training rules + approved standards in CSDLA_KIEN_THUC_HUAN_LUYEN.md, '
             'the 34 standard steps and the three milestone processes in CSDLA_BOSUNG_QT_MOC.md (112 walnut DYE stain, 116 '
             'general standard, 118 branch-2), and the CSDL B dye pack CSDLB_GOI_MAU_DYE.md (45 measured DYE tiles + 26-code '
             'catalogue with stock). Produce EXACTLY the two parts asked: PART 1 = the coating process table (max 9 rows, '
             'coating steps only, colour-type classification only, never name any paint system, mandatory colour-check/touch-up '
             'row right after EVERY sanding); PART 2 = the COLOUR FORMULA, DYE-first (table of 4-6 rows with code %% role, how '
             'to mix, 4-row correction table, 3 test batches). Use ONLY codes that exist in CSDL B. Nothing else, no analysis '
             'restated, no traceability. Write the single output file "%s" and end it with the line HOAN TAT.' % (YC, OUT))

cmd = [AGY, '-p', EXTRA, '--model', MODEL, '--effort', 'high', '--project', PROJECT, '--add-dir', DIR,
       '--dangerously-skip-permissions', '--output-format', 'json', '--print-timeout', '0']
print('model:', MODEL, '| bước:', BUOC)
print('bắt đầu:', time.strftime('%H:%M:%S'))
t0 = time.time()
p = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='replace', cwd=DIR)
dt = time.time() - t0
log = os.path.join(DIR, 'lo10-0710', '_log_agy_b%s_%s.txt' % (BUOC, MODEL))
with open(log, 'w', encoding='utf-8') as f:
    f.write('=== %.1f s | rc=%s | model=%s ===\n' % (dt, p.returncode, MODEL))
    f.write((p.stdout or '') + '\n--- stderr ---\n' + (p.stderr or '')[-3000:])
print('agy xong sau %.1f s · exit=%s' % (dt, p.returncode))
try:
    j = json.loads(p.stdout)
    print('status =', j.get('status'))
    print('usage =', json.dumps(j.get('usage'), ensure_ascii=False))
    r = (j.get('response') or '')
    print('response (đầu):', r[:600].replace('\n', ' '))
except Exception as e:
    print('(không parse được json:', e, ')')
    print((p.stdout or '')[:600])
    print('STDERR:', (p.stderr or '')[-600:])
ok = os.path.exists(OUT)
print('FILE:', os.path.getsize(OUT) if ok else 0, 'byte |', OUT)
if ok:
    txt = open(OUT, encoding='utf-8').read()
    print('HOAN TAT:', 'HOAN TAT' in txt.upper(), '| số dòng:', txt.count('\n') + 1)
