import re

def fix_columns():
    with open('app/modules/sag/templates/detail.html', 'r', encoding='utf-8') as f:
        html = f.read()

    # Udskift selve start containeren! 
    # Målet er at omdanne:
    # <div class="col-lg-8" id="case-left-column"> ... (Hero card, etc.)
    # <div class="col-lg-4" id="case-right-column"> ... (Tidsreg, etc.)
    
    # Fordi det er komplekst at udtrække hver enkelt data-module fra en stor fil uden at tabe layout,
    # griber vi det an ved at ændre CSS klasserne på container niveauet HVIS vi kun ville ha flex, 
    # men for rigtige 3 kolonner flytter vi `case-left-column`s grid definitioner.
    
    # Vi kan bygge 3 kolonner inde "case-left-column" + "case-right-column" er den 3. kolonne.
    # Så left -> 2 kolonner, right -> 1 kolonne. Total 3.
    # Nu er left = col-lg-8. Vi gør den til col-xl-9 col-lg-8.
    # Right = col-lg-4. Bliver til col-xl-3 col-lg-4.
    
    # INDE i left:
    # Put et grid: <div class="row"><div class="col-xl-4"> (Venstre) </div> <div class="col-xl-8"> (Midten med Opgavebeskivelse) </div></div>
    
    # Step 1: Let's find "id="case-left-column""
    html = html.replace('<div class="col-lg-8" id="case-left-column">', '<div class="col-xl-9 col-lg-8" id="case-left-column">\n<div class="row g-4">\n<!-- TREDELT-1: Relations, History, etc. -->\n<div class="col-xl-4 order-2 order-xl-1" id="inner-left-col">\n</div>\n<!-- TREDELT-2: Hero, Info -->\n<div class="col-xl-8 order-1 order-xl-2" id="inner-center-col">\n')
    
    html = html.replace('<div class="col-lg-4" id="case-right-column">', '</div></div><!-- slut inner cols -->\n</div>\n<div class="col-xl-3 col-lg-4" id="case-right-column">')
    
    # Now we need to MOVE widgets from "inner-center-col" (where everything currently is) to "inner-left-col".
    # The widgets we want to move are:
    # 'relations'
    # 'call-history'
    # 'pipeline'
    
    def move_widget(widget_name, dest_id, current_html):
        pattern = f'data-module="{widget_name}"'
        match = current_html.find(pattern)
        if match == -1:
            return current_html
            
        div_start = current_html.rfind('<div class="row mb-3"', max(0, match - 200), match)
        if div_start == -1:
            div_start = current_html.rfind('<div class="card', max(0, match - 200), match)
            
        if div_start == -1:
            return current_html
            
        # Find balanced end
        count = 0
        i = div_start
        end_idx = -1
        while i < len(current_html):
            if current_html.startswith('<div', i):
                count += 1
                i += 4
            elif current_html.startswith('</div', i):
                count -= 1
                if count <= 0:
                    i = current_html.find('>', i) + 1
                    end_idx = i
                    break
                else:
                    i += 5
            else:
                i += 1
                
        if end_idx != -1:
            widget = current_html[div_start:end_idx]
            # Fjern fra oprendelig plads
            current_html = current_html[:div_start] + current_html[end_idx:]
            
            # Sæt ind i ny plads (lige efter dest_id div'en)
            dest_pattern = f'id="{dest_id}">\n'
            dest_pos = current_html.find(dest_pattern)
            if dest_pos != -1:
                insert_pos = dest_pos + len(dest_pattern)
                current_html = current_html[:insert_pos] + widget + "\n" + current_html[insert_pos:]
                
        return current_html

    html = move_widget('relations', 'inner-left-col', html)
    html = move_widget('call-history', 'inner-left-col', html)
    html = move_widget('pipeline', 'inner-left-col', html)

    # Nogle widgets ligger i right-col, som vi gerne vil have i left col nu? 
    # Contacts, Customers, Locations
    # De ligger ikke i en <div class="row mb-3">, de er bare direkte `<div class="card h-100...`
    # Let's extract them correctly
    def move_card(widget_name, dest_id, current_html):
        pattern = f'data-module="{widget_name}"'
        match = current_html.find(pattern)
        if match == -1:
            return current_html
            
        div_start = current_html.rfind('<div class="card', max(0, match - 200), match)
        if div_start == -1:
            return current_html
            
        count = 0
        i = div_start
        end_idx = -1
        while i < len(current_html):
            if current_html.startswith('<div', i):
                count += 1
                i += 4
            elif current_html.startswith('</div', i):
                count -= 1
                if count <= 0:
                    i = current_html.find('>', i) + 1
                    end_idx = i
                    break
                else:
                    i += 5
            else:
                i += 1
                
        if end_idx != -1:
            widget = current_html[div_start:end_idx]
            # De er ofte svøbt i en class mb-3 i col-right. Hvis ikke, læg vi en mb-3 kappe
            widget = f'<div class="mb-3">{widget}</div>'
            current_html = current_html[:div_start] + current_html[end_idx:]
            
            dest_pattern = f'id="{dest_id}">\n'
            dest_pos = current_html.find(dest_pattern)
            if dest_pos != -1:
                insert_pos = dest_pos + len(dest_pattern)
                current_html = current_html[:insert_pos] + widget + "\n" + current_html[insert_pos:]
                
        return current_html

    html = move_card('contacts', 'inner-left-col', html)
    html = move_card('customers', 'inner-left-col', html)
    html = move_card('locations', 'inner-left-col', html)
    
    with open('app/modules/sag/templates/detail.html', 'w', encoding='utf-8') as f:
        f.write(html)
        
    print("Drejede kolonnerne på plads!")

if __name__ == '__main__':
    fix_columns()
