import os
import sys
import django

# Add the project root to the python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'chatpro.settings')
django.setup()

from django.db import connection

def run():
    if connection.vendor != 'mysql':
        print(f"Notice: This script is intended for MySQL databases.")
        print(f"Currently connected to: {connection.vendor}")
        print("If you deploy to MySQL, run this script there to fix Bengali text encoding.")
        return

    db_name = connection.settings_dict['NAME']
    if not db_name:
        print("Could not determine database name.")
        return

    print("Starting MySQL utf8mb4 conversion to support Bengali text...")
    try:
        with connection.cursor() as cursor:
            # 1. Alter Database
            print(f"Altering Database `{db_name}` default character set to utf8mb4...")
            cursor.execute(f"ALTER DATABASE `{db_name}` CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;")
            
            # 2. Alter all Tables
            cursor.execute("SHOW TABLES")
            tables = cursor.fetchall()
            
            for table in tables:
                table_name = table[0]
                print(f"Converting table: {table_name}")
                cursor.execute(f"ALTER TABLE `{table_name}` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;")
                
        print("\n✅ Successfully converted database and all tables to utf8mb4!")
        print("Bengali text will now be correctly stored and retrieved.")
    except Exception as e:
        print(f"\n❌ An error occurred during conversion: {e}")

if __name__ == '__main__':
    run()
