# -*- coding: utf-8 -*-
"""验证：人员状态改动是否立即落 localStorage，并跨「关闭再打开」保留。"""
import io, os

SRC = r'D:\workbbbbbb\排班工具.html'
OUT = r'D:\workbbbbbb\build\_p1.html'

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

BODY_A = r'''
    document.querySelectorAll('#tabbar button').forEach(function (b) {
      if (String(b.textContent).indexOf('人员') >= 0 && b.getAttribute('data-tab')) b.click();
    });
    var st0 = window.__PB.state();
    var p = st0.people[0];
    out('before=' + p.n + '/' + p.status);
    document.querySelector('#peopleList [data-pid="' + p.id + '"]').click();
    var chip = document.querySelector('.inline-form[data-editor="' + p.id + '"] .chip[data-pstat="外勤"]');
    out('chipFound=' + !!chip);
    chip.click();
    out('afterClick=' + window.__PB.state().people[0].status);
    var ls = JSON.parse(localStorage.getItem('paiban_state_v1'));
    out('lsStatus=' + ls.people[0].status);
    out('saveHint=' + document.getElementById('saveHint').textContent);
'''

BODY_B = r'''
    var st = window.__PB.state();
    out('reloadStatus=' + st.people[0].n + '/' + st.people[0].status);
    out('reloadSavedAt=' + (st.savedAt || 'none'));
    var ls = JSON.parse(localStorage.getItem('paiban_state_v1') || '{}');
    out('lsStatus=' + ((ls.people || [{}])[0].status || 'none'));
'''

TMPL = r'''
<script>
(function () {
  var done = false;
  function run() {
    if (done) return;
    done = true;
    var lg = [];
    function out(s) { lg.push(s); }
    try {
      out('pbType=' + (typeof window.__PB) + ' tabbtns=' + document.querySelectorAll('#tabbar button').length);
      BODY
      out('ERRS=' + ((window.__ERRS || []).join(' ; ') || 'none'));
    } catch (e) {
      out('ERR ' + e.message + ' ERRS=' + ((window.__ERRS || []).join(' ; ') || 'none'));
    }
    var d = document.createElement('div');
    d.id = 'E2E'; d.textContent = lg.join('  ||  ');
    document.body.appendChild(d);
  }
  if (document.readyState === 'complete') run();
  else window.addEventListener('load', function () { setTimeout(run, 300); });
  setTimeout(run, 4000);
})();
</script>
'''

def build(script_body, out_path):
    html = io.open(SRC, encoding='utf-8').read()
    tpl = TMPL.replace('      BODY\n', script_body)
    end = html.rfind('</body>')
    h = html[:end] + tpl + html[end:]
    h = h.replace('<script>window.__PAIBAN_DATA__', ERRTRAP + '<script>window.__PAIBAN_DATA__', 1)
    io.open(out_path, 'w', encoding='utf-8').write(h)

if __name__ == '__main__':
    which = os.environ.get('PHASE', 'A')
    build(BODY_A if which == 'A' else BODY_B, OUT)
    print('phase=' + which)
