import json, re

with open('dashboard_data.json', encoding='utf-8') as f:
    data = json.load(f)

with open('dashboard2.html', encoding='utf-8') as f:
    html = f.read()

# 1. Re-inject data
html = re.sub(
    r'const RAW = \{.*?\};',
    'const RAW = ' + json.dumps(data, ensure_ascii=False, default=str) + ';',
    html, flags=re.DOTALL
)

# 2. Backlog HTML section
backlog_html = (
'\n<!-- \u2500\u2500 PIPELINE BACKLOG \u2500\u2500 -->\n'
'<div class="card p-5 mb-6">\n'
'  <div class="flex items-start justify-between mb-5">\n'
'    <div>\n'
'      <p class="section-title">T\u1ed3n \u0111\u1ecdng theo c\u00f4ng \u0111o\u1ea1n \u2014 T\u1ea5t c\u1ea3 c\u00e1c ng\u00e0y</p>\n'
'      <p class="section-sub">S\u1ed1 controls \u0111\u00e3 v\u00e0o c\u00f4ng \u0111o\u1ea1n tr\u01b0\u1edbc nh\u01b0ng ch\u01b0a ho\u00e0n th\u00e0nh c\u00f4ng \u0111o\u1ea1n hi\u1ec7n t\u1ea1i</p>\n'
'    </div>\n'
'    <div id="backlogTotal" class="text-right"></div>\n'
'  </div>\n'
'  <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6" id="backlogCards"></div>\n'
'  <div class="space-y-4" id="backlogBars"></div>\n'
'</div>\n\n'
)

insert_before = '<!-- \u2500\u2500 CHART 1: WORKLOAD BY STAGE \u2500\u2500 -->'
if insert_before in html:
    html = html.replace(insert_before, backlog_html + insert_before)
    print('Backlog HTML inserted OK')
else:
    print('ERROR: insert marker not found')

# 3. Backlog JS
backlog_js = r"""
// -- Pipeline Backlog ----------------------------------------
function renderBacklog() {
  const b = RAW.pipeline_backlog;

  document.getElementById('backlogTotal').innerHTML =
    '<p class="text-slate-400 text-xs">T\u1ed5ng controls</p>' +
    '<p class="text-2xl font-bold text-white">' + b.received.toLocaleString() + '</p>' +
    '<p class="text-emerald-400 text-xs mt-0.5">' + b.pct_stock + '% \u0111\u00e3 v\u00e0o kho</p>';

  const stages = [
    { label:'Receiving',     done:b.received,   pending:null,          pct:100,        color:'#3b82f6', note:'C\u01a1 s\u1edf t\u00ednh to\u00e1n' },
    { label:'QC In',         done:b.qc_done,    pending:b.pending_qc,  pct:b.pct_qc,   color:'#10b981' },
    { label:'Packaging In',  done:b.pack_done,  pending:b.pending_pack,pct:b.pct_pack, color:'#8b5cf6' },
    { label:'Stock In',      done:b.stock_done, pending:b.pending_stock,pct:b.pct_stock,color:'#f59e0b' },
  ];

  function pendingColor(n) {
    if (n === null) return '#64748b';
    return n > 100 ? '#ef4444' : n > 30 ? '#f59e0b' : '#10b981';
  }

  // KPI cards
  document.getElementById('backlogCards').innerHTML = stages.map(s => {
    const pc = pendingColor(s.pending);
    const pendLine = s.pending === null
      ? '<p class="text-slate-500 text-xs mt-1">Kh\u00f4ng \u0111o \u0111\u01b0\u1ee3c</p>'
      : s.pending === 0
        ? '<p class="text-emerald-400 text-xs mt-1 font-semibold">Kh\u00f4ng t\u1ed3n \u0111\u1ecdng</p>'
        : '<p class="text-xs mt-1 font-semibold" style="color:'+pc+'">'+s.pending+' \u0111ang ch\u1edd</p>';
    return '<div class="rounded-xl p-4" style="background:#1e293b;border:1px solid #334155;border-left:3px solid '+s.color+'">'
      + '<p class="text-xs text-slate-400 uppercase tracking-wide mb-2">'+s.label+'</p>'
      + '<p class="text-2xl font-bold" style="color:'+s.color+'">'+s.done.toLocaleString()+'</p>'
      + '<p class="text-slate-500 text-xs">controls xong</p>'
      + pendLine
      + '</div>';
  }).join('');

  // Progress bars (skip Receive)
  document.getElementById('backlogBars').innerHTML = stages.slice(1).map(s => {
    const donePct = s.pct;
    const pendPct = Math.max(0, 100 - donePct);
    const pc = pendingColor(s.pending);
    return '<div>'
      + '<div class="flex justify-between items-center mb-1.5">'
      + '<span class="text-sm font-semibold" style="color:'+s.color+'">'+s.label+'</span>'
      + '<span class="text-xs text-slate-400">'
      + s.done.toLocaleString() + ' / ' + b.received.toLocaleString() + ' controls'
      + (s.pending > 0
          ? ' &nbsp;&middot;&nbsp; <span style="color:'+pc+';font-weight:600">'+s.pending+' \u0111ang ch\u1edd</span>'
          : ' &nbsp;&middot;&nbsp; <span class="text-emerald-400 font-semibold">Kh\u00f4ng t\u1ed3n</span>')
      + '</span>'
      + '</div>'
      + '<div class="flex h-6 bg-slate-700 rounded-full overflow-hidden">'
      + '<div style="width:'+donePct+'%;background:'+s.color+';transition:width .6s ease" class="h-full flex items-center justify-end pr-2">'
      + (donePct > 15 ? '<span class="text-white text-xs font-bold">'+donePct+'%</span>' : '')
      + '</div>'
      + (pendPct > 0
          ? '<div style="width:'+pendPct+'%;background:'+pc+'33;border-left:2px dashed '+pc+'" class="h-full flex items-center pl-1.5">'
            + (pendPct > 5 ? '<span class="text-xs font-semibold" style="color:'+pc+'">'+pendPct.toFixed(1)+'%</span>' : '')
            + '</div>'
          : '')
      + '</div>'
      + '</div>';
  }).join('');
}

"""

render_all_marker = '// -- Render all'
if render_all_marker not in html:
    # try unicode dashes
    render_all_marker = '// \u2500\u2500 Render all \u2500\u2500'
html = html.replace(render_all_marker, backlog_js + render_all_marker, 1)

# 4. Call renderBacklog in renderAll
html = html.replace(
    'function renderAll() {\n  renderKPI();',
    'function renderAll() {\n  renderKPI();\n  renderBacklog();'
)

with open('dashboard2.html', 'w', encoding='utf-8') as f:
    f.write(html)
print('Done, size:', len(html)//1024, 'KB')
