import requests

# Configuration
BASE_URL = "http://localhost:8000"
EMAIL = "admin@example.com"
PASSWORD = "admin123"

def test_shot_task_creation():
    """Test creating a shot task via API"""
    
    # Login
    print("1. Logging in...")
    login_response = requests.post(
        f"{BASE_URL}/auth/login",
        data={"username": EMAIL, "password": PASSWORD},
        headers={"Content-Type": "application/x-www-form-urlencoded"}
    )
    
    if login_response.status_code != 200:
        print(f"❌ Login failed: {login_response.status_code}")
        print(login_response.text)
        return
    
    token = login_response.json()["access_token"]
    headers = {"Authorization": f"Bearer {token}"}
    print("✅ Login successful")
    
    # Get first shot
    print("\n2. Getting shots...")
    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(shots_response.text)
        return
    
    shots = shots_response.json()
    if not shots:
        print("❌ No shots found")
        return
    
    shot_id = shots[0]["id"]
    shot_name = shots[0]["name"]
    print(f"✅ Found shot: {shot_name} (ID: {shot_id})")
    
    # Create a task for the shot
    print(f"\n3. Creating 'layout' task for shot {shot_id}...")
    create_task_response = requests.post(
        f"{BASE_URL}/shots/{shot_id}/tasks?task_type=layout",
        headers=headers
    )
    
    if create_task_response.status_code == 201:
        task_data = create_task_response.json()
        print(f"✅ Task created successfully!")
        print(f"   Task ID: {task_data['task_id']}")
        print(f"   Task Type: {task_data['task_type']}")
        print(f"   Status: {task_data['status']}")
    elif create_task_response.status_code == 200:
        task_data = create_task_response.json()
        print(f"ℹ️  Task already exists")
        print(f"   Task ID: {task_data['task_id']}")
        print(f"   Task Type: {task_data['task_type']}")
        print(f"   Status: {task_data['status']}")
    else:
        print(f"❌ Failed to create task: {create_task_response.status_code}")
        print(create_task_response.text)
        return
    
    # Try creating the same task again (should return existing)
    print(f"\n4. Trying to create the same task again...")
    create_task_response2 = requests.post(
        f"{BASE_URL}/shots/{shot_id}/tasks?task_type=layout",
        headers=headers
    )
    
    if create_task_response2.status_code in [200, 201]:
        task_data = create_task_response2.json()
        print(f"✅ Returned existing task (as expected)")
        print(f"   Task ID: {task_data['task_id']}")
    else:
        print(f"❌ Unexpected response: {create_task_response2.status_code}")
        print(create_task_response2.text)
    
    print("\n✅ All tests passed!")

if __name__ == "__main__":
    test_shot_task_creation()
