import re
from bs4 import BeautifulSoup

css_map = {
    'fw-bold': ('font-weight', '700'),
    'fw-bolder': ('font-weight', '800'),
    'fw-medium': ('font-weight', '500'),
    'fw-normal': ('font-weight', '400'),
    'fs-3': ('font-size', 'calc(1.3rem + 0.6vw)'),
    'fs-4': ('font-size', '26px'),
    'fs-5': ('font-size', '22px'),
    'fs-6': ('font-size', '18px'),
    'fs-7': ('font-size', '16px'),
    'fs-8': ('font-size', '14px'),
    'display-3': ('font-size', '42px'),
    'display-4': ('font-size', '42px')
}

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

soup = BeautifulSoup(html, 'html.parser')

css_rules = {}

for tag in soup.find_all(True):
    if not tag.has_attr('class'): continue
    
    classes = tag['class']
    removed = []
    kept = []
    for c in classes:
        if c in css_map:
            removed.append(c)
        else:
            kept.append(c)
            
    if removed:
        # Update class attribute
        if kept:
            tag['class'] = kept
        else:
            del tag['class']
            
        # Determine best semantic selector
        selector = None
        for c in kept:
            if not c.startswith(('text-', 'bg-', 'mb-', 'mt-', 'm-', 'p-', 'pb-', 'pt-', 'px-', 'py-', 'd-', 'flex-', 'align-', 'justify-', 'border', 'rounded', 'shadow', 'position', 'w-', 'h-', 'lh-', 'gap-', 'col', 'row', 'z-', 'g-')):
                selector = f".{c}"
                break
                
        if not selector:
            # Fallback to parent
            parent = tag.find_parent(class_=lambda x: x and not any(c.startswith(('text-', 'bg-', 'mb-', 'p-', 'd-', 'flex-', 'col', 'row')) for c in x))
            if parent:
                parent_classes = [c for c in parent['class'] if not c.startswith(('text-', 'bg-', 'mb-', 'p-', 'd-', 'flex-', 'col', 'row'))]
                if parent_classes:
                    selector = f".{parent_classes[0]} {tag.name}"
                    
        if not selector:
            selector = tag.name
            
        if selector not in css_rules:
            css_rules[selector] = {}
            
        for r in removed:
            prop, val = css_map[r]
            css_rules[selector][prop] = val

with open('index.html', 'w', encoding='utf-8') as f:
    f.write(str(soup))
    
# Generate CSS
css_str = "\n/* Extracted Typography from Bootstrap utilities */\n"
for selector, props in css_rules.items():
    css_str += f"{selector} {{\n"
    for prop, val in props.items():
        css_str += f"    {prop}: {val} !important;\n"
    css_str += "}\n"

with open('assets/css/style.css', 'a', encoding='utf-8') as f:
    f.write(css_str)

print("Refactoring complete.")
