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. Replace chart 7 HTML section
old_html = '<!-- \u2500\u2500 CHART 7: RECEIVE TIME DISTRIBUTION \u2500\u2500 -->\n<div class="card p-5 mb-6">\n  <div class="flex flex-wrap items-start justify-between gap-2 mb-4">\n    <div>\n      <p class="section-title">\u2462 Ph\u00e2n ph\u1ed1i th\u1eddi gian nh\u1eadn h\u00e0ng (Receiving ID)</p>\n      <p class="section-sub">M\u1ed7i c\u1ed9t = s\u1ed1 chuy\u1ebfn giao h\u00e0ng (Receiving ID) trong khung gi\u1edd \u0111\u00f3 \u00b7 Gi\u00fap x\u00e1c \u0111\u1ecbnh NCC giao h\u00e0ng ch\u1ee7 y\u1ebfu v\u00e0o gi\u1edd n\u00e0o</p>\n    </div>\n    <div class="flex gap-2 items-center">\n      <span class="text-slate-400 text-sm">Xem theo:</span>\n      <select id="receiveTimeMode" onchange="renderChart7()" class="">\n        <option value="all">T\u1ea5t c\u1ea3 ng\u00e0y</option>\n        <option value="bydate">T\u1eebng ng\u00e0y</option>\n      </select>\n    </div>\n  </div>\n  <div class="grid grid-cols-4 gap-3 mb-5" id="zoneCards"></div>\n  <div style="height:280px"><canvas id="chart7"></canvas></div>\n</div>'

new_html = '''<!-- \u2500\u2500 CHART 7: RECEIVE TIME DISTRIBUTION \u2500\u2500 -->
<div class="card p-5 mb-6">
  <div class="flex flex-wrap items-start justify-between gap-3 mb-4">
    <div>
      <p class="section-title">\u2462 Ph\u00e2n ph\u1ed1i th\u1eddi gian nh\u1eadn h\u00e0ng (Receiving ID)</p>
      <p class="section-sub">M\u1ed7i c\u1ed9t = s\u1ed1 chuy\u1ebfn giao h\u00e0ng trong khung gi\u1edd \u00b7 Xem theo ng\u00e0y / th\u00e1ng / n\u0103m</p>
    </div>
    <div class="flex flex-wrap gap-2 items-center">
      <div class="flex rounded-lg overflow-hidden border border-slate-600">
        <button id="btnDay"   onclick="setRTMode(\'day\')"   class="rt-mode-btn px-3 py-1.5 text-sm bg-blue-600 text-white">Ng\u00e0y</button>
        <button id="btnMonth" onclick="setRTMode(\'month\')" class="rt-mode-btn px-3 py-1.5 text-sm bg-slate-700 text-slate-300">Th\u00e1ng</button>
        <button id="btnYear"  onclick="setRTMode(\'year\')"  class="rt-mode-btn px-3 py-1.5 text-sm bg-slate-700 text-slate-300">N\u0103m</button>
      </div>
      <select id="rtPeriodSelect" onchange="renderChart7()" class="min-w-[130px]"></select>
    </div>
  </div>
  <div class="grid grid-cols-4 gap-3 mb-5" id="zoneCards"></div>
  <div style="height:260px"><canvas id="chart7"></canvas></div>
</div>'''

if old_html in html:
    html = html.replace(old_html, new_html)
    print('Chart7 HTML replaced OK')
else:
    # try finding by partial match
    marker = 'id="receiveTimeMode"'
    if marker in html:
        print('Found by marker, doing targeted replace')
        start = html.rfind('<!-- \u2500\u2500 CHART 7:', 0, html.find(marker))
        end = html.find('</div>', html.find('id="chart7"')) + 6
        html = html[:start] + new_html + html[end:]
        print('Done via targeted replace')
    else:
        print('ERROR: chart7 HTML section not found')

# 3. Replace chart7 JS block
old_js_start = '// \u2500\u2500 Chart 7: Receive Time Distribution \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500'
old_js_end   = '\n// \u2500\u2500 Render all \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500'
si = html.find(old_js_start)
ei = html.find(old_js_end)
print(f'JS block: si={si}, ei={ei}')

new_js = '''// \u2500\u2500 Chart 7: Receive Time Distribution \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
let chart7Inst = null;
let rtMode = 'day';

const ZONE_CFG = [
  { key:'morning',   label:'S\u00e1ng (8-11h)',   color:'#3b82f6' },
  { key:'midday',    label:'Tr\u01b0a (11-14h)',  color:'#10b981' },
  { key:'afternoon', label:'Chi\u1ec1u (14-17h)', color:'#f59e0b' },
  { key:'evening',   label:'T\u1ed1i (17h+)',     color:'#ef4444' },
];

function setRTMode(mode) {
  rtMode = mode;
  ['Day','Month','Year'].forEach(m => {
    const b = document.getElementById('btn'+m);
    if (b) b.className = 'rt-mode-btn px-3 py-1.5 text-sm ' +
      (mode === m.toLowerCase() ? 'bg-blue-600 text-white' : 'bg-slate-700 text-slate-300');
  });
  buildRTPeriodOptions();
  renderChart7();
}

function buildRTPeriodOptions() {
  const sel = document.getElementById('rtPeriodSelect');
  const distKey = rtMode === 'day' ? 'by_day' : rtMode === 'month' ? 'by_month' : 'by_year';
  const keys = Object.keys(RAW.receive_time_dist[distKey]).sort().reverse();
  sel.innerHTML = keys.map(k => {
    let label = k;
    if (rtMode === 'day') {
      const [y,m,d] = k.split('-');
      label = d+'/'+m+'/'+y;
    } else if (rtMode === 'month') {
      const [y,m] = k.split('-');
      label = 'Th\u00e1ng '+m+'/'+y;
    } else {
      label = 'N\u0103m '+k;
    }
    return '<option value="'+k+'">'+label+'</option>';
  }).join('');
}

function renderZoneCards(zones, total) {
  const container = document.getElementById('zoneCards');
  container.innerHTML = ZONE_CFG.map(z => {
    const cnt = zones[z.key] || 0;
    const pct = total ? Math.round(cnt / total * 100) : 0;
    const warn = z.key === 'evening' && cnt > 0;
    return '<div class="rounded-xl p-4 border border-slate-700" style="background:'+z.color+'18">'+
      '<p class="text-xs mb-1" style="color:'+z.color+'">'+z.label+'</p>'+
      '<p class="text-2xl font-bold" style="color:'+z.color+'">'+cnt+'</p>'+
      '<p class="text-xs mt-1 '+(warn?'font-semibold':'text-slate-500')+'" style="'+(warn?'color:#f87171':'')+'">'+
      pct+'% t\u1ed5ng chuy\u1ebfn'+(warn?' \u26a0\ufe0f':'')+
      '</p></div>';
  }).join('');
}

function renderChart7() {
  const distKey = rtMode === 'day' ? 'by_day' : rtMode === 'month' ? 'by_month' : 'by_year';
  const period  = document.getElementById('rtPeriodSelect').value;
  const entry   = RAW.receive_time_dist[distKey]?.[period];
  if (!entry) return;

  renderZoneCards(entry.zones, entry.total);

  const hours    = Array.from({length:12}, (_,i) => (i+8)+':00');
  const hourKeys = Array.from({length:12}, (_,i) => String(i+8));

  function barColor(h) {
    const hi = parseInt(h);
    if (hi >= 17) return 'rgba(239,68,68,0.82)';
    if (hi >= 14) return 'rgba(245,158,11,0.82)';
    if (hi >= 11) return 'rgba(16,185,129,0.82)';
    return 'rgba(59,130,246,0.82)';
  }

  const counts = hourKeys.map(h => entry.hours[h] || 0);

  if (chart7Inst) { chart7Inst.destroy(); chart7Inst = null; }
  chart7Inst = new Chart(document.getElementById('chart7').getContext('2d'), {
    type: 'bar',
    data: {
      labels: hours,
      datasets: [{
        label: 'S\u1ed1 chuy\u1ebfn',
        data: counts,
        backgroundColor: hourKeys.map(h => barColor(h)),
        borderRadius: 6,
        borderWidth: 0,
      }]
    },
    options: {
      responsive: true, maintainAspectRatio: false,
      plugins: { legend: { display: false } },
      scales: {
        x: { grid: { color: 'rgba(148,163,184,0.07)' } },
        y: { grid: { color: 'rgba(148,163,184,0.07)' }, beginAtZero: true, ticks: { stepSize: 1 } }
      }
    },
    plugins: [{
      id: 'eveningZone',
      afterDraw(chart) {
        const {ctx, chartArea, scales} = chart;
        if (!chartArea || !scales.x) return;
        const barW = (chartArea.right - chartArea.left) / 12;
        const x17 = chartArea.left + barW * 9;
        ctx.save();
        ctx.fillStyle = 'rgba(239,68,68,0.06)';
        ctx.fillRect(x17, chartArea.top, chartArea.right - x17, chartArea.bottom - chartArea.top);
        ctx.setLineDash([4,3]);
        ctx.strokeStyle = 'rgba(239,68,68,0.5)';
        ctx.lineWidth = 1.5;
        ctx.beginPath(); ctx.moveTo(x17, chartArea.top); ctx.lineTo(x17, chartArea.bottom); ctx.stroke();
        ctx.restore();
      }
    }]
  });
}

'''

if si != -1 and ei != -1:
    html = html[:si] + new_js + html[ei:]
    print('Chart7 JS replaced OK')
else:
    print('ERROR: JS markers not found')

# 4. Update renderAll
html = html.replace(
    '  renderZoneCards();\n  renderChart7();',
    '  buildRTPeriodOptions();\n  renderChart7();'
)

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