#!/usr/bin/env python3
"""
Script to create comprehensive example data for the VFX project management system.
This includes episodes, assets, and project members for the Dragon Quest project.
"""

import sqlite3
import json
from datetime import date, datetime
from pathlib import Path

def get_database_path():
    """Get the database path."""
    possible_paths = [
        "vfx_project_management.db",
        "database.db"
    ]
    
    for path in possible_paths:
        if Path(path).exists():
            return path
    
    return "vfx_project_management.db"

def create_example_episodes(cursor, project_id):
    """Create example episodes for the project."""
    
    episodes_data = [
        {
            "name": "The Dragon's Awakening",
            "episode_number": 1,
            "description": "Opening sequence where the ancient dragon awakens from its thousand-year slumber. Features extensive particle effects, environmental destruction, and creature animation.",
            "status": "in_progress"
        },
        {
            "name": "The Quest Begins",
            "episode_number": 2,
            "description": "Heroes embark on their journey through magical forests and mystical landscapes. Requires complex environment work and magical effect sequences.",
            "status": "planning"
        },
        {
            "name": "Battle of the Crystal Caves",
            "episode_number": 3,
            "description": "Epic battle sequence in underground crystal caves with magical creatures. Heavy focus on lighting effects, crystal simulations, and creature interactions.",
            "status": "planning"
        },
        {
            "name": "The Final Confrontation",
            "episode_number": 4,
            "description": "Climactic battle between heroes and the dragon. Most VFX-intensive episode featuring fire effects, destruction, magical spells, and complex creature animation.",
            "status": "planning"
        }
    ]
    
    episode_ids = []
    current_time = datetime.now().isoformat()
    
    for episode_data in episodes_data:
        # Check if episode already exists
        cursor.execute("""
            SELECT id FROM episodes 
            WHERE project_id = ? AND episode_number = ?
        """, (project_id, episode_data["episode_number"]))
        
        existing_episode = cursor.fetchone()
        if existing_episode:
            episode_ids.append(existing_episode[0])
            continue
        
        insert_query = """
        INSERT INTO episodes (
            project_id, name, episode_number, description, status,
            created_at, updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?)
        """
        
        cursor.execute(insert_query, (
            project_id,
            episode_data["name"],
            episode_data["episode_number"],
            episode_data["description"],
            episode_data["status"],
            current_time,
            current_time
        ))
        
        episode_ids.append(cursor.lastrowid)
    
    return episode_ids

def create_example_assets(cursor, project_id):
    """Create example assets for the project."""
    
    assets_data = [
        {
            "name": "Ancient Dragon",
            "category": "characters",
            "description": "Main antagonist dragon character with detailed scales, wings, and fire-breathing capabilities. Requires complex rigging and animation systems.",
            "status": "in_progress"
        },
        {
            "name": "Hero Character - Warrior",
            "category": "characters", 
            "description": "Main protagonist warrior character with armor, weapons, and facial animation capabilities.",
            "status": "completed"
        },
        {
            "name": "Hero Character - Mage",
            "category": "characters",
            "description": "Magical character with spell-casting animations and mystical effects integration.",
            "status": "in_progress"
        },
        {
            "name": "Crystal Cave Environment",
            "category": "sets",
            "description": "Underground cave system with glowing crystals, stalactites, and magical lighting effects.",
            "status": "in_progress"
        },
        {
            "name": "Enchanted Forest",
            "category": "sets",
            "description": "Magical forest environment with animated trees, floating particles, and dynamic lighting.",
            "status": "not_started"
        },
        {
            "name": "Dragon's Lair",
            "category": "sets",
            "description": "Massive cave environment where the dragon resides, featuring treasure piles and ancient architecture.",
            "status": "not_started"
        },
        {
            "name": "Excalibur Sword",
            "category": "props",
            "description": "Legendary sword with magical glow effects and particle systems.",
            "status": "approved"
        },
        {
            "name": "Magic Staff",
            "category": "props",
            "description": "Mage's staff with crystal orb and magical energy effects.",
            "status": "in_progress"
        },
        {
            "name": "Dragon Armor Set",
            "category": "props",
            "description": "Protective armor made from dragon scales with metallic and organic textures.",
            "status": "not_started"
        },
        {
            "name": "Dragon Wings",
            "category": "props",
            "description": "Detailed dragon wing assets for close-up shots and animation reference.",
            "status": "in_progress"
        },
        {
            "name": "Flying Carpet",
            "category": "vehicles",
            "description": "Magical flying carpet for transportation sequences with cloth simulation.",
            "status": "completed"
        },
        {
            "name": "War Chariot",
            "category": "vehicles",
            "description": "Battle chariot for epic combat sequences with destruction capabilities.",
            "status": "not_started"
        }
    ]
    
    asset_ids = []
    current_time = datetime.now().isoformat()
    
    for asset_data in assets_data:
        # Check if asset already exists
        cursor.execute("""
            SELECT id FROM assets 
            WHERE project_id = ? AND name = ?
        """, (project_id, asset_data["name"]))
        
        existing_asset = cursor.fetchone()
        if existing_asset:
            asset_ids.append(existing_asset[0])
            continue
        
        insert_query = """
        INSERT INTO assets (
            project_id, name, category, description, status,
            created_at, updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?)
        """
        
        cursor.execute(insert_query, (
            project_id,
            asset_data["name"],
            asset_data["category"],
            asset_data["description"],
            asset_data["status"],
            current_time,
            current_time
        ))
        
        asset_ids.append(cursor.lastrowid)
    
    return asset_ids

def create_example_data():
    """Create comprehensive example data for the VFX project."""
    
    print("Creating Example VFX Project Data")
    print("=" * 40)
    
    db_path = get_database_path()
    print(f"Using database: {db_path}")
    
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # Get the Dragon Quest project ID
        cursor.execute("SELECT id FROM projects WHERE code_name = 'DRAGON_QUEST_2024'")
        project_result = cursor.fetchone()
        
        if not project_result:
            print("❌ Dragon Quest project not found. Please run create_example_project.py first.")
            return False
        
        project_id = project_result[0]
        print(f"✅ Found Dragon Quest project (ID: {project_id})")
        
        # Create episodes
        print("\n📺 Creating example episodes...")
        episode_ids = create_example_episodes(cursor, project_id)
        print(f"✅ Created/found {len(episode_ids)} episodes")
        
        # Create assets
        print("\n🎨 Creating example assets...")
        asset_ids = create_example_assets(cursor, project_id)
        print(f"✅ Created/found {len(asset_ids)} assets")
        
        # Commit all changes
        conn.commit()
        
        # Show summary
        print(f"\n📊 Summary:")
        print(f"   Project: Dragon Quest: The Awakening")
        print(f"   Episodes: {len(episode_ids)}")
        print(f"   Assets: {len(asset_ids)}")
        
        # Show episode breakdown
        cursor.execute("""
            SELECT name, episode_number, status 
            FROM episodes 
            WHERE project_id = ? 
            ORDER BY episode_number
        """, (project_id,))
        
        episodes = cursor.fetchall()
        print(f"\n📺 Episodes:")
        for episode in episodes:
            status_emoji = {"not_started": "⏳", "planning": "📋", "in_progress": "🎬", "completed": "✅"}
            print(f"   {status_emoji.get(episode[2], '❓')} Episode {episode[1]}: {episode[0]} ({episode[2].replace('_', ' ').title()})")
        
        # Show asset breakdown by category
        cursor.execute("""
            SELECT category, COUNT(*) as count
            FROM assets 
            WHERE project_id = ? 
            GROUP BY category
            ORDER BY count DESC
        """, (project_id,))
        
        asset_categories = cursor.fetchall()
        print(f"\n🎨 Assets by Category:")
        category_emojis = {"characters": "👤", "sets": "🌍", "props": "⚔️", "vehicles": "🚗"}
        for category, count in asset_categories:
            emoji = category_emojis.get(category, "📦")
            print(f"   {emoji} {category.title()}: {count}")
        
        # Show asset status breakdown
        cursor.execute("""
            SELECT status, COUNT(*) as count
            FROM assets 
            WHERE project_id = ? 
            GROUP BY status
            ORDER BY count DESC
        """, (project_id,))
        
        asset_statuses = cursor.fetchall()
        print(f"\n📈 Asset Status:")
        status_emojis = {"not_started": "⏳", "planning": "📋", "in_progress": "🎬", "completed": "✅"}
        for status, count in asset_statuses:
            emoji = status_emojis.get(status, "❓")
            print(f"   {emoji} {status.replace('_', ' ').title()}: {count}")
        
        return True
        
    except sqlite3.Error as e:
        print(f"❌ Database error: {e}")
        if conn:
            conn.rollback()
        return False
    except Exception as e:
        print(f"❌ Unexpected error: {e}")
        if conn:
            conn.rollback()
        return False
    finally:
        if conn:
            conn.close()

if __name__ == "__main__":
    print("VFX Project Management - Example Data Creator")
    print("=" * 50)
    
    success = create_example_data()
    
    if success:
        print("\n🎬 Example data created successfully!")
        print("The Dragon Quest project now has realistic episodes and assets for testing.")
    else:
        print("\n❌ Failed to create example data.")