# -*- coding: utf-8 -*-
"""Chờ ChatGPT trả lời xong rồi lưu HTML + Markdown câu trả lời cuối."""
import json, os, re, subprocess, sys, time

ACT = 'browser-act'
SES = 'gptd'
TMP = os.path.expandvars(r'%LOCALAPPDATA%\Temp\csdlD')
TEN = sys.argv[1] if len(sys.argv) > 1 else 'cau_hoi_1'
CHO_TOI = int(sys.argv[2]) if len(sys.argv) > 2 else 900


def ev(expr):
    p = subprocess.run([ACT, '--session', SES, 'eval', expr], capture_output=True, text=True,
                       encoding='utf-8', errors='replace')
    return ((p.stdout or '') + (p.stderr or '')).strip()


def html_md(h):
    h = re.sub(r'<br\s*/?>', '\n', h)
    h = re.sub(r'</(p|div|li|tr|h[1-6])>', '\n', h)
    h = re.sub(r'<li[^>]*>', '- ', h)
    h = re.sub(r'</t[dh]>', ' | ', h)
    h = re.sub(r'<h([1-6])[^>]*>', lambda m: '\n' + '#' * int(m.group(1)) + ' ', h)
    h = re.sub(r'</?table[^>]*>', '\n', h)
    h = re.sub(r'</?tr[^>]*>', '\n', h)
    h = re.sub(r'</?(thead|tbody)[^>]*>', '', h)
    h = re.sub(r'<(strong|b)[^>]*>(.*?)</\1>', r'**\2**', h, flags=re.S)
    h = re.sub(r'<(em|i)[^>]*>(.*?)</\1>', r'*\2*', h, flags=re.S)
    h = re.sub(r'<code[^>]*>(.*?)</code>', r'`\1`', h, flags=re.S)
    h = re.sub(r'<[^>]+>', '', h)
    h = (h.replace('&nbsp;', ' ').replace('&amp;', '&').replace('&lt;', '<').replace('&gt;', '>')
          .replace('&quot;', '"').replace('&#39;', "'"))
    h = re.sub(r'[ \t]{2,}', ' ', h)
    h = re.sub(r'\n{3,}', '\n\n', h)
    return h.strip()


print('chờ ChatGPT (tối đa %d giây)...' % CHO_TOI)
t0 = time.time()
truoc, on_dinh = -1, 0
while time.time() - t0 < CHO_TOI:
    time.sleep(20)
    st = ev("(()=>{const b=document.body.innerText||'';const stop=!!document.querySelector('button[data-testid=stop-button], button[aria-label*=Stop]');return JSON.stringify({len:b.length, stop:stop});})()")
    try:
        d = json.loads(st.splitlines()[-1])
    except Exception:
        print('   (bỏ qua phản hồi lạ)', st[:100])
        continue
    giay = int(time.time() - t0)
    print('   %4ds | %7d ký tự | đang chạy: %s' % (giay, d['len'], d['stop']))
    if not d['stop'] and d['len'] == truoc:
        on_dinh += 1
        if on_dinh >= 3:
            print('=> có vẻ đã xong sau %d giây' % giay)
            break
    else:
        on_dinh = 0
    truoc = d['len']

ra = ev("(()=>{const a=[...document.querySelectorAll('article')]; const el=a.length?a[a.length-1]:null; if(!el) return 'KHONG THAY BAI TRA LOI'; return JSON.stringify({html:el.innerHTML, txt:(el.innerText||'').length});})()")
try:
    d = json.loads(ra.splitlines()[-1])
except Exception:
    print('LỖI trích xuất:', ra[:400])
    sys.exit(1)
open(os.path.join(TMP, '%s.html' % TEN), 'w', encoding='utf-8').write(d['html'])
md = html_md(d['html'])
open(os.path.join(TMP, '%s.md' % TEN), 'w', encoding='utf-8').write(md)
print('\nđã lưu: %s.html (%d byte HTML) · %s.md (%d ký tự, %d dòng)'
      % (TEN, len(d['html']), TEN, len(md), md.count('\n') + 1))
print('--- 25 dòng đầu Markdown ---')
print('\n'.join(md.split('\n')[:25]))
