# -*- coding: utf-8 -*-
"""Chạy agy đọc 3 phiếu + mô tả 4 ảnh hiện trường (việc QC 07/10 của Trí)."""
import json, os, subprocess, time

AGY = r"C:\Users\admin\AppData\Local\agy\bin\agy.exe"
WS = r"C:\Claw 2\QC\_agy_tri_0710"
MODEL = 'gemini-3.8-flash-high'
OUT = os.path.join(WS, 'ket_qua.md')

PROMPT = ('Read the instruction file "prompt.txt" in the current workspace (UTF-8, Vietnamese) and follow it EXACTLY. '
          'Read EVERY image in the anh\\ subfolder with your own vision: 3 document photos (a printed process sheet for '
          'MDF, a handwritten B1-B4 sheet, a small R&D form) and 4 workshop photos. Write results progressively into '
          'ket_qua.md and end it with HOAN TAT.')

cmd = [AGY, '-p', PROMPT, '--model', MODEL, '--project', '6fcf8a9c-46c9-4354-b8a1-5b15e55ff027',
       '--add-dir', WS, '--dangerously-skip-permissions', '--output-format', 'json', '--print-timeout', '0']
print('bắt đầu:', time.strftime('%H:%M:%S'), '| model:', MODEL)
t0 = time.time()
p = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='replace', cwd=WS, timeout=2400)
dt = time.time() - t0
io = open(os.path.join(WS, '_log_agy.txt'), 'w', encoding='utf-8')
io.write('=== %.1f s | rc=%s | model=%s ===\n' % (dt, p.returncode, MODEL))
io.write((p.stdout or '') + '\n--- stderr ---\n' + (p.stderr or '')[-3000:])
io.close()
print('agy xong sau %.1f s · exit=%s' % (dt, p.returncode))
try:
    j = json.loads(p.stdout)
    print('status =', j.get('status'), '| usage =', json.dumps(j.get('usage'), ensure_ascii=False))
    print('response (đầu):', (j.get('response') or '')[:400].replace('\n', ' '))
except Exception as e:
    print('(json lỗi:', e, ')')
    print((p.stdout or '')[:500])
    print('STDERR:', (p.stderr or '')[-500:])
ok = os.path.exists(OUT)
print('FILE:', os.path.getsize(OUT) if ok else 0, 'byte |', OUT)
if ok:
    t = open(OUT, encoding='utf-8').read()
    print('HOAN TAT:', 'HOAN TAT' in t.upper(), '| dòng:', t.count('\n') + 1)
