# -*- coding: utf-8 -*-
"""v2 就近版专项自测：确认数据隔离 + 生成结果按机构就近。"""
import io, os, sys, re

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
BASE = r"D:\workbbbbbb\v2"
B = os.path.join(BASE, "build")
SRC = os.environ.get("CMP_SRC") or os.path.join(BASE, r"排班工具_就近版.html")
OUT = os.environ.get("CMP_OUT") or os.path.join(B, "_v2_e2e.html")

html = io.open(SRC, encoding="utf-8").read()

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

TEST = r'''<script>
(function () {
  var done = false;
  function out(t) {
    var d = document.getElementById('E2E');
    if (!d) { d = document.createElement('div'); d.id = 'E2E'; document.body.appendChild(d); }
    d.appendChild(document.createTextNode(t + ' || '));
  }
  function run() {
    if (done) return; done = true;
    try {
      var PB = window.__PB;
      out('v2bar=' + !!document.querySelector('.v2bar'));
      out('barText=' + (document.querySelector('.v2bar') || {}).textContent);
      var lsKeys = [];
      try { for (var i = 0; i < localStorage.length; i++) lsKeys.push(localStorage.key(i)); } catch (e) { }
      out('lsKeys=' + lsKeys.join(','));
      out('hasV1Key=' + (lsKeys.indexOf('paiban_state_v1') >= 0));
      out('hasV2Key=' + (lsKeys.indexOf('paiban2_near_state_v1') >= 0));
      var st = PB.state();
      out('people=' + st.people.length);
      /* 加一条拱宸桥支行的安排（周一全天 1 人） */
      var inp = document.getElementById('orgInput');
      /* 只加一条：笕桥支行（v1：城东辖区认领人优先；v2：谁近谁上） */
      inp.value = '笕桥';
      inp.dispatchEvent(new Event('input', { bubbles: true }));
      var sug2 = document.querySelector('#orgSug div[data-i]');
      out('sug2=' + (sug2 ? sug2.textContent.replace(/\s+/g, ' ') : 'none'));
      if (sug2) sug2.click();
      document.getElementById('btnAddPlan').click();
      out('plans=' + window.__PB.state().plans.length);
      var rk = PB.rankFor('T710150000', '城东辖区', 0);
      out('rank=' + rk.map(function (c) { return c.n + '(' + c.d + 'km' + (c.same ? ',本辖区' : '') + ')'; }).join(' > '));
      out('rankMinFirst=' + (rk.length > 1 ? (rk[0].d <= rk[1].d) : true));
      document.getElementById('btnGen').click();
      var r = PB.state().lastResult;
      out('rows=' + (r.rows || []).length);
      (r.rows || []).forEach(function (x) {
        out('ROW ' + x.area + '/' + x.org + ' members=' + x.members.join('、')
          + ' roles=' + (x.roles || []).join('、') + ' d=' + (x.dists || []).join('、')
          + ' m=' + (x.mins || []).join('、'));
      });
      out('flexTag=' + document.querySelectorAll('.tag').length);
      out('ERRS=' + ((window.__ERRS || []).join(' ; ') || 'none'));
    } catch (e) {
      out('ERR ' + e.message);
      out('ERRS=' + ((window.__ERRS || []).join(' ; ') || 'none'));
    }
  }
  if (document.readyState === 'complete') setTimeout(run, 400);
  else window.addEventListener('load', function () { setTimeout(run, 400); });
  setTimeout(run, 4000);
})();
</script>'''

i = html.find('<script>window.__PAIBAN_DATA__')
html = html[:i] + ERRTRAP + html[i:]
j = html.rfind('</body>')
html = html[:j] + TEST + html[j:]
io.open(OUT, 'w', encoding='utf-8').write(html)
print('out=' + OUT)
