import re

with open(r'D:\Evolução categorias\sistema_dfe.html', 'r', encoding='utf-8') as f:
    html = f.read()

# Find the main script (second one, with all JS logic)
matches = list(re.finditer(r'(<script(?:\s[^>]*)?>)(.*?)(</script>)', html, re.DOTALL))
script_match = matches[1]  # second script tag

pre       = html[:script_match.start()]
tag_open  = script_match.group(1)
body      = script_match.group(2)
tag_close = script_match.group(3)
post      = html[script_match.end():]

lines = body.split('\n')

# Find where new buildDRE() closes
new_builddre_close = None
depth = 0
in_fn = False
for i, line in enumerate(lines):
    if re.match(r'\s*function buildDRE\s*\(', line):
        in_fn = True; depth = 0
    if in_fn:
        depth += line.count('{') - line.count('}')
        if depth == 0 and i > 0 and ('{' in line or '}' in line):
            new_builddre_close = i
            in_fn = False
            break

print(f'Nova buildDRE fecha no indice: {new_builddre_close} (linha {new_builddre_close+1})')
print(f'Conteudo apos: {lines[new_builddre_close+1][:60]!r}')

# Find old tail end - look for the next standalone function after the tail
# The old tail ends where dreToggleGroup starts (which should be a standalone function)
old_tail_end = None
for i in range(new_builddre_close+1, len(lines)):
    line = lines[i]
    if re.match(r'^function (dreToggleGroup|dreToggleAll|dreVarCell|dreVarPct|dreFmt)\s*\(', line.strip()):
        old_tail_end = i
        break

print(f'Tail antigo vai do indice {new_builddre_close+1} ate {old_tail_end-1} (linha {old_tail_end})')
print(f'Primeira linha apos tail: {lines[old_tail_end][:60]!r}')

# Remove lines from new_builddre_close+1 to old_tail_end-1
# (keep: 0..new_builddre_close, old_tail_end..end)
clean_lines = lines[:new_builddre_close+1] + [''] + lines[old_tail_end:]
clean_body = '\n'.join(clean_lines)

# Validate braces
opens  = clean_body.count('{')
closes = clean_body.count('}')
print(f'\nValidacao: opens={opens} closes={closes} diff={opens-closes}')

new_html = pre + tag_open + clean_body + tag_close + post
with open(r'D:\Evolução categorias\sistema_dfe.html', 'w', encoding='utf-8') as f:
    f.write(new_html)
print('Arquivo salvo!')
