#!/usr/bin/env python
"""
Fix the django_session table issue by creating it if it doesn't exist.
This script should be run on the production server.

Usage:
    python fix_django_session.py
"""

import os
import sys
import django

# Setup Django environment
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wtlms.settings')
django.setup()

from django.db import connection

def fix_django_session_table():
    """Create the django_session table if it doesn't exist."""
    print("Checking for django_session table...")
    
    # Check if the table exists
    with connection.cursor() as cursor:
        cursor.execute("""
            SELECT name FROM sqlite_master 
            WHERE type='table' AND name='django_session';
        """)
        table_exists = cursor.fetchone() is not None
    
    if table_exists:
        print("django_session table already exists.")
        return
    
    print("django_session table doesn't exist. Creating it...")
    
    # Create the django_session table
    with connection.cursor() as cursor:
        cursor.execute("""
            CREATE TABLE "django_session" (
                "session_key" varchar(40) NOT NULL PRIMARY KEY,
                "session_data" text NOT NULL,
                "expire_date" datetime NOT NULL
            );
        """)
        
        # Create index
        cursor.execute("""
            CREATE INDEX "django_session_expire_date_a5c62663" 
            ON "django_session" ("expire_date");
        """)
    
    print("django_session table created successfully.")

if __name__ == "__main__":
    fix_django_session_table()
