"""
Test script for task status endpoint access control
"""
import requests
import json

BASE_URL = "http://localhost:8000"

def test_artist_access_control():
    """Test that artists can only access projects they're members of"""
    
    # Login as artist
    login_response = requests.post(
        f"{BASE_URL}/auth/login",
        json={
            "email": "artist@vfx.com",
            "password": "artist123"
        }
    )
    
    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 as artist successful")
    
    # Get list of all projects (as admin to see all)
    admin_login = requests.post(
        f"{BASE_URL}/auth/login",
        json={
            "email": "admin@vfx.com",
            "password": "admin123"
        }
    )
    admin_token = admin_login.json()["access_token"]
    admin_headers = {"Authorization": f"Bearer {admin_token}"}
    
    projects_response = requests.get(
        f"{BASE_URL}/projects/",
        headers=admin_headers
    )
    
    if projects_response.status_code != 200:
        print(f"❌ Failed to get projects: {projects_response.status_code}")
        return
    
    projects = projects_response.json()
    if len(projects) < 1:
        print("❌ Need at least 1 project for testing")
        return
    
    project_id = projects[0]["id"]
    print(f"✅ Testing with project ID: {project_id}")
    
    # Check if artist is a member of this project
    members_response = requests.get(
        f"{BASE_URL}/projects/{project_id}/members",
        headers=admin_headers
    )
    
    if members_response.status_code != 200:
        print(f"❌ Failed to get project members: {members_response.status_code}")
        return
    
    members = members_response.json()
    
    # Get artist user ID
    user_response = requests.get(
        f"{BASE_URL}/users/me",
        headers=headers
    )
    artist_user_id = user_response.json()["id"]
    
    is_member = any(m["user_id"] == artist_user_id for m in members)
    
    # Test access to task statuses
    print(f"\n--- Testing artist access (is_member: {is_member}) ---")
    response = requests.get(
        f"{BASE_URL}/projects/{project_id}/task-statuses",
        headers=headers
    )
    
    print(f"Status Code: {response.status_code}")
    
    if is_member:
        # Artist should have access
        if response.status_code == 200:
            print("✅ Artist correctly has access to project task statuses")
            data = response.json()
            print(f"✅ Retrieved {len(data['system_statuses'])} system statuses")
            print(f"✅ Retrieved {len(data['statuses'])} custom statuses")
        else:
            print(f"❌ Artist should have access but got {response.status_code}")
            print(response.text)
    else:
        # Artist should NOT have access
        if response.status_code == 403:
            print("✅ Artist correctly denied access to non-member project")
            print(f"Response: {response.json()}")
        else:
            print(f"❌ Expected 403 Forbidden but got {response.status_code}")
            print(response.text)


def test_coordinator_access():
    """Test that coordinators can access all projects"""
    
    # Login as coordinator (admin is also a coordinator)
    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(login_response.text)
        return
    
    token = login_response.json()["access_token"]
    headers = {"Authorization": f"Bearer {token}"}
    
    print("\n✅ Login as coordinator successful")
    
    # Get first project
    projects_response = requests.get(
        f"{BASE_URL}/projects/",
        headers=headers
    )
    
    if projects_response.status_code != 200:
        print(f"❌ Failed to get projects: {projects_response.status_code}")
        return
    
    projects = projects_response.json()
    if not projects:
        print("❌ No projects found")
        return
    
    project_id = projects[0]["id"]
    print(f"✅ Testing with project ID: {project_id}")
    
    # Test access to task statuses
    print(f"\n--- Testing coordinator access ---")
    response = requests.get(
        f"{BASE_URL}/projects/{project_id}/task-statuses",
        headers=headers
    )
    
    print(f"Status Code: {response.status_code}")
    
    if response.status_code == 200:
        print("✅ Coordinator correctly has access to project task statuses")
        data = response.json()
        print(f"✅ Retrieved {len(data['system_statuses'])} system statuses")
        print(f"✅ Retrieved {len(data['statuses'])} custom statuses")
    else:
        print(f"❌ Coordinator should have access but got {response.status_code}")
        print(response.text)


if __name__ == "__main__":
    test_artist_access_control()
    test_coordinator_access()
