import re

MESES = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho',
         'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro']

with open(r'D:\Evolução categorias\sistema_dfe.html', 'r', encoding='utf-8') as f:
    html = f.read()

# ── 1. CSS extra ──────────────────────────────────────────────────────────────
css_extra = """
/* ── Filtro DRE mensal ─────────────────────────────────────────────── */
.dre-filter-bar {
  display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
  background: #0d1f35; border: 1px solid #1e3a5f;
  border-radius: 10px; padding: 12px 18px; margin-bottom: 16px;
}
.dre-filter-label { color: #94A3B8; font-size: 12px; font-weight: 600;
  text-transform: uppercase; letter-spacing: .05em; margin-right: 4px; }
.dre-toggle-group { display: flex; background: #0f1b2d;
  border-radius: 8px; border: 1px solid #1e3a5f; overflow: hidden; }
.dre-toggle-btn {
  padding: 6px 18px; font-size: 13px; font-weight: 600; cursor: pointer;
  background: transparent; border: none; color: #64748B;
  transition: all .2s; white-space: nowrap;
}
.dre-toggle-btn.active { background: #1e3a5f; color: #60A5FA; }
.dre-month-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-month-select.visible { display: block; }
.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; }
.dre-filter-info {
  margin-left: auto; font-size: 11px; color: #60A5FA;
  background: #1e3a5f33; padding: 4px 10px; border-radius: 6px;
}
.dre-row-sub-monthly td { padding-left: 10px !important; }
"""

# Inject CSS before </style>
html = html.replace('</style>', css_extra + '\n</style>', 1)

# ── 2. Substituir header da DRE ───────────────────────────────────────────────
MESES_JS = str(MESES).replace("'", '"')

old_header = '''      <div class="dre-header-row">
        <div class="dre-header-left">
          <h2>DRE Consolidado</h2>
          <span>Demonstração do Resultado do Exercício &mdash; comparativo anual 2021–2026</span>
        </div>
        <div class="dre-btn-group">
          <button class="dre-btn" id="dreExpandBtn" onclick="dreToggleAll()">
            <i class="fa-solid fa-expand"></i> Expandir Tudo
          </button>
          <button class="dre-btn" onclick="window.print()">
            <i class="fa-solid fa-print"></i> Imprimir / Exportar
          </button>
        </div>
      </div>'''

new_header = '''      <div class="dre-header-row">
        <div class="dre-header-left">
          <h2>DRE Consolidado</h2>
          <span id="dreSubtitle">Demonstração do Resultado do Exercício &mdash; comparativo anual 2021–2026</span>
        </div>
        <div class="dre-btn-group">
          <button class="dre-btn" id="dreExpandBtn" onclick="dreToggleAll()">
            <i class="fa-solid fa-expand"></i> Expandir Tudo
          </button>
          <button class="dre-btn" onclick="window.print()">
            <i class="fa-solid fa-print"></i> Imprimir / Exportar
          </button>
        </div>
      </div>

      <!-- Barra de filtro -->
      <div class="dre-filter-bar">
        <span class="dre-filter-label"><i class="fa-solid fa-filter"></i> Visualização</span>
        <div class="dre-toggle-group">
          <button class="dre-toggle-btn active" id="dreViewAnual" onclick="dreSetView('anual')">
            <i class="fa-solid fa-calendar"></i> Anual
          </button>
          <button class="dre-toggle-btn" id="dreViewMensal" onclick="dreSetView('mensal')">
            <i class="fa-solid fa-calendar-days"></i> Por Mês
          </button>
        </div>
        <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>
        <span class="dre-filter-info" id="dreFilterInfo">Todos os anos | Totais anuais</span>
      </div>'''

html = html.replace(old_header, new_header, 1)

# ── 3. Substituir função buildDRE() ──────────────────────────────────────────
# Find and replace the entire buildDRE function
old_fn_match = re.search(r'function buildDRE\(\).*?(?=\nfunction |\n  function )', html, re.DOTALL)
if not old_fn_match:
    print("ERROR: buildDRE not found")
    exit(1)

new_fn = r"""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();
}

function buildDRE() {
  const D = DFE_DATA;
  const YRS = YEARS;
  const MESES_NOME = """ + MESES_JS + r""";
  const view = window.dreView || 'anual';
  const mesIdx = parseInt(document.getElementById('dreMonthSel')?.value ?? 0);
  const mesNome = MESES_NOME[mesIdx];

  // Atualizar subtítulo e info
  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 {
    document.getElementById('dreSubtitle').textContent =
      'Demonstração do Resultado do Exercício — comparativo anual 2021–2026';
    document.getElementById('dreFilterInfo').textContent =
      'Todos os anos | Totais anuais';
    document.getElementById('dreExpandBtn').style.display = '';
  }

  // 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;
  }

  // --- HEAD ---
  let head = '<tr>';
  head += '<th>DEMONSTRATIVO DE RESULTADO DO EXERCÍCIO</th>';
  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>`;
    }
  });
  if (view === 'anual') head += '<th class="th-var">Var%&nbsp;25/24</th>';
  head += '</tr>';
  document.getElementById('dreHead').innerHTML = head;

  // --- BODY ---
  let body = '';
  const sep = `<tr class="dre-row-sep"><td colspan="${YRS.length + (view==='anual'?2:1)}"></td></tr>`;
  const cols = YRS.length + (view === 'anual' ? 2 : 1);

  function fmtV(v) {
    if (v === null || v === undefined) return '<span style="color:#334155">—</span>';
    const abs = Math.abs(v);
    const s = abs.toLocaleString('pt-BR', {minimumFractionDigits:2, maximumFractionDigits:2});
    if (v < 0) return `<span style="color:#f87171">(${s})</span>`;
    return s;
  }

  function varCell(v24, v25, isExpense) {
    if (!v24) return '<td class="td-varp">—</td>';
    const pct = (v25 - v24) / Math.abs(v24) * 100;
    const good = isExpense ? pct < 0 : pct > 0;
    const cls = good ? 'green' : 'red';
    const sym = pct > 0 ? '▲' : '▼';
    return `<td class="td-varp ${cls}">${sym} ${Math.abs(pct).toFixed(1)}%</td>`;
  }

  function rowAnual(label, dataKey, cls, isExpense, prefix) {
    let r = `<tr class="${cls}"><td>${prefix||''}${label}</td>`;
    let v24=0, v25=0;
    YRS.forEach(y => {
      const v = view==='anual' ? (D[dataKey]?.[y]||0)
              : (()=>{
                  const mKey='mensal_'+dataKey;
                  return D[mKey]?.[y]?.[mesIdx] ?? null;
                })();
      if (y==='2024') v24 = v||0;
      if (y==='2025') v25 = v||0;
      r += `<td>${fmtV(v)}</td>`;
    });
    if (view==='anual') r += varCell(v24, v25, isExpense);
    r += '</tr>';
    return r;
  }

  function rowCalc(label, fn, cls, isExpense, prefix) {
    let r = `<tr class="${cls}"><td>${prefix||''}${label}</td>`;
    let v24=0, v25=0;
    YRS.forEach(y => {
      const v = fn(y);
      if (y==='2024') v24 = v||0;
      if (y==='2025') v25 = v||0;
      r += `<td>${fmtV(v)}</td>`;
    });
    if (view==='anual') r += varCell(v24, v25, isExpense);
    r += '</tr>';
    return r;
  }

  function rowMargin(label, numKey, denKey, numFn, denFn) {
    let r = `<tr class="dre-row-margin"><td style="padding-left:24px;font-style:italic">${label}</td>`;
    YRS.forEach(y => {
      const num = numFn ? numFn(y) : (D[numKey]?.[y]||0);
      const den = denFn ? denFn(y) : (D[denKey]?.[y]||0);
      const pct = den ? (num/den*100) : 0;
      r += `<td style="font-style:italic;color:#94A3B8">${pct.toFixed(1)}%</td>`;
    });
    if (view==='anual') r += '<td></td>';
    r += '</tr>';
    return r;
  }

  function groupHeader(id, label, dataKey, isExpense, extraCls) {
    if (view === 'mensal') {
      // No mensal, group headers just show totals without expand
      let r = `<tr class="dre-row-group ${extraCls||''}" style="cursor:default">`;
      r += `<td><i class="fa-solid fa-minus" style="margin-right:8px;font-size:10px"></i>${label}</td>`;
      YRS.forEach(y => {
        const v = D[dataKey]?.[y] || 0;
        // For monthly, scale by proportion (approx: use annual/12 as fallback)
        const mv = view==='mensal' ? (v/12) : v;
        r += `<td>${fmtV(mv)}</td>`;
      });
      r += '</tr>';
      return r;
    }
    let r = `<tr class="dre-row-group ${extraCls||''}" onclick="dreToggleGroup('${id}',this)">`;
    r += `<td><i class="fa-solid fa-chevron-right dre-chevron" style="margin-right:8px;font-size:10px;transition:transform .2s"></i>${label}</td>`;
    let v24=0, v25=0;
    YRS.forEach(y => {
      const v = D[dataKey]?.[y] || 0;
      if(y==='2024') v24=v; if(y==='2025') v25=v;
      r += `<td>${fmtV(v)}</td>`;
    });
    r += varCell(v24, v25, isExpense);
    r += '</tr>';
    return r;
  }

  function subRows(groupId, subsKey, isExpense) {
    if (view === 'mensal') return ''; // sem subcontas no modo mensal
    const subs = D[subsKey] || {};
    return Object.entries(subs).map(([nome, vals], i) => {
      const bg = i%2===0 ? '#0f1b2d' : '#141f2e';
      let r = `<tr class="dre-row-sub" data-group="${groupId}" style="display:none;background:${bg}">`;
      r += `<td style="padding-left:42px;font-size:12px;color:#94A3B8">▸ ${nome}</td>`;
      let v24=0, v25=0;
      YRS.forEach(y => {
        const v = vals[y]||0;
        if(y==='2024') v24=v; if(y==='2025') v25=v;
        r += `<td style="font-size:12px;color:#94A3B8">${fmtV(v)}</td>`;
      });
      r += varCell(v24, v25, isExpense);
      r += '</tr>';
      return r;
    }).join('');
  }

  // Lucro bruto (calc)
  const lbFn  = y => (D.receita?.[y]||0) - (D.cmv?.[y]||0);
  const lbMFn = y => { const mr=D.mensal_receita?.[y]?.[mesIdx]||0; const mc=D.mensal_cmv?.[y]?.[mesIdx]||0; return mr-mc; };
  const resFn  = y => D.resultado?.[y]||0;
  const resMFn = y => D.mensal_resultado?.[y]?.[mesIdx]||0;
  const totDespFn  = y => D.tot_desp?.[y]||0;
  const totDespMFn = y => { const lb=lbMFn(y); const rs=resMFn(y); return lb-rs; };

  // ── BUILD ──
  // 1. Receita
  body += sep;
  body += rowAnual('(+) RECEITA BRUTA', 'receita', 'dre-row-receita', false, '');
  body += sep;

  // 2. CMV
  if (view==='anual') {
    body += groupHeader('cmv','(-) CUSTO MERCADORIAS VENDIDAS','cmv',true,'');
    body += subRows('cmv','cmv_subs',true);
  } else {
    body += rowAnual('(-) CUSTO MERCADORIAS VENDIDAS','cmv','dre-row-group',true,'');
  }
  body += sep;

  // 3. Lucro Bruto
  body += rowCalc('(=) LUCRO BRUTO', view==='mensal'?lbMFn:lbFn, 'dre-row-lb', false, '');
  body += rowMargin('Margem Bruta %', null, null,
    view==='mensal'?lbMFn:lbFn,
    view==='mensal'?(y=>D.mensal_receita?.[y]?.[mesIdx]||0):(y=>D.receita?.[y]||0));
  body += sep;

  // 4. Despesas
  if (view==='anual') {
    body += `<tr class="dre-row-group" style="cursor:default;opacity:.7">
      <td colspan="${cols}"><small style="padding-left:8px;letter-spacing:.1em;color:#64748B">▼ DESPESAS OPERACIONAIS</small></td></tr>`;
    body += groupHeader('fixas','(-) Despesas Fixas','desp_fixas',true,'');
    body += subRows('fixas','fix_subs',true);
    body += groupHeader('trib','(-) Despesas Tributárias','desp_trib',true,'');
    body += subRows('trib','trib_subs',true);
    body += groupHeader('var','(-) Despesas Variáveis','desp_var',true,'');
    body += subRows('var','var_subs',true);
    body += groupHeader('folha','(-) Folha de Pagamento','folha',true,'');
    body += subRows('folha','folha_subs',true);
    body += groupHeader('financ','(-) Encargos Financeiros','financ',true,'');
  } else {
    body += rowAnual('(-) Despesas Fixas','desp_fixas','dre-row-group',true,'  ');
    body += rowAnual('(-) Despesas Tributárias','desp_trib','dre-row-group',true,'  ');
    body += rowAnual('(-) Despesas Variáveis','desp_var','dre-row-group',true,'  ');
    body += rowAnual('(-) Folha de Pagamento','folha','dre-row-group',true,'  ');
    body += rowAnual('(-) Encargos Financeiros','financ','dre-row-group',true,'  ');
  }
  body += sep;

  // 5. Total Despesas
  if (view==='anual') {
    body += rowAnual('(-) TOTAL DESPESAS','tot_desp','dre-row-totdesp',true,'');
  } else {
    body += rowCalc('(-) TOTAL DESPESAS', totDespMFn, 'dre-row-totdesp', true, '');
  }
  body += sep;

  // 6. Resultado
  body += rowCalc('(=) RESULTADO DO EXERCÍCIO', view==='mensal'?resMFn:resFn, 'dre-row-resultado', false, '');
  body += rowMargin('Margem Líquida %', null, null,
    view==='mensal'?resMFn:resFn,
    view==='mensal'?(y=>D.mensal_receita?.[y]?.[mesIdx]||0):(y=>D.receita?.[y]||0));
  body += sep;

  document.getElementById('dreBody').innerHTML = body;
}

"""

html = html[:old_fn_match.start()] + new_fn + html[old_fn_match.end():]

with open(r'D:\Evolução categorias\sistema_dfe.html', 'w', encoding='utf-8') as f:
    f.write(html)

print("OK - DRE com filtro mensal aplicado")
