import mysql.connector
import os
import sys

# Add parent dir to path to import db
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from db import DB_CONFIG

def migrate():
    try:
        conn = mysql.connector.connect(**DB_CONFIG)
        cursor = conn.cursor()
        
        print("Checking materials table...")
        cursor.execute("DESCRIBE materials")
        columns = [c[0] for c in cursor.fetchall()]
        
        if 'name_key' in columns:
            print("Migrating materials table to localized columns...")
            cursor.execute("ALTER TABLE materials ADD COLUMN name_en VARCHAR(100) AFTER id")
            cursor.execute("ALTER TABLE materials ADD COLUMN name_ru VARCHAR(100) AFTER name_en")
            cursor.execute("ALTER TABLE materials ADD COLUMN name_me VARCHAR(100) AFTER name_ru")
            cursor.execute("ALTER TABLE materials ADD COLUMN desc_en TEXT AFTER name_me")
            cursor.execute("ALTER TABLE materials ADD COLUMN desc_ru TEXT AFTER desc_en")
            cursor.execute("ALTER TABLE materials ADD COLUMN desc_me TEXT AFTER desc_ru")
            cursor.execute("ALTER TABLE materials DROP COLUMN name_key")
            cursor.execute("ALTER TABLE materials DROP COLUMN description_key")
            
        print("Checking services table...")
        cursor.execute("DESCRIBE services")
        columns = [c[0] for c in cursor.fetchall()]
        if 'description_key' in columns:
            # Check if it's already text or needs change
            pass # We'll just leave it for now or truncate and redo
            
        conn.commit()
        print("Migration complete.")
        
    except Exception as e:
        print(f"Error: {e}")
    finally:
        if 'conn' in locals() and conn.is_connected():
            cursor.close()
            conn.close()

if __name__ == "__main__":
    migrate()
