import re, os, json

path = 'index_main.html'
with open(path, 'r', encoding='utf-8') as f:
    html = f.read()

before_size = len(html.encode('utf-8'))

# Find VD Set start
vd_start = html.find('const VERIFIED_DETAILS=new Set([')
if vd_start < 0:
    raise SystemExit('VD set not found')

# Find the end of Set(...) by bracket depth
bracket_start = html.find('([', vd_start)
# Actually structure: new Set([ ... ])
# Find the [ after Set(
bracket_start = html.find('[', html.find('new Set(', vd_start))
depth = 1
i = bracket_start + 1
while i < len(html) and depth > 0:
    c = html[i]
    if c == '[':
        depth += 1
    elif c == ']':
        depth -= 1
    i += 1
# i is now just past the closing ]
bracket_end = i - 1  # position of ]

# Existing VD entries
inside = html[bracket_start+1:bracket_end]
existing = set(re.findall(r'"(details/[^"]+)"', inside))
print(f'Existing VD entries: {len(existing)}')

# Find missing from PROGRAMS
pm = re.search(r'const PROGRAMS=\[', html)
# Find PROGRAMS array end
prog_start = html.find('[', pm.start())
depth = 1
i = prog_start + 1
while i < len(html) and depth > 0:
    c = html[i]
    if c == '[':
        depth += 1
    elif c == ']':
        depth -= 1
    i += 1
prog_block = html[prog_start+1:i-1]
prog_urls = re.findall(r'url:"(details/[^"]+)"', prog_block)
missing = [u for u in prog_urls if u not in existing]
print(f'PROGRAMS urls: {len(prog_urls)}, missing: {len(missing)}')

# Verify each missing exists on disk
to_add = []
for u in missing:
    p = u.replace('/', os.sep)
    if os.path.exists(p):
        to_add.append(u)
    else:
        print(f'  DISK MISSING (skip): {u}')

print(f'Will add: {len(to_add)} entries')

# Build the new block: insert entries before ]
# Format: existing entries may or may not have trailing comma
# We need: existing inside + (existing ends with comma? or not) + new entries
# Safer: rebuild inside as comma-separated list
all_entries = sorted(existing | set(to_add))
new_inside = ','.join(f'"{e}"' for e in all_entries)
new_html = html[:bracket_start+1] + new_inside + html[bracket_end:]

after_size = len(new_html.encode('utf-8'))
print(f'Before: {before_size}, After: {after_size}, Delta: +{after_size-before_size}')

with open(path, 'w', encoding='utf-8') as f:
    f.write(new_html)

print('Done. Run _vd_check.py to verify.')
