# -*- coding: utf-8 -*-
"""Gọi AGY đọc lại 3 ô đối chứng (gemini-3.1-pro-high)."""
import json, os, subprocess, time

DIR = r'C:\Claw 2\Nghien cuu\Du-an-B-He-mau-Stain-Glaze\metal-complex-08-10'
AGY = r'C:\Users\admin\AppData\Local\agy\bin\agy.exe'
OUT = os.path.join(DIR, 'doc-lai-doi-chung', 'DOI_CHUNG_LAI.md')
prompt = ('Đọc file hướng dẫn "doc-lai-doi-chung\\YEU_CAU.txt" (UTF-8, tiếng Việt) trong thư mục làm việc và làm đúng theo đó. '
          'Phải TỰ NHÌN 3 ảnh anh_o\\t4_o07.png, anh_o\\t4_o08.png, anh_o\\t4_o09.png và GHI FILE THẬT ra '
          'doc-lai-doi-chung\\DOI_CHUNG_LAI.md, ghi dần từng mục, kết thúc bằng HOAN TAT.')
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.1-pro-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
open(os.path.join(DIR, 'doc-lai-doi-chung', '_log_agy.txt'), 'w', encoding='utf-8').write((r.stdout or '') + '\n--- STDERR ---\n' + (r.stderr or ''))
print('AGY xong sau %.1f giây (exit %s)' % (giay, r.returncode), flush=True)
try:
    j = json.loads((r.stdout or '').strip())
    u = j.get('usage') or {}
    print('status:', j.get('status'), '| token:', u.get('input_tokens') or u.get('prompt_tokens'), '/', u.get('output_tokens') or u.get('completion_tokens'), flush=True)
    if j.get('error'):
        print('error:', str(j['error'])[:200], flush=True)
except Exception as e:
    print('không parse JSON:', e, (r.stdout or '')[:200], flush=True)
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 | có HOAN TAT:', 'HOAN TAT' in s, flush=True)
    print(s[:3000], flush=True)
else:
    print('!!! CHƯA có file kết quả', flush=True)
