"""
Test script for bulk shot creation project consistency validation
Tests the enhanced bulk shot creation with project validation
"""
import requests
import json

BASE_URL = "http://localhost:8000"

# Test credentials
LOGIN_DATA = {
    "email": "admin@vfx.com",
    "password": "admin123"
}


def login():
    """Login and get access token"""
    response = requests.post(f"{BASE_URL}/auth/login", json=LOGIN_DATA)
    if response.status_code == 200:
        return response.json()["access_token"]
    else:
        print(f"Login failed: {response.status_code}")
        return None


def test_bulk_shot_project_validation():
    """Test bulk shot creation with project validation"""
    print("=== Test: Bulk Shot Creation Project Validation ===\n")
    
    token = login()
    if not token:
        return
    
    headers = {"Authorization": f"Bearer {token}"}
    episode_id = 1  # Assuming this exists
    
    # Test 1: Valid bulk shot creation
    print("1. Testing valid bulk shot creation...")
    bulk_data = {
        "name_prefix": "TEST_BULK_",
        "shot_count": 3,
        "start_number": 100,
        "number_padding": 3,
        "frame_start": 1001,
        "frame_end": 1100,
        "description_template": "Test shot {shot_name} for validation",
        "create_default_tasks": True
    }
    
    response = requests.post(
        f"{BASE_URL}/shots/bulk?episode_id={episode_id}",
        headers=headers,
        json=bulk_data
    )
    
    print(f"   Status: {response.status_code}")
    if response.status_code == 201:
        result = response.json()
        print(f"   ✓ Success: {result['message']}")
        print(f"   ✓ Created shots: {len(result['created_shots'])}")
        print(f"   ✓ All shots have same project_id: {all(shot['project_id'] == result['created_shots'][0]['project_id'] for shot in result['created_shots'])}")
        
        # Store project_id for later tests
        project_id = result['created_shots'][0]['project_id']
        print(f"   ✓ Project ID: {project_id}")
        
        print(f"\n   Shot names created:")
        for shot in result['created_shots']:
            print(f"     - {shot['name']} (ID: {shot['id']}, Project: {shot['project_id']})")
    else:
        print(f"   ✗ Error: {response.json()}")
        return
    
    # Test 2: Duplicate name validation within project
    print("\n2. Testing duplicate name validation...")
    duplicate_data = {
        "name_prefix": "TEST_BULK_",
        "shot_count": 2,
        "start_number": 100,  # Same as above - should conflict
        "number_padding": 3,
        "frame_start": 1001,
        "frame_end": 1100,
        "create_default_tasks": False
    }
    
    response = requests.post(
        f"{BASE_URL}/shots/bulk?episode_id={episode_id}",
        headers=headers,
        json=duplicate_data
    )
    
    print(f"   Status: {response.status_code}")
    if response.status_code == 400:
        error = response.json()
        print(f"   ✓ Correctly rejected duplicate names: {error['detail']}")
    else:
        print(f"   ✗ Should have rejected duplicate names: {response.json()}")
    
    # Test 3: Internal duplicate validation
    print("\n3. Testing internal duplicate validation...")
    internal_duplicate_data = {
        "name_prefix": "DUP_",
        "shot_count": 3,
        "start_number": 1,
        "number_padding": 1,  # This will create DUP_1, DUP_2, DUP_3 - no duplicates
        "frame_start": 1001,
        "frame_end": 1100,
        "create_default_tasks": False
    }
    
    response = requests.post(
        f"{BASE_URL}/shots/bulk?episode_id={episode_id}",
        headers=headers,
        json=internal_duplicate_data
    )
    
    print(f"   Status: {response.status_code}")
    if response.status_code == 201:
        result = response.json()
        print(f"   ✓ No internal duplicates - created successfully: {result['message']}")
    else:
        print(f"   ✗ Unexpected error: {response.json()}")
    
    # Test 4: Frame range validation
    print("\n4. Testing frame range validation...")
    invalid_frame_data = {
        "name_prefix": "FRAME_",
        "shot_count": 1,
        "start_number": 1,
        "number_padding": 3,
        "frame_start": 1100,
        "frame_end": 1001,  # Invalid: end < start
        "create_default_tasks": False
    }
    
    response = requests.post(
        f"{BASE_URL}/shots/bulk?episode_id={episode_id}",
        headers=headers,
        json=invalid_frame_data
    )
    
    print(f"   Status: {response.status_code}")
    if response.status_code == 400:
        error = response.json()
        print(f"   ✓ Correctly rejected invalid frame range: {error['detail']}")
    else:
        print(f"   ✗ Should have rejected invalid frame range: {response.json()}")
    
    # Test 5: Project consistency verification
    print("\n5. Testing project consistency...")
    consistency_data = {
        "name_prefix": "CONSISTENCY_",
        "shot_count": 5,
        "start_number": 1,
        "number_padding": 2,
        "frame_start": 1001,
        "frame_end": 1200,
        "create_default_tasks": True
    }
    
    response = requests.post(
        f"{BASE_URL}/shots/bulk?episode_id={episode_id}",
        headers=headers,
        json=consistency_data
    )
    
    print(f"   Status: {response.status_code}")
    if response.status_code == 201:
        result = response.json()
        project_ids = [shot['project_id'] for shot in result['created_shots']]
        all_same_project = len(set(project_ids)) == 1
        print(f"   ✓ All shots have same project_id: {all_same_project}")
        print(f"   ✓ Project ID: {project_ids[0] if project_ids else 'None'}")
        print(f"   ✓ Created {len(result['created_shots'])} shots with {result['created_tasks_count']} tasks")
    else:
        print(f"   ✗ Error: {response.json()}")
    
    print("\n=== Test Completed ===")


if __name__ == "__main__":
    test_bulk_shot_project_validation()