# -*- coding: utf-8 -*-
r"""B167: AGY đọc LÔ A (9 ảnh Lộc 14/10) — gemini-3.8-flash-high, ghi dần ra NOI_DUNG_AGY_A.md."""
import io, json, os, subprocess, time

AGY = r'C:\Users\admin\AppData\Local\agy\bin\agy.exe'
LO = r'C:\Claw 2\QC\images\_agy_loc_1410_A'
RA = os.path.join(LO, 'NOI_DUNG_AGY_A.md')
LOG = r'C:\Claw 2\QC\_qc_loc1410\_log_agy_A.txt'

boi = io.open(os.path.join(LO, 'BOI_CANH.txt'), encoding='utf-8').read()
yc = io.open(os.path.join(LO, 'YEU_CAU.txt'), encoding='utf-8').read()
PROMPT = boi + '\n\n' + yc + '\n\nGhi ket qua ra file: NOI_DUNG_AGY_A.md (trong chinh thu muc nay).'

print('  LÔ A bắt đầu', time.strftime('%H:%M:%S'), '| 9 ả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=2700)
print('  agy A xong sau %.1f s · exit=%s' % (time.time() - t0, r.returncode), flush=True)
io.open(LOG, 'w', encoding='utf-8').write((r.stdout or '') + '\n--- STDERR ---\n' + (r.stderr or '')[:3000])
try:
    j = json.loads(r.stdout)
    print('  status =', j.get('status'), '| 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 đọc được JSON:', e, ')')
if os.path.exists(RA):
    t = io.open(RA, encoding='utf-8').read()
    print('  FILE: %d byte · %d dòng | HOAN TAT: %s' % (os.path.getsize(RA), t.count('\n') + 1, 'HOAN TAT' in t.upper()))
else:
    print('  KHÔNG CÓ FILE kết quả lô A')
