"""
Debug script to check why admin is getting 403
"""
import requests
import json

BASE_URL = "http://localhost:8000"

# Try to login and access a shot
print("=" * 60)
print("Debugging Shot 403 Error")
print("=" * 60)

# Step 1: Login
print("\n1. Attempting login...")
login_response = requests.post(f"{BASE_URL}/auth/login", json={
    "email": "admin@vfx.com",
    "password": "admin123"
})

if login_response.status_code != 200:
    print(f"✗ Login failed: {login_response.status_code}")
    print(f"Response: {login_response.text}")
    exit(1)

print("✓ Login successful")
token = login_response.json()["access_token"]
user_data = login_response.json().get("user", {})
print(f"  User: {user_data.get('email')}")
print(f"  Role: {user_data.get('role')}")
print(f"  Is Admin: {user_data.get('is_admin')}")

headers = {"Authorization": f"Bearer {token}"}

# Step 2: Get shots list
print("\n2. Getting shots list...")
shots_response = requests.get(f"{BASE_URL}/shots/", headers=headers)

if shots_response.status_code != 200:
    print(f"✗ Failed to get shots: {shots_response.status_code}")
    print(f"Response: {shots_response.text}")
    exit(1)

shots = shots_response.json()
print(f"✓ Got {len(shots)} shots")

if not shots:
    print("No shots available to test")
    exit(0)

# Step 3: Try to get first shot detail
shot = shots[0]
shot_id = shot["id"]
print(f"\n3. Getting shot detail for shot ID: {shot_id}")
print(f"   Shot name: {shot.get('name')}")
print(f"   Episode ID: {shot.get('episode_id')}")

shot_detail_response = requests.get(f"{BASE_URL}/shots/{shot_id}", headers=headers)

print(f"\n4. Response:")
print(f"   Status Code: {shot_detail_response.status_code}")

if shot_detail_response.status_code == 200:
    print("✓ SUCCESS: Shot detail retrieved")
    detail = shot_detail_response.json()
    print(f"   Shot: {detail.get('name')}")
    print(f"   Frame range: {detail.get('frame_start')}-{detail.get('frame_end')}")
elif shot_detail_response.status_code == 403:
    print("✗ FAILED: 403 Forbidden")
    print(f"   Response: {shot_detail_response.text}")
    print("\n   This means the backend check_episode_access function is still blocking access")
    print("   Possible causes:")
    print("   - Backend not restarted after code change")
    print("   - User is_admin field is False in database")
    print("   - Different endpoint being called")
else:
    print(f"✗ FAILED: {shot_detail_response.status_code}")
    print(f"   Response: {shot_detail_response.text}")

# Step 5: Check user in database
print("\n5. Checking user in database...")
import sys
sys.path.insert(0, '.')
from database import SessionLocal
from models.user import User

db = SessionLocal()
try:
    db_user = db.query(User).filter(User.email == user_data.get('email')).first()
    if db_user:
        print(f"✓ User found in database")
        print(f"   Email: {db_user.email}")
        print(f"   Role: {db_user.role}")
        print(f"   is_admin: {db_user.is_admin}")
        
        if not db_user.is_admin:
            print("\n⚠ WARNING: User is_admin is False in database!")
            print("   This is why you're getting 403")
            print("   Run: python backend/migrate_admin_users.py")
    else:
        print("✗ User not found in database")
finally:
    db.close()
