# -*- coding: utf-8 -*-
"""Gửi câu hỏi vào ChatGPT: chèn text bằng base64 (tránh lỗi dấu nháy), rồi bấm gửi."""
import base64, json, os, subprocess, sys, time

ACT = 'browser-act'
SES = 'gptd'
TMP = os.path.expandvars(r'%LOCALAPPDATA%\Temp\csdlD')
SRC = sys.argv[1] if len(sys.argv) > 1 else os.path.join(TMP, 'cau_hoi_1.txt')


def run(args, stdin_file=None):
    cmd = [ACT, '--session', SES] + args
    if stdin_file:
        with open(stdin_file, 'rb') as f:
            p = subprocess.run(cmd, stdin=f, capture_output=True, text=True, encoding='utf-8', errors='replace')
    else:
        p = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='replace')
    return ((p.stdout or '') + (p.stderr or '')).strip()


text = open(SRC, encoding='utf-8').read()
b64 = base64.b64encode(text.encode('utf-8')).decode('ascii')
js = ("(()=>{const T=new TextDecoder().decode(Uint8Array.from(atob('%s'),c=>c.charCodeAt(0)));"
      "const e=[...document.querySelectorAll('[contenteditable=true]')].pop();"
      "if(!e)return 'KHONG THAY O SOAN';e.focus();"
      "document.execCommand('insertText',false,T);"
      "const t=(e.innerText||'').trim();"
      "return JSON.stringify({so_ky_tu:t.length, dau:t.slice(0,40)});})()" % b64)
jf = os.path.join(TMP, '_go_text.js')
open(jf, 'w', encoding='ascii').write(js)
print('gõ:', run(['eval', '--stdin'], jf))

time.sleep(2)
print('gửi:', run(['eval', "(()=>{const bs=[...document.querySelectorAll('button')].filter(b=>/send/i.test((b.getAttribute('data-testid')||'')+' '+(b.getAttribute('aria-label')||'')) && !b.disabled); if(bs.length){bs[bs.length-1].click(); return 'da bam nut gui ('+bs.length+' nut)';} return 'KHONG THAY NUT GUI';})()"]))
time.sleep(2)
print('trang:', run(['eval', "JSON.stringify({url:location.href, so_tin:document.querySelectorAll('[data-message-author-role=user]').length, dang_tra_loi:!!document.querySelector('[data-message-author-role=assistant]')})"]))
