# -*- coding: utf-8 -*-
r"""B70: kiểm chứng AGY T41 — (1) log status; (2) file mới; (3) KHÔNG file cũ nào bị sửa (so với backup)."""
import glob, hashlib, json, os, shutil, subprocess

D = r'C:\Claw 2\Bao cao - Hanh chinh\Bao cao lam mau'
SACH = os.path.join(D, 'da lam sach')
BAK = os.path.join(D, 'da lam sach_BACKUP_20261012_1855')

print('  === 1. log agy ===')
s = open(os.path.join(D, '_log_agy_T41.txt'), encoding='utf-8', errors='replace').read()
i, j = s.find('{'), s.rfind('}')
try:
    d = json.loads(s[i:j + 1])
    print('   status=%s | giây=%.0f | token=%s' % (d.get('status'), d.get('duration_seconds', 0), (d.get('usage') or {}).get('total_tokens')))
    r = (d.get('response') or '')
    if 'blocked' in r or 'error' in r.lower():
        print('   ⚠ response:', r[:300])
    else:
        print('   response (200 ký tự đầu):', r[:200].replace('\n', ' '))
except Exception as e:
    print('   lỗi parse:', str(e)[:80], '| cuối log:', s[-200:])

print()
print('  === 2. file mới trong "da lam sach" (so với backup) ===')
cu = {f: (os.path.getsize(os.path.join(BAK, f)), hashlib.md5(open(os.path.join(BAK, f), 'rb').read()).hexdigest())
      for f in os.listdir(BAK)}
moi, sua = [], []
for f in os.listdir(SACH):
    p = os.path.join(SACH, f)
    if not os.path.isfile(p):
        continue
    h = hashlib.md5(open(p, 'rb').read()).hexdigest()
    if f not in cu:
        moi.append((f, os.path.getsize(p)))
    elif cu[f][1] != h:
        sua.append((f, cu[f][0], os.path.getsize(p)))
print('   FILE MỚI (%d):' % len(moi))
for f, sz in sorted(moi):
    print('      %-46s %8d B' % (f, sz))
print('   FILE CŨ BỊ SỬA: %s' % ('KHÔNG ✓' if not sua else sua))
print('   tổng file trong backup: %d | hiện tại: %d' % (len(cu), len([f for f in os.listdir(SACH) if os.path.isfile(os.path.join(SACH, f))])))

print()
print('  === 3. script clean_and_merge_tuan41.py + báo cáo md ===')
for p in (os.path.join(D, 'clean_and_merge_tuan41.py'), os.path.join(SACH, 'Bao_cao_lam_sach_Tuan41.md')):
    if os.path.exists(p):
        print('   %-40s %8d B' % (os.path.basename(p), os.path.getsize(p)))
    else:
        print('   %-40s CHƯA CÓ' % os.path.basename(p))
