# -*- coding: utf-8 -*-
"""Gọi AGY (gemini-3.8-flash-high) phân loại + trích nguyên văn + chọn ảnh cho mục QC Lộc 08/10."""
import json, os, subprocess, sys, time

DIR = r'C:\Claw 2\QC\images\_loc_0810'
AGY = r'C:\Users\admin\AppData\Local\agy\bin\agy.exe'
OUT = os.path.join(DIR, '_agy_loc_0810.md')
LOG = os.path.join(DIR, '_log_agy.txt')

prompt = open(os.path.join(DIR, 'YEU_CAU.txt'), encoding='utf-8').read()
print('bắt đầu gọi AGY', time.strftime('%H:%M:%S'), flush=True)
t0 = time.time()
r = subprocess.run([AGY, '-p', prompt, '--model', 'gemini-3.8-flash-high', '--add-dir', DIR,
                    '--dangerously-skip-permissions', '--output-format', 'json'],
                   capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=2400)
giay = time.time() - t0
ra = (r.stdout or '') + '\n--- STDERR ---\n' + (r.stderr or '')
open(LOG, 'w', encoding='utf-8').write(ra)
print('AGY xong sau %.1f giây (exit %s)' % (giay, r.returncode), flush=True)

try:
    j = json.loads((r.stdout or '').strip())
    print('status:', j.get('status'), '| model:', j.get('model'), flush=True)
    u = j.get('usage') or {}
    print('token:', u.get('input_tokens') or u.get('prompt_tokens'), '/', u.get('output_tokens') or u.get('completion_tokens'), flush=True)
    if j.get('response'):
        print('response (200 ký tự đầu):', str(j['response'])[:200].replace('\n', ' '), flush=True)
except Exception as e:
    print('không parse được JSON:', e, '| 300 ký tự đầu:', (r.stdout or '')[:300], flush=True)

# verify file
if os.path.exists(OUT):
    s = open(OUT, encoding='utf-8').read()
    print('FILE:', OUT, os.path.getsize(OUT), 'byte /', s.count('\n') + 1, 'dòng', flush=True)
    print('  có KẾT LUẬN CHỌN ẢNH:', 'KẾT LUẬN CHỌN ẢNH' in s, flush=True)
    print('  có HOAN TAT:', 'HOAN TAT' in s, flush=True)
else:
    print('!!! CHƯA có file kết quả — coi như CHƯA xong', flush=True)
