# -*- coding: utf-8 -*-
r"""B161: gọi AGY (gemini-3.8-flash-high) đọc 4 ảnh báo cáo Trí QC 14/10 — ghi dần ra NOI_DUNG_AGY.md."""
import io, json, os, subprocess, sys, time

AGY = r'C:\Users\admin\AppData\Local\agy\bin\agy.exe'
LO = r'C:\Claw 2\QC\images\_agy_tri_1410'
RA = os.path.join(LO, 'NOI_DUNG_AGY.md')
LOG = r'C:\Claw 2\QC\_qc1410\_log_agy.txt'

boi_canh = io.open(os.path.join(LO, 'BOI_CANH.txt'), encoding='utf-8').read()
yeu_cau = io.open(os.path.join(LO, 'YEU_CAU.txt'), encoding='utf-8').read()
NGUYEN_VAN = io.open(os.path.join(LO, 'NGUYEN_VAN_ZALO.txt'), encoding='utf-8').read()
PROMPT = (boi_canh + '\n\nNGUYEN VAN TIN NHAN ZALO (nguon goc):\n' + NGUYEN_VAN + '\n\n' + yeu_cau +
          '\n\nGhi ket qua ra file: NOI_DUNG_AGY.md (trong chinh thu muc nay).')

print('  bắt đầu', time.strftime('%H:%M:%S'), '| model gemini-3.8-flash-high | 4 ảnh', flush=True)
t0 = time.time()
r = subprocess.run([AGY, '-p', PROMPT, '--model', 'gemini-3.8-flash-high',
                    '--add-dir', LO, '--dangerously-skip-permissions', '--output-format', 'json'],
                   capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=2400)
gi = round(time.time() - t0, 1)
with io.open(LOG, 'w', encoding='utf-8') as f:
    f.write(r.stdout or '')
    f.write('\n--- STDERR ---\n')
    f.write((r.stderr or '')[:4000])
print('  agy xong sau %s s · exit=%s' % (gi, r.returncode), flush=True)
try:
    j = json.loads(r.stdout)
    print('  status =', j.get('status'))
    print('  usage  =', json.dumps(j.get('usage'), ensure_ascii=False))
    if j.get('error'):
        print('  error  =', str(j['error'])[:200])
except Exception as e:
    print('  (không phân tích được JSON:', e, ')')
if os.path.exists(RA):
    txt = io.open(RA, encoding='utf-8').read()
    print('  FILE: %d byte · %d dòng | HOAN TAT: %s | KẾT LUẬN CHỌN ẢNH: %s'
          % (os.path.getsize(RA), txt.count('\n') + 1, 'HOAN TAT' in txt, 'KẾT LUẬN CHỌN ẢNH' in txt))
else:
    print('  KHÔNG CÓ FILE kết quả')
