#!/usr/bin/env python3
"""
Test script to verify trip creator access functionality
Tests the specific issue where trip creators can't access their own trips
"""

import requests
import json
import time

BASE_URL = "http://localhost:8000"
FRONTEND_URL = "http://localhost:3002"

def test_trip_creator_access():
    """Test that trip creators can access their own trips"""
    print("🧪 Testing Trip Creator Access...")
    print("=" * 50)

    # Step 1: Create a trip as a creator
    trip_data = {
        "name": "Creator Access Test Trip",
        "creator_name": "Test Creator",
        "currency_code": "USD"
    }

    print("1. Creating trip as creator...")
    response = requests.post(f"{BASE_URL}/api/trips/", json=trip_data)
    assert response.status_code == 200

    trip = response.json()
    print(f"   ✅ Created trip '{trip['name']}' with ID {trip['id']}")
    print(f"   ✅ Share code: {trip['share_code']}")

    # Step 2: Verify trip exists and has creator as participant
    print("2. Verifying trip details...")
    response = requests.get(f"{BASE_URL}/api/trips/{trip['id']}")
    assert response.status_code == 200

    trip_details = response.json()
    print(f"   ✅ Trip has {len(trip_details['participants'])} participants")

    creator_found = False
    for participant in trip_details['participants']:
        if participant['name'] == 'Test Creator' and participant['is_creator']:
            creator_found = True
            print(f"   ✅ Creator found as participant: {participant['name']} (ID: {participant['id']})")
            break

    assert creator_found, "Creator not found as participant in trip"

    # Step 3: Test trip accessibility via share code
    print("3. Testing trip accessibility via share code...")
    response = requests.get(f"{BASE_URL}/api/trips/share/{trip['share_code']}")
    assert response.status_code == 200

    share_data = response.json()
    assert share_data['id'] == trip['id']
    print(f"   ✅ Trip accessible via share code: {share_data['name']}")

    # Step 4: Simulate frontend accessing the trip
    print("4. Testing frontend trip access...")
    response = requests.get(FRONTEND_URL)
    assert response.status_code == 200
    print("   ✅ Frontend is accessible")

    # Test trip page direct access (this would normally require identity)
    response = requests.get(f"{FRONTEND_URL}/trip/{trip['id']}")
    # Might redirect to join page if no identity stored
    print(f"   ✅ Trip page response: {response.status_code}")

    # Step 5: Test adding participant and identification
    print("5. Testing participant addition and identification...")

    # Add another participant
    participant_data = {"name": "Test Participant"}
    response = requests.post(
        f"{BASE_URL}/api/participants/{trip['id']}/participants",
        json=participant_data
    )
    assert response.status_code == 200

    new_participant = response.json()
    print(f"   ✅ Added participant: {new_participant['name']} (ID: {new_participant['id']})")

    # Test user identification for creator
    device_id = f"test_device_creator_{int(time.time())}"

    # Find the creator participant ID
    creator_participant = None
    for participant in trip_details['participants']:
        if participant['name'] == 'Test Creator' and participant['is_creator']:
            creator_participant = participant
            break

    assert creator_participant is not None, "Creator participant not found"

    response = requests.post(
        f"{BASE_URL}/api/auth/identify",
        params={
            "trip_id": trip['id'],
            "participant_id": creator_participant['id'],
            "device_id": device_id
        }
    )
    assert response.status_code == 200, f"Identification failed: {response.text}"

    result = response.json()
    print(f"   ✅ Creator identified: {result['participant_name']}")

    # Test user identification for regular participant
    device_id_2 = f"test_device_participant_{int(time.time())}"
    response = requests.post(
        f"{BASE_URL}/api/auth/identify",
        params={
            "trip_id": trip['id'],
            "participant_id": new_participant['id'],
            "device_id": device_id_2
        }
    )
    assert response.status_code == 200

    result = response.json()
    print(f"   ✅ Participant identified: {result['participant_name']}")

    print("\n🎉 Trip creator access test completed successfully!")
    print("✅ Creator can create trips and be identified")
    print("✅ Trip is accessible via API endpoints")
    print("✅ Multiple participants can be added and identified")
    print("✅ All basic functionality working correctly")

    return True

def test_multi_trip_creator_scenario():
    """Test a more complex multi-trip scenario"""
    print("\n🔄 Testing Multi-Trip Creator Scenario...")
    print("=" * 50)

    # Create first trip as creator
    trip1_data = {
        "name": "Multi Trip Test 1",
        "creator_name": "Multi Creator",
        "currency_code": "USD"
    }
    response = requests.post(f"{BASE_URL}/api/trips/", json=trip1_data)
    trip1 = response.json()
    print(f"1. ✅ Created trip 1: {trip1['name']} (ID: {trip1['id']})")

    # Create second trip as same creator
    trip2_data = {
        "name": "Multi Trip Test 2",
        "creator_name": "Multi Creator",
        "currency_code": "EUR"
    }
    response = requests.post(f"{BASE_URL}/api/trips/", json=trip2_data)
    trip2 = response.json()
    print(f"2. ✅ Created trip 2: {trip2['name']} (ID: {trip2['id']})")

    # Add participant to first trip
    participant_data = {"name": "Test Participant"}
    response = requests.post(
        f"{BASE_URL}/api/participants/{trip1['id']}/participants",
        json=participant_data
    )
    participant = response.json()
    print(f"3. ✅ Added participant to trip 1: {participant['name']}")

    # Verify both trips have creator as participant
    response1 = requests.get(f"{BASE_URL}/api/trips/{trip1['id']}")
    response2 = requests.get(f"{BASE_URL}/api/trips/{trip2['id']}")

    trip1_details = response1.json()
    trip2_details = response2.json()

    # Check creator in both trips
    creator_in_trip1 = any(p['name'] == 'Multi Creator' and p['is_creator'] for p in trip1_details['participants'])
    creator_in_trip2 = any(p['name'] == 'Multi Creator' and p['is_creator'] for p in trip2_details['participants'])

    assert creator_in_trip1, "Creator not found in trip 1"
    assert creator_in_trip2, "Creator not found in trip 2"
    print(f"4. ✅ Creator found in both trips")

    # Test identification for both trips
    device_id = f"multi_trip_device_{int(time.time())}"

    # Identify as creator for trip 1
    creator_participant_1 = next(p for p in trip1_details['participants'] if p['is_creator'])
    response = requests.post(
        f"{BASE_URL}/api/auth/identify",
        params={
            "trip_id": trip1['id'],
            "participant_id": creator_participant_1['id'],
            "device_id": device_id
        }
    )
    assert response.status_code == 200
    print(f"5. ✅ Identified as creator of trip 1")

    # Identify as participant in trip 2 (same device should work)
    creator_participant_2 = next(p for p in trip2_details['participants'] if p['is_creator'])
    response = requests.post(
        f"{BASE_URL}/api/auth/identify",
        params={
            "trip_id": trip2['id'],
            "participant_id": creator_participant_2['id'],
            "device_id": device_id
        }
    )
    assert response.status_code == 200
    print(f"6. ✅ Identified as creator of trip 2 with same device")

    print("\n🎉 Multi-trip creator scenario test completed!")
    print("✅ Same user can create multiple trips")
    print("✅ Creator identity works across multiple trips")
    print("✅ Device identification works consistently")

    return True

def main():
    """Main test runner"""
    print("🚀 Trip Creator Access Tests")
    print("=" * 60)

    try:
        # Test basic creator access
        test_trip_creator_access()

        # Test multi-trip scenario
        test_multi_trip_creator_scenario()

        print("\n" + "=" * 60)
        print("🎉 All creator access tests passed!")
        print("\n📋 Verified Functionality:")
        print("  • Trip creators can create trips")
        print("  • Creators are automatically added as participants")
        print("  • Trip access works via API endpoints")
        print("  • Multi-trip support for creators")
        print("  • Device identification works correctly")
        print("  • Participants can be added and identified")

        return 0

    except Exception as e:
        print(f"\n❌ Test failed with error: {e}")
        return 1

if __name__ == "__main__":
    exit(main())