#!/usr/bin/env python3
"""
Migration script to add technical specifications fields to the projects table.

This script adds the following columns to the projects table:
- frame_rate (FLOAT)
- data_drive_path (VARCHAR)
- publish_storage_path (VARCHAR)
- delivery_image_resolution (VARCHAR)
- delivery_movie_specs_by_department (JSON)

Usage:
    python migrate_project_technical_specs.py
"""

import sqlite3
import json
import sys
from pathlib import Path

# Default delivery movie specifications per department
DEFAULT_DELIVERY_MOVIE_SPECS = {
    "layout": {
        "resolution": "1920x1080",
        "format": "mov",
        "codec": "h264",
        "quality": "medium"
    },
    "animation": {
        "resolution": "1920x1080", 
        "format": "mov",
        "codec": "h264",
        "quality": "high"
    },
    "lighting": {
        "resolution": "2048x1080",
        "format": "exr",
        "codec": None,
        "quality": "high"
    },
    "composite": {
        "resolution": "2048x1080",
        "format": "mov",
        "codec": "prores",
        "quality": "high"
    }
}


def get_database_path():
    """Get the database path, trying multiple possible locations."""
    possible_paths = [
        "vfx_project_management.db",  # Primary database
        "database.db",
        "../vfx_project_management.db"
    ]
    
    for path in possible_paths:
        if Path(path).exists():
            return path
    
    # If no existing database found, use the default name
    return "vfx_project_management.db"


def check_column_exists(cursor, table_name, column_name):
    """Check if a column exists in a table."""
    cursor.execute(f"PRAGMA table_info({table_name})")
    columns = [column[1] for column in cursor.fetchall()]
    return column_name in columns


def migrate_database():
    """Add technical specifications columns to the projects table."""
    db_path = get_database_path()
    print(f"Using database: {db_path}")
    
    try:
        # Connect to the database
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # Check if projects table exists
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='projects'")
        if not cursor.fetchone():
            print("Projects table not found. Creating new database schema...")
            conn.close()
            return
        
        print("Adding technical specifications columns to projects table...")
        
        # Add technical specification columns if they don't exist
        columns_to_add = [
            ("frame_rate", "REAL"),
            ("data_drive_path", "VARCHAR"),
            ("publish_storage_path", "VARCHAR"),
            ("delivery_image_resolution", "VARCHAR"),
            ("delivery_movie_specs_by_department", "JSON")
        ]
        
        for column_name, column_type in columns_to_add:
            if not check_column_exists(cursor, "projects", column_name):
                print(f"Adding column: {column_name}")
                cursor.execute(f"ALTER TABLE projects ADD COLUMN {column_name} {column_type}")
            else:
                print(f"Column {column_name} already exists, skipping...")
        
        # Set default values for existing projects
        print("Setting default technical specifications for existing projects...")
        
        # Set default frame rate and image resolution
        cursor.execute("""
            UPDATE projects 
            SET frame_rate = 24.0, 
                delivery_image_resolution = '1920x1080'
            WHERE frame_rate IS NULL OR delivery_image_resolution IS NULL
        """)
        
        # Set default delivery movie specs for projects that don't have them
        default_specs_json = json.dumps(DEFAULT_DELIVERY_MOVIE_SPECS)
        cursor.execute("""
            UPDATE projects 
            SET delivery_movie_specs_by_department = ?
            WHERE delivery_movie_specs_by_department IS NULL
        """, (default_specs_json,))
        
        # Commit changes
        conn.commit()
        
        # Verify the migration
        cursor.execute("SELECT COUNT(*) FROM projects")
        project_count = cursor.fetchone()[0]
        print(f"Migration completed successfully! Updated {project_count} projects.")
        
        # Show sample of updated data
        cursor.execute("""
            SELECT id, name, frame_rate, delivery_image_resolution 
            FROM projects 
            LIMIT 3
        """)
        
        print("\nSample of updated projects:")
        for row in cursor.fetchall():
            print(f"  Project {row[0]}: {row[1]} - {row[2]} fps, {row[3]} resolution")
        
    except sqlite3.Error as e:
        print(f"Database error: {e}")
        if conn:
            conn.rollback()
        sys.exit(1)
    except Exception as e:
        print(f"Unexpected error: {e}")
        if conn:
            conn.rollback()
        sys.exit(1)
    finally:
        if conn:
            conn.close()


if __name__ == "__main__":
    print("VFX Project Management - Technical Specifications Migration")
    print("=" * 60)
    
    migrate_database()
    
    print("\nMigration completed successfully!")
    print("Technical specifications have been added to all projects.")