import sys
import os

# Add project root to python path to allow importing app modules
sys.path.append(os.getcwd())

from app.core.database import execute_query, init_db
from app.core.config import settings

def fix_relations():
    # Patch database URL for local execution
    if "@postgres" in settings.DATABASE_URL:
        print(f"🔧 Patcher DATABASE_URL fra '{settings.DATABASE_URL}'...")
        settings.DATABASE_URL = settings.DATABASE_URL.replace("@postgres", "@localhost").replace(":5432", ":5433")
        print(f"   ...til '{settings.DATABASE_URL}'")

    # Initialize database connection
    init_db()

    print("🚀 Standardiserer relationstyper i databasen...")
    
    # Mapping: Højre side (liste) konverteres til Venstre side (key)
    mappings = {
        "Afledt af": ["DERIVED", "derived", "AFLEDT AF", "afledt af"],
        "Blokkerer": ["BLOCKS", "blocks", "BLOKKERER", "blokkerer"],
        "Relateret til": ["RELATED", "related", "RELATERET TIL", "relateret til", "relateret"]
    }

    total_updated = 0
    
    for new_val, old_vals in mappings.items():
        for old_val in old_vals:
            if old_val == new_val:
                continue
                
            # Hent antal der skal opdateres
            try:
                check_query = "SELECT COUNT(*) as count FROM sag_relationer WHERE relationstype = %s AND deleted_at IS NULL"
                result = execute_query(check_query, (old_val,))
                count = result[0]['count'] if result else 0
                
                if count > 0:
                    print(f"   🔄 Konverterer {count} rækker fra '{old_val}' -> '{new_val}'")
                    update_query = "UPDATE sag_relationer SET relationstype = %s WHERE relationstype = %s"
                    execute_query(update_query, (new_val, old_val))
                    total_updated += count
            except Exception as e:
                print(f"Fejl ved behandling af '{old_val}': {e}")

    print(f"✅ Færdig! Opdaterede i alt {total_updated} relationer.")

if __name__ == "__main__":
    fix_relations()
