"""
Debug script to check episode access issue
"""
import sqlite3

conn = sqlite3.connect('backend/vfx_project_management.db')
cursor = conn.cursor()

# Check if episode 2 exists
print("=== Checking Episode 2 ===")
cursor.execute('SELECT id, name, project_id FROM episodes WHERE id = 2')
episode = cursor.fetchone()
if episode:
    print(f"Episode found: ID={episode[0]}, Name={episode[1]}, Project ID={episode[2]}")
    project_id = episode[2]
    
    # Check if admin user is a member of this project
    print(f"\n=== Checking Project {project_id} Membership ===")
    cursor.execute('''
        SELECT u.id, u.email, u.role, pm.project_id 
        FROM users u
        LEFT JOIN project_members pm ON u.id = pm.user_id AND pm.project_id = ?
        WHERE u.email = "admin@vfx.com"
    ''', (project_id,))
    user_info = cursor.fetchone()
    print(f"User ID: {user_info[0]}, Email: {user_info[1]}, Role: {user_info[2]}, Project Member: {user_info[3]}")
    
    if user_info[3] is None:
        print(f"\n⚠️  User is NOT a member of project {project_id}")
        print("This is why the 403 error occurs!")
        
        # Add user to project
        print(f"\nAdding user to project {project_id}...")
        cursor.execute('''
            INSERT INTO project_members (user_id, project_id, department_role)
            VALUES (?, ?, NULL)
        ''', (user_info[0], project_id))
        conn.commit()
        print("✓ User added to project")
    else:
        print(f"\n✓ User is already a member of project {project_id}")
else:
    print("Episode 2 not found!")
    
    # List all episodes
    print("\n=== All Episodes ===")
    cursor.execute('SELECT id, name, project_id FROM episodes')
    for ep in cursor.fetchall():
        print(f"  Episode {ep[0]}: {ep[1]} (Project {ep[2]})")

conn.close()
