#!/usr/bin/env python3
"""
Create a fresh database with proper schema and test data.
"""

import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

def create_fresh_database():
    """Create a fresh database with proper schema."""
    
    print("Creating Fresh Database")
    print("=" * 30)
    
    # Use a new database name
    new_db_name = "vfx_project_fresh.db"
    
    # Remove if exists
    if os.path.exists(new_db_name):
        os.remove(new_db_name)
        print(f"Removed existing {new_db_name}")
    
    # Update database configuration temporarily
    os.environ['DATABASE_URL'] = f"sqlite:///./{new_db_name}"
    
    try:
        # Import after setting environment variable
        from database import engine, Base
        import models  # This imports all models
        
        # Create all tables
        Base.metadata.create_all(bind=engine)
        print("✅ Created database schema")
        
        # Create admin user
        from database import get_db
        from models.user import User, UserRole
        from utils.auth import get_password_hash
        
        db = next(get_db())
        
        # Check if admin exists
        admin_user = db.query(User).filter(User.email == "admin@vfx.com").first()
        if not admin_user:
            admin_user = User(
                email="admin@vfx.com",
                password_hash=get_password_hash("admin123"),
                first_name="Admin",
                last_name="User",
                role=UserRole.COORDINATOR,
                is_admin=True,
                is_approved=True
            )
            db.add(admin_user)
            db.commit()
            print("✅ Created admin user")
        else:
            print("✅ Admin user already exists")
        
        # Create test projects
        from models.project import Project, ProjectStatus, ProjectType
        import json
        from datetime import datetime
        
        # Project 1
        project1 = Project(
            name="Test VFX Project",
            code_name="TEST_VFX_001",
            client_name="Test Studio",
            project_type=ProjectType.CINEMA,
            description="Test project for VFX management system",
            status=ProjectStatus.PLANNING,
            frame_rate=24.0,
            data_drive_path="/projects/test_vfx/data",
            publish_storage_path="/projects/test_vfx/publish",
            delivery_image_resolution="1920x1080",
            delivery_movie_specs_by_department=json.dumps({
                "layout": {"resolution": "1920x1080", "format": "mov", "codec": "h264", "quality": "medium"},
                "animation": {"resolution": "1920x1080", "format": "mov", "codec": "h264", "quality": "high"}
            })
        )
        
        # Project 2
        project2 = Project(
            name="Dragon Quest: The Awakening",
            code_name="DRAGON_QUEST_2024",
            client_name="Epic Fantasy Studios",
            project_type=ProjectType.CINEMA,
            description="A high-budget fantasy film featuring dragons and magic",
            status=ProjectStatus.IN_PROGRESS,
            frame_rate=24.0,
            data_drive_path="/projects/dragon_quest_2024/data",
            publish_storage_path="/projects/dragon_quest_2024/publish",
            delivery_image_resolution="4096x2160",
            delivery_movie_specs_by_department=json.dumps({
                "layout": {"resolution": "1920x1080", "format": "mov", "codec": "h264", "quality": "medium"},
                "animation": {"resolution": "2048x1080", "format": "mov", "codec": "h264", "quality": "high"},
                "lighting": {"resolution": "4096x2160", "format": "exr", "codec": None, "quality": "high"},
                "composite": {"resolution": "4096x2160", "format": "mov", "codec": "prores", "quality": "high"}
            })
        )
        
        db.add(project1)
        db.add(project2)
        db.commit()
        print("✅ Created test projects")
        
        # Rename to replace old database
        db.close()
        
        # Now replace the old database
        old_db = "vfx_project_management.db"
        if os.path.exists(old_db):
            os.remove(old_db)
        
        os.rename(new_db_name, old_db)
        print(f"✅ Replaced old database with fresh one")
        
        print("\n🎉 Fresh database created successfully!")
        print("Admin credentials: admin@vfx.com / admin123")
        
        return True
        
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    create_fresh_database()