# -*- coding: utf-8 -*-
import io, os, subprocess, time, html as H

SRC = r"D:\workbbbbbb\排班工具.html"
OUT = r"D:\workbbbbbb\build\_a2_e2e.html"
DOM = r"D:\workbbbbbb\build\_a2_dom.html"
TXT = r"D:\workbbbbbb\build\_a2_out.txt"

ERRTRAP = '<script>window.__ERRS=[];window.addEventListener("error",function(e){window.__ERRS.push((e.message||"")+" @"+e.lineno);});</script>'

TEST = r"""
<div id="E2E">PENDING</div>
<script>
(function () {
  var out = [], done = false;
  function push(s) { out.push(s); }
  function run() {
    if (done) return; done = true;
    try {
      var pb = window.__PB;
      push('pbType=' + (pb ? 'object' : typeof pb));
      var rows = pb.peopleRows();
      push('rowsN=' + rows.length + ' colsN=' + rows[0].length);
      push('head=' + rows[0].join('|'));
      push('row2=' + rows[1].join('|'));
      var names = rows.slice(1).map(function (r) { return r[0] + ':' + r[4]; });
      push('addrList=' + names.join(' ; '));
      var st = pb.state();
      push('people=' + st.people.map(function (p) {
        return p.n + '/' + p.home + '/' + (p.district || '-') + '/' + (p.autoArea || '-') + '/' + (pAreasTxt(p));
      }).join(' ; '));
      function pAreasTxt(p) { return (p.areas || []).join(','); }
      var t2 = document.querySelector('#peopleList .row .t2');
      push('t2=' + (t2 ? t2.textContent.replace(/\s+/g, ' ').slice(0, 120) : 'none'));
      var g = pb.geo();
      push('homes=' + (g.homes || []).length);
      var kq = null;
      (g.homes || []).forEach(function (h) { if (h.n.indexOf('水韵') >= 0) kq = h; });
      push('kq=' + (kq ? (kq.a + '@' + kq.lat + ',' + kq.lng) : 'none'));
      push('distKq=' + (pb.distP2O({ home: '水韵康桥康泽苑', id: 'x' }, 'T710220000', '拱墅辖区')));
      document.querySelector('[data-tab="v-area"]').click();
      document.getElementById('btnAutoArea').click();
      push('cover=' + document.getElementById('areaCover').textContent);
      push('stat2=' + (document.getElementById('areaStat2') || {}).textContent);
      push('ERRS=' + ((window.__ERRS || []).join(' ; ') || 'none'));
    } catch (e) { push('ERR ' + e.message); }
    document.getElementById('E2E').textContent = out.join(' || ');
  }
  if (document.readyState === 'complete') run(); else window.addEventListener('load', function () { setTimeout(run, 300); });
  setTimeout(run, 4000);
})();
</script>
"""


def build():
    with io.open(SRC, encoding='utf-8') as f:
        h = f.read()
    i = h.find('<script>window.__PAIBAN_DATA__')
    h = h[:i] + ERRTRAP + h[i:]
    e = h.rfind('</body>')
    h = h[:e] + TEST + h[e:]
    with io.open(OUT, 'w', encoding='utf-8') as f:
        f.write(h)
    print('built', os.path.getsize(OUT))


def dump():
    edge = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
    if os.path.exists(DOM):
        os.remove(DOM)
    subprocess.run(['taskkill', '/F', '/IM', 'msedge.exe'], capture_output=True)
    time.sleep(2)
    prof = 'C:/Windows/Temp/e2eA%d' % (int(time.time()) % 100000)
    cmd = [edge, '--headless=new', '--disable-gpu', '--user-data-dir=' + prof,
           '--virtual-time-budget=9000', '--dump-dom', OUT]
    r = subprocess.run(cmd, capture_output=True)
    with io.open(DOM, 'wb') as f:
        f.write(r.stdout)
    print('dom', len(r.stdout))


def extract():
    with io.open(DOM, encoding='utf-8', errors='replace') as f:
        s = f.read()
    k = s.find('id="E2E"')
    if k < 0:
        txt = 'NO_E2E len=%d' % len(s)
    else:
        b = s.find('>', k) + 1
        e = s.find('</div>', b)
        txt = H.unescape(s[b:e]).strip()
    with io.open(TXT, 'w', encoding='utf-8') as f:
        f.write(txt)
    print('extracted', len(txt))


build()
dump()
extract()
