import re

# ── 1. Patch admin.html ─────────────────────────────────────────────────────
with open(r'd:\SERVIDO_QNB\frontend\admin.html', 'r', encoding='utf-8', errors='replace') as f:
    html = f.read()

# Normalize to find the block regardless of \r\n vs \n
html_norm = html.replace('\r\n', '\n').replace('\r', '\n')

# The unique marker inside the venda row
MARKER = "Pedido #${v.pedido_id}"
idx = html_norm.find(MARKER)
if idx < 0:
    print("ERROR: marker not found in html")
    exit(1)

# Find the start of the venda <div> (go backwards to find it)
div_start = html_norm.rfind('<div style="display:flex;align-items:center;justify-content:space-between', 0, idx)
if div_start < 0:
    print("ERROR: outer div not found")
    exit(1)

# Find the closing </div> of this venda block
# We need to count depth to find the matching close
depth = 0
pos = div_start
while pos < len(html_norm):
    open_pos = html_norm.find('<div', pos)
    close_pos = html_norm.find('</div>', pos)
    if close_pos < 0:
        break
    if open_pos >= 0 and open_pos < close_pos:
        depth += 1
        pos = open_pos + 4
    else:
        depth -= 1
        if depth == 0:
            div_end = close_pos + 6  # include </div>
            break
        pos = close_pos + 6

old_block = html_norm[div_start:div_end]

new_block = '''<div style="display:flex;align-items:center;justify-content:space-between;padding:10px 12px;background:var(--bg-canvas);border-radius:10px;margin-bottom:6px;border:1px solid var(--border-color);font-size:12px;">
                                        <div>
                                            <span style="font-weight:700;color:var(--text-primary);">Pedido #${v.pedido_id}</span>
                                            <span style="color:var(--text-secondary);margin-left:8px;">${v.hora_venda || ''}</span>
                                            <div style="font-size:10px;color:var(--text-secondary);margin-top:2px;">${gcFmt(v.total_pedido)} em vendas</div>
                                        </div>
                                        <div style="display:flex;align-items:center;gap:8px;">
                                            <div style="text-align:right;">
                                                <div style="font-weight:900;color:#6c5ce7;font-size:14px;">${gcFmt(v.valor_porcentagem)}</div>
                                                <div style="font-size:9px;font-weight:900;margin-top:2px;" class="${v.fechamento_id ? 'gc-tag-fechado' : 'gc-tag-pendente'}">${v.fechamento_id ? 'FECHADO' : 'PENDENTE'}</div>
                                            </div>
                                            <button onclick="window.editarComissaoVenda(${v.id}, ${v.valor_porcentagem}, ${v.total_pedido}, ${id})" title="Editar comissao desta venda" style="border:none;background:#6c5ce720;color:#6c5ce7;border-radius:8px;padding:7px 10px;font-size:13px;font-weight:900;cursor:pointer;flex-shrink:0;"><i class="fas fa-pen"></i></button>
                                        </div>
                                    </div>'''

if old_block in html_norm:
    new_html = html_norm.replace(old_block, new_block, 1)
    # Restore CRLF for Windows
    new_html = new_html.replace('\n', '\r\n')
    with open(r'd:\SERVIDO_QNB\frontend\admin.html', 'w', encoding='utf-8') as f:
        f.write(new_html)
    print("SUCCESS: venda row updated in admin.html")
else:
    print("FALLBACK: trying direct string injection at div_start...")
    # Write original_block for debug
    print("BLOCK FOUND:", repr(old_block[:200]))

# ── 2. Add editarComissaoVenda JS function before </script> of garcon script ─
with open(r'd:\SERVIDO_QNB\frontend\admin.html', 'r', encoding='utf-8', errors='replace') as f:
    html2 = f.read()

html2_norm = html2.replace('\r\n', '\n').replace('\r', '\n')

INSERT_AFTER = "window.fecharComissaoGarcom = async function(id) {"
INSERT_MARKER = "window.editarComissaoVenda"

if INSERT_MARKER in html2_norm:
    print("JS function already present, skipping...")
else:
    new_js = '''window.editarComissaoVenda = async function(vendaId, valorAtual, totalPedido, garcomId) {
                const pctAtual = totalPedido > 0 ? ((valorAtual / totalPedido) * 100).toFixed(2) : '0';
                const novoValorStr = prompt(
                    'Editar comissao do garcom\\n\\nVenda: ' + gcFmt(totalPedido) + '\\nComissao atual: ' + gcFmt(valorAtual) + '\\n\\nDigite o NOVO VALOR de comissao (R$):',
                    valorAtual.toFixed ? valorAtual.toFixed(2).replace('.', ',') : valorAtual
                );
                if (novoValorStr === null) return;
                const novoValor = parseFloat(String(novoValorStr).replace(',', '.'));
                if (isNaN(novoValor) || novoValor < 0) { alert('Valor invalido. Use numeros positivos (ex: 7,48)'); return; }
                try {
                    const res = await fetch('/api/admin/garcons-vendas/' + vendaId, {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ valor_porcentagem: novoValor })
                    });
                    const d = await res.json();
                    if (!d.success) { alert(d.error || 'Erro ao atualizar comissao'); return; }
                    alert('Comissao atualizada para ' + gcFmt(novoValor) + ' com sucesso!');
                    window.carregarRelatorioGarcom(garcomId);
                } catch(e) {
                    alert('Erro de conexao ao atualizar comissao.');
                }
            };

            '''

    old_anchor = "window.fecharComissaoGarcom = async function(id) {"
    if old_anchor in html2_norm:
        new_html2 = html2_norm.replace(old_anchor, new_js + old_anchor, 1)
        new_html2 = new_html2.replace('\n', '\r\n')
        with open(r'd:\SERVIDO_QNB\frontend\admin.html', 'w', encoding='utf-8') as f:
            f.write(new_html2)
        print("SUCCESS: editarComissaoVenda JS function added")
    else:
        print("ERROR: anchor for JS not found")
