#!/usr/bin/env python3
"""
Recreate the database with proper schema and migrate existing data.
"""

import sqlite3
import os
from pathlib import Path

def backup_projects_data():
    """Backup existing projects data."""
    
    print("Backing up existing projects data...")
    
    db_path = "vfx_project_management.db"
    
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # Get all projects data
        cursor.execute("SELECT * FROM projects")
        projects = cursor.fetchall()
        
        # Get column names
        cursor.execute("PRAGMA table_info(projects)")
        columns = [col[1] for col in cursor.fetchall()]
        
        return projects, columns
        
    except Exception as e:
        print(f"Error backing up data: {e}")
        return [], []
    finally:
        if conn:
            conn.close()

def recreate_database():
    """Recreate the database with proper schema."""
    
    print("Recreating Database with Proper Schema")
    print("=" * 40)
    
    # Backup existing data
    projects_data, columns = backup_projects_data()
    print(f"Backed up {len(projects_data)} projects")
    
    # Remove old database
    db_path = "vfx_project_management.db"
    if os.path.exists(db_path):
        os.remove(db_path)
        print("Removed old database")
    
    # Import and create new database schema
    try:
        from database import engine, Base
        import models  # This imports all models
        
        # Create all tables with proper schema
        Base.metadata.create_all(bind=engine)
        print("Created new database schema")
        
        # Restore projects data if any
        if projects_data:
            print("Restoring projects data...")
            
            conn = sqlite3.connect(db_path)
            cursor = conn.cursor()
            
            for project in projects_data:
                # Map old data to new schema
                insert_sql = """
                INSERT INTO projects (
                    id, name, description, status, start_date, end_date,
                    created_at, updated_at, code_name, client_name, project_type,
                    frame_rate, data_drive_path, publish_storage_path,
                    delivery_image_resolution, delivery_movie_specs_by_department
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                """
                
                cursor.execute(insert_sql, project)
            
            conn.commit()
            conn.close()
            print(f"Restored {len(projects_data)} projects")
        
        print("✅ Database recreated successfully!")
        return True
        
    except Exception as e:
        print(f"❌ Error recreating database: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    recreate_database()