#!/usr/bin/env python
"""
Test script for ParkLocation model functionality
"""
from apps.parks.models import Park, ParkLocation, Company
import os
import django

# Setup Django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.django.test")
django.setup()


def test_park_location():
    print("🧪 Testing ParkLocation Model Functionality")
    print("=" * 50)

    # Create a test company (operator)
    operator, created = Company.objects.get_or_create(
        name="Test Theme Parks Inc",
        defaults={"slug": "test-theme-parks-inc", "roles": ["OPERATOR"]},
    )
    print(f"✅ Created operator: {operator.name}")

    # Create a test park
    park, created = Park.objects.get_or_create(
        name="Test Magic Kingdom",
        defaults={
            "slug": "test-magic-kingdom",
            "description": "A test theme park for location testing",
            "operator": operator,
        },
    )
    print(f"✅ Created park: {park.name}")

    # Create a park location
    location, created = ParkLocation.objects.get_or_create(
        park=park,
        defaults={
            "street_address": "1313 Disneyland Dr",
            "city": "Anaheim",
            "state": "California",
            "country": "USA",
            "postal_code": "92802",
            "highway_exit": "I-5 Exit 110B",
            "parking_notes": "Large parking structure available",
            "seasonal_notes": "Open year-round",
        },
    )
    print(f"✅ Created location: {location}")

    # Test coordinate setting
    print("\n🔍 Testing coordinate functionality:")
    location.set_coordinates(33.8121, -117.9190)  # Disneyland coordinates
    location.save()

    print(f"  Latitude: {location.latitude}")
    print(f"  Longitude: {location.longitude}")
    print(f"  Coordinates: {location.coordinates}")
    print(f"  Formatted Address: {location.formatted_address}")

    # Test Park model integration
    print("\n🔍 Testing Park model integration:")
    print(f"  Park formatted location: {park.formatted_location}")
    print(f"  Park coordinates: {park.coordinates}")

    # Create another location for distance testing
    operator2, created = Company.objects.get_or_create(
        name="Six Flags Entertainment",
        defaults={"slug": "six-flags-entertainment", "roles": ["OPERATOR"]},
    )

    park2, created = Park.objects.get_or_create(
        name="Six Flags Magic Mountain",
        defaults={
            "slug": "six-flags-magic-mountain",
            "description": "Another test theme park",
            "operator": operator2,
        },
    )

    location2, created = ParkLocation.objects.get_or_create(
        park=park2,
        defaults={"city": "Valencia", "state": "California", "country": "USA"},
    )
    # Six Flags Magic Mountain coordinates
    location2.set_coordinates(34.4244, -118.5971)
    location2.save()

    # Test distance calculation
    print("\n🔍 Testing distance calculation:")
    distance = location.distance_to(location2)
    if distance:
        print(f"  Distance between parks: {distance:.2f} km")
    else:
        print("  ❌ Distance calculation failed")

    # Test spatial indexing
    print("\n🔍 Testing spatial queries:")
    try:
        from django.contrib.gis.measure import D
        from django.contrib.gis.geos import Point

        # Find parks within 100km of a point
        # Same as Disneyland
        search_point = Point(-117.9190, 33.8121, srid=4326)
        nearby_locations = ParkLocation.objects.filter(
            point__distance_lte=(search_point, D(km=100))
        )
        print(f"  Found {nearby_locations.count()} parks within 100km")
        for loc in nearby_locations:
            print(f"    - {loc.park.name} in {loc.city}, {loc.state}")
    except Exception as e:
        print(f"  ⚠️  Spatial queries not fully functional: {e}")

    print("\n✅ ParkLocation model tests completed successfully!")
    return True


if __name__ == "__main__":
    try:
        test_park_location()
    except Exception as e:
        print(f"❌ Test failed: {e}")
        import traceback

        traceback.print_exc()
