import json
import re

# 1. Generate FA list from metadata
try:
    with open('fa_meta.json', 'r') as f:
        data = json.load(f)
    
    fa_icons = []
    for name, info in data.items():
        styles = info.get('styles', [])
        for style in styles:
            prefix = 'fa-solid' if style == 'solid' else \
                     'fa-regular' if style == 'regular' else \
                     'fa-brands' if style == 'brands' else \
                     'fa-light'
            
            if prefix == 'fa-light': continue
            fa_icons.append(f"{prefix} fa-{name}")
            
    fa_js = '        const fontawesomeIcons = [\n            ' + ', '.join([f'"{icon}"' for icon in fa_icons]) + '\n        ]'
    print(f"Generated {len(fa_icons)} FA icons.")

except Exception as e:
    print(f"Error processing FA json: {e}")
    fa_js = ''

# 2. Read existing Homelab list from file to preserve it
homelab_js = ''
try:
    with open('app/templates/admin.html', 'r') as f:
        content = f.read()
        # Escape brackets in regex for literal match
        match = re.search(r'const homelabIcons = \[.*?\].*?;', content, re.DOTALL)
        if match:
            homelab_js = match.group(0)
            print(f"Found existing homelab icons block.")
        else:
            print("Did NOT find homelab icons block.")
            # Fallback for debugging
            print(content[:500]) 
except Exception as e:
    print(f"Error reading admin.html: {e}")

# 3. Write replacement
if homelab_js and fa_js:
    with open('replacement_fa.txt', 'w') as f:
        f.write(homelab_js + '\n\n' + fa_js)
    print("Wrote replacement_fa.txt")
else:
    print("Skipping write because data missing.")