# -*- coding: utf-8 -*-
"""注入端到端自测脚本，生成 build/_e2e.html"""
import io, sys, os
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
BASE = r"D:\workbbbbbb"
src = os.path.join(BASE, "排班工具.html")
dst = os.path.join(BASE, "build", "_e2e.html")

E2E = r"""
<script>
setTimeout(function () {
  var log = [];
  function out(s) { log.push(s); }
  try {
    // 1. 搜索机构
    var oi = document.getElementById('orgInput');
    oi.value = '笕桥';
    oi.dispatchEvent(new Event('input'));
    var sug = document.getElementById('orgSug');
    out('orgsLen=' + (window.__PAIBAN_DATA__ ? window.__PAIBAN_DATA__.orgs.length : 'noDATA'));
    out('manualHit=' + (window.__PAIBAN_DATA__.orgs.filter(function (o) { return o.n.indexOf('笕桥') >= 0; }).length));
    out('sugCount=' + sug.children.length);
    out('sugHTML=' + String(sug.innerHTML || '').slice(0, 100));
    out('ioVal=' + document.getElementById('orgInput').value);
    out('dbgSearch=' + (window.__PB ? window.__PB.search('笕桥').length : 'noPB'));
    out('dbgStateOrgs=' + (window.__PB ? window.__PB.state().orgs.length : 'noPB'));
    window.__PB && window.__PB.sug('笕桥');
    out('sugCountAfterDirect=' + document.getElementById('orgSug').children.length);
    sug.children[0].click();
    out('picked=' + document.getElementById('pickedName').textContent);

    // 2. 选周二周三 + 人数 2
    document.querySelector('#dayChips .chip[data-day="1"]').click();
    document.querySelector('#dayChips .chip[data-day="2"]').click();
    document.querySelector('#needChips .chip[data-need="2"]').click();
    document.getElementById('btnAddPlan').click();
    out('plans=' + document.getElementById('planCount').textContent);

    // 3. 加一条下沙安排（不同辖区，验证跨辖区）
    oi.value = '下沙';
    oi.dispatchEvent(new Event('input'));
    var s2 = document.getElementById('orgSug');
    out('sug2=' + s2.children.length);
    s2.children[0].click();
    document.querySelector('#slotChips .chip[data-slot="am"]').click();
    document.querySelector('#needChips .chip[data-need="1"]').click();
    document.getElementById('btnAddPlan').click();
    out('plans2=' + document.getElementById('planCount').textContent);

    // 4. 生成
    document.getElementById('btnGen').click();
    var tw = document.getElementById('resultWrap');
    var tabs = tw.querySelectorAll('table.tbl');
    out('tblCount=' + tabs.length);
    var pr = (tabs.length ? tabs[tabs.length - 1] : tw).querySelectorAll('tbody tr');
    out('resultRows=' + pr.length);
    var names = [];
    pr.forEach(function (r) {
      var td = r.querySelectorAll('td');
      var g = function (i) { return td[i] ? String(td[i].textContent).trim() : '-'; };
      names.push(g(0) + '/' + g(1) + '/' + g(2) + '=>' + g(4));
    });
    out('DETAIL:' + names.join(' | '));

    // 5. 请假人员不得出现
    out('hasLeaveGuy=' + (tw.textContent.indexOf('郑文斌') >= 0));

    // 6. 切换 tab
    document.querySelector('#tabbar button[data-tab="v-people"]').click();
    out('tab=' + document.getElementById('pageTitle').textContent);
    var pl = document.getElementById('peopleList').children.length;
    out('peopleRows=' + pl);

    // 7. 导出表格数据
    var t = document.getElementById('resultWrap');
    out('btns=' + document.querySelectorAll('#resultWrap button[data-act]').length);

    // 8. 记忆功能
    out('saveHint=' + document.getElementById('saveHint').textContent);
    out('savedAt=' + (window.__PB ? (window.__PB.state().savedAt || 'none') : 'noPB'));
    out('histWeeks=' + (window.__PB ? window.__PB.history().length : 'noPB'));
    var hw = document.getElementById('historyWrap');
    out('histHTML=' + (hw ? String(hw.textContent).replace(/\s+/g, ' ').slice(0, 140) : 'none'));
    out('histHasScore=' + (hw && hw.textContent.indexOf('次') >= 0));
    document.querySelector('#tabbar button[data-tab="v-set"]').click();
    var wsi = document.getElementById('weekStartInput');
    wsi.value = '2026-11-09';
    wsi.dispatchEvent(new Event('change'));
    out('week2=' + document.getElementById('weekLabel').textContent.replace(/\s+/g, ' '));
    document.querySelector('#tabbar button[data-tab="v-plan"]').click();
    document.getElementById('btnGen').click();
    out('histWeeks2=' + window.__PB.history().length);
    out('histFirst=' + (window.__PB.history()[0] || {}).weekStart);
    out('histScoreLine=' + (document.getElementById('historyWrap').textContent.indexOf('累计') >= 0));
    out('histRows2=' + document.querySelectorAll('#historyWrap details').length);
    out('diskBtns=' + document.querySelectorAll('#btnPickDisk,#btnWriteDisk,#btnUnlinkDisk,#btnSaveHtml').length);
    out('diskState=' + document.getElementById('diskState').textContent);
    out('diskSupport=' + (!!window.showSaveFilePicker));
    out('diskHintLen=' + document.getElementById('diskHint').textContent.length);
    out('saveAsHtmlFn=' + (typeof window.__PB.saveAsHtml));
    try { window.__PB.saveAsHtml(); } catch (e) { out('saveAsHtmlERR ' + e.message); }
    setTimeout(function () {
      var l2 = [];
      var t2 = window.__SAVED_HTML;
      if (!t2) { l2.push('SAVED=null'); }
      else if (String(t2).indexOf('FETCHERR') === 0) { l2.push(t2.slice(0, 160)); }
      else {
        l2.push('SAVEDlen=' + t2.length);
        l2.push('SAVEDhasInject=' + (t2.indexOf('localStorage.setItem') >= 0));
        l2.push('SAVEDhasData=' + (t2.indexOf('__PAIBAN_DATA__') >= 0));
        var ip = t2.indexOf('localStorage.setItem'), dp = t2.indexOf('__PAIBAN_DATA__');
        l2.push('injectOrder=' + (ip >= 0 && dp >= 0 && ip < dp ? 'before' : 'after'));
        var doc = new DOMParser().parseFromString(t2, 'text/html');
        l2.push('parsedH1=' + (doc.querySelector('h1') ? doc.querySelector('h1').textContent : 'noH1'));
        l2.push('parsedTabs=' + doc.querySelectorAll('#tabbar button').length);
        l2.push('parsedScripts=' + doc.querySelectorAll('script').length);
      }
      var d2 = document.createElement('div');
      d2.id = 'E2E2';
      d2.textContent = l2.join('  ||  ');
      document.body.appendChild(d2);
    }, 2500);
  } catch (e) {
    out('ERR ' + e.message + ' @@ ' + (e.stack || '').slice(0, 300));
  }
  out('ERRS=' + ((window.__ERRS || []).join(' ; ') || 'none'));
  var d = document.createElement('div');
  d.id = 'E2E';
  d.textContent = log.join('  ||  ');
  document.body.appendChild(d);
}, 400);
</script>
"""

with open(src, "r", encoding="utf-8") as f:
    html = f.read()
if "</body>" not in html:
    raise SystemExit("no </body>")
ERRTRAP = ('<script>window.__ERRS=[];window.addEventListener("error",function(e){'
           'window.__ERRS.push((e.message||"")+" @line"+e.lineno);});</script>')
SAVEHOOK = r"""<script>
window.__SAVED_HTML = null;
(function () {
  var orig = HTMLAnchorElement.prototype.click;
  HTMLAnchorElement.prototype.click = function () {
    var a = this;
    try {
      if (a.download && /\.html$/i.test(a.download)) {
        fetch(a.href).then(function (r) { return r.text(); })
          .then(function (t) { window.__SAVED_HTML = t; })
          .catch(function (e) { window.__SAVED_HTML = 'FETCHERR ' + e.message; });
        return;
      }
    } catch (e) {}
    return orig.apply(this, arguments);
  };
})();
</script>"""
html = html.replace('<script>window.__PAIBAN_DATA__', SAVEHOOK + ERRTRAP + '<script>window.__PAIBAN_DATA__', 1)
_end = html.rfind("</body>")
if _end < 0:
    raise SystemExit("no </body>")
html = html[:_end] + E2E + html[_end:]
with open(dst, "w", encoding="utf-8") as f:
    f.write(html)
print("wrote", dst, os.path.getsize(dst))
