# -*- coding: utf-8 -*-
r"""B168: tải file DOCX trong hội thoại Lộc QC (KIỂM TRA CHỈ TIÊU MÀU SẮC SAU KHI TÁI CHẾ MÀU TVT WHITE 131 026.docx)."""
import io, os, shutil, subprocess, time

S = 'qcloc1410'
RA = r'C:\Claw 2\QC\_qc_loc1410'
DICH = os.path.join(RA, 'KIEM_TRA_MAU_SAU_TAI_CHE_TVT_WHITE_1410.docx')
DL = os.path.join(os.environ.get('USERPROFILE', r'C:\Users\admin'), 'Downloads')


def chay(args, inp=None, t=240):
    try:
        r = subprocess.run(['browser-act'] + args, input=inp, capture_output=True, text=True,
                           encoding='utf-8', errors='replace', timeout=t)
        return ((r.stdout or '') + (r.stderr or '')).strip()
    except Exception as e:
        return 'LOI: %s' % e


def ev(js, t=240):
    return chay(['--session', S, 'eval', '--stdin'], inp=js, t=t)


truoc = set(os.listdir(DL))
print('  tải về hiện có %d tệp' % len(truoc))
# danh sách card file trong hội thoại
print('  card file:', ev("""(()=>{const ds=[...document.querySelectorAll('.file-message__container, .file-message')];
 return JSON.stringify({so:ds.length, ten:ds.slice(0,5).map(e=>(e.innerText||'').replace(/\\s+/g,' ').slice(0,60))});})()""")[-300:])

# hover + bấm nút tải của card ĐẦU TIÊN (file mới nhất nằm dưới cùng -> lấy card cuối cùng có chữ KIỂM TRA)
for lan in range(3):
    r = ev("""(()=>{const ds=[...document.querySelectorAll('.file-message__container, .file-message')];
      const t=[...ds].reverse().find(e=>/KI[EỂ]M TRA/i.test(e.innerText||'')) || ds[ds.length-1];
      if(!t) return 'KHONG THAY CARD';
      t.dispatchEvent(new MouseEvent('mouseover',{bubbles:true}));
      const a=t.querySelector('a.file-message__actions.download, .file-message__actions a, a[download]');
      if(!a) return 'KHONG THAY NUT TAI';
      a.click(); return 'da bam tai: ' + (t.innerText||'').replace(/\\s+/g,' ').slice(0,50);})()""", t=120)
    print('  lần %d: %s' % (lan + 1, r[-90:]))
    time.sleep(6)
    moi = [f for f in os.listdir(DL) if f not in truoc]
    if moi:
        break

moi = [f for f in os.listdir(DL) if f not in truoc]
print('  tệp mới trong Downloads:', moi)
if moi:
    nguon = os.path.join(DL, max((os.path.join(DL, f) for f in moi), key=os.path.getmtime))
    with io.open(nguon, 'rb') as f:
        dau = f.read(4)
    print('  4 byte đầu:', dau, '(PK.. = docx ok)')
    if dau[:2] == b'PK':
        shutil.move(nguon, DICH)
        print('  đã lưu:', DICH, os.path.getsize(DICH), 'byte')
    else:
        print('  KHÔNG phải docx — để nguyên tệp tải về:', nguon)
else:
    print('  KHÔNG tải được tệp nào')
