import re

with open(r'D:\Evolução categorias\sistema_dfe.html', 'r', encoding='utf-8') as f:
    html = f.read()

# ── 1. Adicionar seletor de ano ao HTML do filtro ─────────────────────────────
old_filter = '''        <select class="dre-month-select" id="dreMonthSel" onchange="buildDRE()">
          <option value="0">Janeiro</option><option value="1">Fevereiro</option>
          <option value="2">Março</option><option value="3">Abril</option>
          <option value="4">Maio</option><option value="5">Junho</option>
          <option value="6">Julho</option><option value="7">Agosto</option>
          <option value="8">Setembro</option><option value="9">Outubro</option>
          <option value="10">Novembro</option><option value="11">Dezembro</option>
        </select>'''

new_filter = '''        <select class="dre-year-select" id="dreYearSel" onchange="buildDRE()">
          <option value="2021">2021</option>
          <option value="2022">2022</option>
          <option value="2023">2023</option>
          <option value="2024">2024</option>
          <option value="2025">2025</option>
          <option value="2026" selected>2026</option>
        </select>
        <select class="dre-month-select" id="dreMonthSel" onchange="buildDRE()">
          <option value="0">Janeiro</option><option value="1">Fevereiro</option>
          <option value="2">Março</option><option value="3" selected>Abril</option>
          <option value="4">Maio</option><option value="5">Junho</option>
          <option value="6">Julho</option><option value="7">Agosto</option>
          <option value="8">Setembro</option><option value="9">Outubro</option>
          <option value="10">Novembro</option><option value="11">Dezembro</option>
        </select>'''

html = html.replace(old_filter, new_filter, 1)

# ── 2. CSS: mostrar dre-year-select quando modo mensal ────────────────────────
old_css = '''.dre-year-select {
  background: #0f1b2d; border: 1px solid #1e3a5f; border-radius: 8px;
  color: #E2E8F0; padding: 6px 14px; font-size: 13px; cursor: pointer;
  display: none; outline: none;
}
.dre-year-select.visible { display: block; }'''

# Se já tiver o CSS, substituir; se não, adicionar junto ao dre-month-select
if '.dre-year-select' not in html:
    html = html.replace(
        '.dre-month-select.visible { display: block; }',
        '.dre-month-select.visible { display: block; }\n.dre-year-select.visible { display: block; }'
    )

# ── 3. Atualizar dreSetView para mostrar/ocultar year select ──────────────────
old_setview = '''function dreSetView(v) {
  window.dreView = v;
  document.getElementById('dreViewAnual').classList.toggle('active', v==='anual');
  document.getElementById('dreViewMensal').classList.toggle('active', v==='mensal');
  const mSel = document.getElementById('dreMonthSel');
  mSel.classList.toggle('visible', v==='mensal');
  buildDRE();
}'''

new_setview = '''function dreSetView(v) {
  window.dreView = v;
  document.getElementById('dreViewAnual').classList.toggle('active', v==='anual');
  document.getElementById('dreViewMensal').classList.toggle('active', v==='mensal');
  document.getElementById('dreMonthSel').classList.toggle('visible', v==='mensal');
  document.getElementById('dreYearSel').classList.toggle('visible', v==='mensal');
  buildDRE();
}'''

html = html.replace(old_setview, new_setview, 1)

# ── 4. Atualizar buildDRE para usar ano selecionado no modo mensal ────────────
old_view_line = "  const view = window.dreView || 'anual';\n  const mesIdx = parseInt(document.getElementById('dreMonthSel')?.value ?? 0);\n  const mesNome = MESES_NOME[mesIdx];"

new_view_line = """  const view = window.dreView || 'mensal';
  const mesIdx = parseInt(document.getElementById('dreMonthSel')?.value ?? 3);
  const anoSel = document.getElementById('dreYearSel')?.value || '2026';
  const mesNome = MESES_NOME[mesIdx];"""

html = html.replace(old_view_line, new_view_line, 1)

# ── 5. Atualizar getVal para usar anoSel no modo mensal ──────────────────────
old_getval = """  // Função: obter valor (anual ou mensal)
  function getVal(dataKey, year) {
    if (view === 'mensal') {
      const mKey = 'mensal_' + dataKey;
      if (D[mKey] && D[mKey][year]) return D[mKey][year][mesIdx] || 0;
      return null; // sem dado mensal → null
    }
    return D[dataKey] ? (D[dataKey][year] || 0) : 0;
  }

  // Para visão mensal: derivar despesas = lucro_bruto - resultado
  function getTotDespMensal(year) {
    const r = (D.mensal_receita[year]||[])[mesIdx] || 0;
    const c = (D.mensal_cmv[year]||[])[mesIdx] || 0;
    const lb = r - c;
    const res = (D.mensal_resultado[year]||[])[mesIdx] || 0;
    return lb - res;
  }"""

new_getval = """  // Função: obter valor (anual ou mensal)
  function getVal(dataKey, year) {
    if (view === 'mensal') {
      const mKey = 'mensal_' + dataKey;
      if (D[mKey] && D[mKey][year]) return D[mKey][year][mesIdx] || 0;
      return null;
    }
    return D[dataKey] ? (D[dataKey][year] || 0) : 0;
  }

  // Modo mensal: só exibir o ano selecionado
  const YRS = view === 'mensal' ? [anoSel] : YEARS;

  // Para visão mensal: derivar despesas = lucro_bruto - resultado
  function getTotDespMensal(year) {
    const r = (D.mensal_receita[year]||[])[mesIdx] || 0;
    const c = (D.mensal_cmv[year]||[])[mesIdx] || 0;
    const lb = r - c;
    const res = (D.mensal_resultado[year]||[])[mesIdx] || 0;
    return lb - res;
  }"""

html = html.replace(old_getval, new_getval, 1)

# ── 6. Corrigir YRS no HEAD – 2026 (Jan-Abr) só aparece no modo anual ────────
old_head_2026 = """  YRS.forEach(y => {
    if (y === '2026' && view === 'anual') {
      head += `<th class="th-2026">${y}<br><small style="font-weight:400;font-size:10px;color:#60A5FA">(Jan–Abr)</small></th>`;
    } else {
      head += `<th>${y}</th>`;
    }
  });"""

new_head_2026 = """  YRS.forEach(y => {
    if (y === '2026' && view === 'anual') {
      head += `<th class="th-2026">${y}<br><small style="font-weight:400;font-size:10px;color:#60A5FA">(Jan–Abr)</small></th>`;
    } else if (view === 'mensal') {
      head += `<th style="background:#1e3a5f;color:#60A5FA">${mesNome} / ${y}</th>`;
    } else {
      head += `<th>${y}</th>`;
    }
  });"""

html = html.replace(old_head_2026, new_head_2026, 1)

# ── 7. Atualizar subtítulo e info no modo mensal ──────────────────────────────
old_subtitle = """  if (view === 'mensal') {
    document.getElementById('dreSubtitle').textContent =
      'Demonstração do Resultado do Exercício — ' + mesNome + ' (comparativo entre anos)';
    document.getElementById('dreFilterInfo').textContent =
      'Mês selecionado: ' + mesNome + ' | Um valor por ano';
    document.getElementById('dreExpandBtn').style.display = 'none';
  } else {"""

new_subtitle = """  if (view === 'mensal') {
    document.getElementById('dreSubtitle').textContent =
      'Demonstração do Resultado do Exercício — ' + mesNome + ' de ' + anoSel;
    document.getElementById('dreFilterInfo').textContent =
      mesNome + ' / ' + anoSel;
    document.getElementById('dreExpandBtn').style.display = 'none';
  } else {"""

html = html.replace(old_subtitle, new_subtitle, 1)

# ── 8. Definir padrão inicial: modo mensal, abril, 2026 ──────────────────────
# Mudar o botão anual para não ter 'active' e o mensal ter 'active'
old_btn_anual   = '<button class="dre-toggle-btn active" id="dreViewAnual" onclick="dreSetView(\'anual\')">'
new_btn_anual   = '<button class="dre-toggle-btn" id="dreViewAnual" onclick="dreSetView(\'anual\')">'
old_btn_mensal  = '<button class="dre-toggle-btn" id="dreViewMensal" onclick="dreSetView(\'mensal\')">'
new_btn_mensal  = '<button class="dre-toggle-btn active" id="dreViewMensal" onclick="dreSetView(\'mensal\')">'

html = html.replace(old_btn_anual,  new_btn_anual,  1)
html = html.replace(old_btn_mensal, new_btn_mensal, 1)

# Mostrar selects já visíveis por padrão (modo mensal é o padrão)
html = html.replace(
    '<select class="dre-month-select" id="dreMonthSel"',
    '<select class="dre-month-select visible" id="dreMonthSel"', 1)
html = html.replace(
    '<select class="dre-year-select" id="dreYearSel"',
    '<select class="dre-year-select visible" id="dreYearSel"', 1)

# ── 9. Definir window.dreView = 'mensal' antes do init ───────────────────────
html = html.replace(
    "window.addEventListener('DOMContentLoaded', init);",
    "window.dreView = 'mensal';\nwindow.addEventListener('DOMContentLoaded', init);"
)

with open(r'D:\Evolução categorias\sistema_dfe.html', 'w', encoding='utf-8') as f:
    f.write(html)

# Validar chaves
import re as _re
scripts = list(_re.finditer(r'<script[^>]*>(.*?)</script>', html, _re.DOTALL))
s = scripts[1].group(1)
diff = s.count('{') - s.count('}')
print(f"Chaves: opens={s.count('{')} closes={s.count('}')} diff={diff}")
print("OK!" if diff == 0 else "ERRO: chaves desbalanceadas!")
