#!/usr/bin/env python3
"""
Move Relationer to center column + add dynamic column distribution JS.
"""

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

# ── 1. Extract the relations block from inner-left-col ───────────────────────
start_marker = '<div class="row mb-3">\n        <div class="col-12 mb-3">\n            <div class="card h-100 d-flex flex-column" data-module="relations"'
end_marker_after = '    </div>\n<div class="mb-3"></div>\n<div class="mb-3"></div>\n<div class="mb-3"></div>'

start_idx = content.find(start_marker)
if start_idx == -1:
    print("ERROR: Could not find relations block start")
    exit(1)

end_marker_idx = content.find(end_marker_after, start_idx)
if end_marker_idx == -1:
    print("ERROR: Could not find relations block end / empty spacers")
    exit(1)

end_idx = end_marker_idx + len(end_marker_after)

relations_block = content[start_idx:end_idx - len('\n<div class="mb-3"></div>\n<div class="mb-3"></div>\n<div class="mb-3"></div>')]
print(f"Extracted relations block: chars {start_idx} - {end_idx}")
print(f"Relations block starts with: {relations_block[:80]!r}")
print(f"Relations block ends with: {relations_block[-60:]!r}")

# ── 2. Remove the relations block + spacers from inner-left-col ──────────────
content = content[:start_idx] + content[end_idx:]
print("Removed relations + spacers from inner-left-col")

# ── 3. Insert relations into inner-center-col (before ROW 3: Files) ──────────
insert_before = '    <!-- ROW 3: Files + Linked Emails -->'
insert_idx = content.find(insert_before)
if insert_idx == -1:
    print("ERROR: Could not find ROW 3 insertion point")
    exit(1)

relations_in_center = '\n    <!-- Relationer (center) -->\n' + relations_block + '\n\n'
content = content[:insert_idx] + relations_in_center + content[insert_idx:]
print(f"Inserted relations before ROW 3 at char {insert_idx}")

# ── 4. Add updateInnerColumnVisibility() after updateRightColumnVisibility() ─
old_js = """        function updateRightColumnVisibility() {
            const rightColumn = document.getElementById('case-right-column');
            const leftColumn = document.getElementById('case-left-column');
            if (!rightColumn || !leftColumn) return;

            const visibleRightModules = rightColumn.querySelectorAll('.right-module-card:not(.d-none)');
            if (visibleRightModules.length === 0) {
                rightColumn.classList.add('d-none');
                rightColumn.classList.remove('col-lg-4');
                leftColumn.classList.remove('col-lg-8');
                leftColumn.classList.add('col-12');
            } else {
                rightColumn.classList.remove('d-none');
                rightColumn.classList.add('col-lg-4');
                leftColumn.classList.add('col-lg-8');
                leftColumn.classList.remove('col-12');
            }
        }"""

new_js = """        function updateRightColumnVisibility() {
            const rightColumn = document.getElementById('case-right-column');
            const leftColumn = document.getElementById('case-left-column');
            if (!rightColumn || !leftColumn) return;

            const visibleRightModules = rightColumn.querySelectorAll('.right-module-card:not(.d-none)');
            if (visibleRightModules.length === 0) {
                rightColumn.classList.add('d-none');
                rightColumn.classList.remove('col-lg-4');
                leftColumn.classList.remove('col-lg-8');
                leftColumn.classList.add('col-12');
            } else {
                rightColumn.classList.remove('d-none');
                rightColumn.classList.add('col-lg-4');
                leftColumn.classList.add('col-lg-8');
                leftColumn.classList.remove('col-12');
            }
        }

        function updateInnerColumnVisibility() {
            const leftCol = document.getElementById('inner-left-col');
            const centerCol = document.getElementById('inner-center-col');
            if (!leftCol || !centerCol) return;

            // Tæl synlige moduler i venstre kolonnen (mb-3 wrappers der ikke er skjulte)
            const visibleLeftModules = leftCol.querySelectorAll('.mb-3:not(.d-none) [data-module]');
            const hasVisibleLeft = visibleLeftModules.length > 0;

            if (!hasVisibleLeft) {
                // Ingen synlige moduler i venstre - udvid center til fuld bredde
                leftCol.classList.add('d-none');
                centerCol.classList.remove('col-xl-8');
                centerCol.classList.add('col-xl-12');
            } else {
                // Gendan 4/8 split
                leftCol.classList.remove('d-none');
                centerCol.classList.remove('col-xl-12');
                centerCol.classList.add('col-xl-8');
            }
        }"""

if old_js in content:
    content = content.replace(old_js, new_js)
    print("Added updateInnerColumnVisibility() function")
else:
    print("ERROR: Could not find updateRightColumnVisibility() for JS patch")
    exit(1)

# ── 5. Call updateInnerColumnVisibility() from applyViewLayout ───────────────
old_call = '            updateRightColumnVisibility();\n        }'
new_call = '            updateRightColumnVisibility();\n            updateInnerColumnVisibility();\n        }'

if old_call in content:
    content = content.replace(old_call, new_call, 1)
    print("Added updateInnerColumnVisibility() call in applyViewLayout")
else:
    print("ERROR: Could not find updateRightColumnVisibility() call")
    exit(1)

# ── Write file ────────────────────────────────────────────────────────────────
with open('app/modules/sag/templates/detail.html', 'w', encoding='utf-8') as f:
    f.write(content)

print("\n✅ Done! Lines written:", content.count('\n'))
