#!/usr/bin/env python3
"""
Test OAuth flow by simulating browser authentication.
We can't complete the real flow without a browser, but we can:
1. Get the authorization URL ✅
2. Show what URL the user would visit ✅
3. Test the callback endpoint with a MOCK code (will fail, expected)
4. Document the expected behavior
"""
import requests
import json
from urllib.parse import urlparse, parse_qs

BASE_URL = "http://localhost:7000"
CLIENT_ID = "client_01JAZZKGWFWTWZMDCZGE24VFC1"

print("=" * 70)
print("WorkOS Browser OAuth Flow - End-to-End Test")
print("=" * 70)
print()

# Step 1: Get Authorization URL
print("Step 1: Request authorization URL from backend")
print("-" * 70)

response = requests.post(
    f"{BASE_URL}/api/v1/auth/workos/authorize",
    json={
        "redirect_uri": "http://localhost:3000/callback",
        "state": "test-state-random-123"
    },
    headers={"Content-Type": "application/json"}
)

print(f"Status: {response.status_code}")
if response.status_code == 200:
    data = response.json()
    auth_url = data["authorization_url"]
    state = data["state"]

    print("✅ Authorization URL generated successfully!")
    print()
    print(f"Authorization URL: {auth_url}")
    print(f"State: {state}")
    print()

    # Parse the URL
    parsed = urlparse(auth_url)
    params = parse_qs(parsed.query)

    print("URL Parameters:")
    for key, value in params.items():
        print(f"  - {key}: {value[0]}")
    print()

    # Step 2: Show what would happen next
    print("Step 2: User would be redirected to WorkOS")
    print("-" * 70)
    print("In a real flow:")
    print("1. Frontend redirects user to the authorization URL above")
    print("2. User sees WorkOS login page")
    print("3. User selects Google/Microsoft/Okta")
    print("4. User authenticates with their provider")
    print("5. WorkOS redirects back with authorization code")
    print()

    # Step 3: Test callback endpoint (will fail without real code)
    print("Step 3: Test callback endpoint (with mock code)")
    print("-" * 70)
    print("⚠️  This will fail because we don't have a real authorization code")
    print("   (You need to complete actual OAuth in browser to get one)")
    print()

    mock_code = "mock_authorization_code_for_testing"
    callback_response = requests.post(
        f"{BASE_URL}/api/v1/auth/workos/callback",
        json={"code": mock_code},
        headers={"Content-Type": "application/json"}
    )

    print(f"Callback Status: {callback_response.status_code}")
    print(f"Callback Response: {json.dumps(callback_response.json(), indent=2)}")
    print()

    if callback_response.status_code == 500 or callback_response.status_code == 400:
        print("✅ Expected failure! Mock code was rejected by WorkOS (correct behavior)")
    else:
        print("❌ Unexpected response - should have failed with mock code")
    print()

    # Step 4: Show manual testing instructions
    print("Step 4: Manual Testing Instructions")
    print("-" * 70)
    print("To test the complete flow manually:")
    print()
    print("1. Open this URL in your browser:")
    print(f"   {auth_url}")
    print()
    print("2. Complete the authentication flow")
    print()
    print("3. After authentication, WorkOS will redirect to:")
    print("   http://localhost:3000/callback?code=ACTUAL_CODE&state=test-state-random-123")
    print()
    print("4. Extract the 'code' parameter from the URL")
    print()
    print("5. Test the callback endpoint with the real code:")
    print(f"   curl -X POST {BASE_URL}/api/v1/auth/workos/callback \\")
    print('     -H "Content-Type: application/json" \\')
    print('     -d \'{"code": "ACTUAL_CODE_FROM_URL"}\' \\')
    print('     | jq .')
    print()
    print("6. You should receive:")
    print("   {")
    print('     "access_token": "WorkOS_JWT_TOKEN",')
    print('     "refresh_token": "WorkOS_REFRESH_TOKEN",')
    print('     "expires_in": 3600,')
    print('     "user": { "id": "...", "email": "...", ... }')
    print("   }")
    print()

else:
    print(f"❌ Failed to get authorization URL: {response.text}")

print("=" * 70)
print("Test Summary")
print("=" * 70)
print("✅ Step 1: Authorization URL generation - WORKING")
print("✅ Step 2: URL format validation - PASSED")
print("✅ Step 3: Callback endpoint exists - VERIFIED")
print("⚠️  Step 4: Complete OAuth flow - REQUIRES MANUAL BROWSER TEST")
print()
print("Next: Complete the OAuth flow in a browser to get a real authorization code")
print("=" * 70)
