#!/usr/bin/env python3
"""
Basic test script to verify RideLocation and CompanyHeadquarters models work correctly.
"""
from apps.rides.models import Ride, RideLocation
from apps.parks.models import Company, CompanyHeadquarters
import os
import sys
import django

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


def test_company_headquarters():
    """Test CompanyHeadquarters model functionality"""
    print("Testing CompanyHeadquarters...")

    # Try to use an existing company or skip this test if none exist
    existing_company = Company.objects.first()
    if not existing_company:
        print("⚠️  No existing companies found, skipping CompanyHeadquarters test")
        return None, None

    # Check if headquarters already exist (use queryset lookup to avoid relying on a reverse attribute name)
    headquarters = CompanyHeadquarters.objects.filter(company=existing_company).first()
    if headquarters:
        print(f"✓ Found existing headquarters: {headquarters}")
    else:
        # Create headquarters for existing company
        headquarters = CompanyHeadquarters.objects.create(
            company=existing_company,
            city="Orlando",
            state_province="Florida",
            country="USA",
            street_address="123 Theme Park Blvd",
            postal_code="32801",
        )
        print(f"✓ Created new headquarters: {headquarters}")

    print(f"✓ Created headquarters: {headquarters}")
    print(f"✓ Location display: {headquarters.location_display}")
    print(f"✓ Formatted location: {headquarters.formatted_location}")

    return existing_company, headquarters


def test_ride_location():
    """Test RideLocation model functionality"""
    print("\nTesting RideLocation...")

    # First, we need a ride - let's check if any exist
    if Ride.objects.exists():
        ride = Ride.objects.first()
        # Safely access the ride's name in case static analysis or runtime sees None/no attribute.
        ride_name = getattr(ride, "name", None) if ride is not None else None
        if ride_name:
            print(f"✓ Using existing ride: {ride_name}")
        else:
            # Fall back to repr of the ride object to avoid AttributeError
            print(f"✓ Using existing ride: {ride!r}")
    else:
        print("! No rides found in database - skipping RideLocation test")
        return None, None

    # Create ride location
    ride_location = RideLocation.objects.create(
        ride=ride,
        park_area="Fantasyland",
        notes="General location information",
        entrance_notes="Queue entrance is to the left of the main attraction sign",
        accessibility_notes="Wheelchair accessible entrance available via side path",
    )

    print(f"✓ Created ride location: {ride_location}")
    print(f"✓ Has coordinates: {ride_location.has_coordinates}")

    # Test setting coordinates
    ride_location.set_coordinates(28.3772, -81.5707)  # Disney World coordinates
    ride_location.save()

    print(f"✓ Set coordinates: {ride_location.coordinates}")
    print(f"✓ Latitude: {ride_location.latitude}")
    print(f"✓ Longitude: {ride_location.longitude}")

    return ride, ride_location


def cleanup_test_data(company=None, headquarters=None, ride_location=None):
    """Clean up test data"""
    print("\nCleaning up test data...")

    if ride_location:
        ride_location.delete()
        print("✓ Deleted test ride location")

    if headquarters:
        headquarters.delete()
        print("✓ Deleted test headquarters")

    # Do not delete an existing company record discovered in the database.
    # Tests should avoid removing production/existing data. If a test created a Company
    # instance explicitly, add logic to delete it here (not implemented by default).


def main():
    """Run all tests"""
    print("=" * 50)
    print("Testing Location Models Implementation")
    print("=" * 50)

    try:
        # Test CompanyHeadquarters
        company, headquarters = test_company_headquarters()

        # Test RideLocation
        ride, ride_location = test_ride_location()

        print("\n" + "=" * 50)
        print("✅ ALL TESTS PASSED!")
        print(
            "✅ Both RideLocation and CompanyHeadquarters models are working correctly"
        )
        print("=" * 50)

        # Clean up
        cleanup_test_data(company, headquarters, ride_location)

    except Exception as e:
        print(f"\n❌ TEST FAILED: {e}")
        import traceback

        traceback.print_exc()
        return False

    return True


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
