with open('dashboard_estoque.html','r',encoding='utf-8') as f:
    html = f.read()

# Substituir todas as chamadas fmt(x) pelo equivalente correto no bloco da aba margem
# fmt(valor) => valor.toLocaleString('pt-BR',{minimumFractionDigits:2,maximumFractionDigits:2})
import re

# Localizar bloco JS da aba margem
start = html.find('// ════════════════════════════════════════════\n//  ABA MARGEM DE LUCRO')
end   = html.find('\n</script>\n</body>', start)

if start < 0:
    print("ERRO: bloco nao encontrado")
else:
    bloco = html[start:end]
    # Substituir fmt(p.custo) => p.custo.toLocaleString(...)
    def sub_fmt(m):
        arg = m.group(1)
        return f"{arg}.toLocaleString('pt-BR',{{minimumFractionDigits:2,maximumFractionDigits:2}})"
    novo = re.sub(r'\bfmt\(([^)]+)\)', sub_fmt, bloco)
    html = html[:start] + novo + html[end:]
    count = bloco.count('fmt(')
    print(f"Substituidas {count} chamadas fmt()")

with open('dashboard_estoque.html','w',encoding='utf-8') as f:
    f.write(html)
print("Salvo OK")
