#!/usr/bin/env python3
"""
Utility script to verify store coordinates and calculate distances.
Helps identify incorrect coordinates in the database.
"""

from math import radians, sin, cos, sqrt, atan2

def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
    """Calculate the distance between two points on Earth using Haversine formula."""
    R = 6371.0  # Earth radius in kilometers
    
    lat1_rad = radians(lat1)
    lon1_rad = radians(lon1)
    lat2_rad = radians(lat2)
    lon2_rad = radians(lon2)
    
    dlat = lat2_rad - lat1_rad
    dlon = lon2_rad - lon1_rad
    
    a = sin(dlat / 2) ** 2 + cos(lat1_rad) * cos(lat2_rad) * sin(dlon / 2) ** 2
    c = 2 * atan2(sqrt(a), sqrt(1 - a))
    
    distance = R * c
    return distance


def verify_coordinates(user_lat: float, user_lon: float, store_lat: float, store_lon: float, store_name: str = "Store"):
    """Verify coordinates and provide Google Maps links."""
    print("=" * 80)
    print(f"COORDINATE VERIFICATION FOR: {store_name}")
    print("=" * 80)
    print()
    print(f"Your Location:")
    print(f"  Latitude:  {user_lat}")
    print(f"  Longitude: {user_lon}")
    print()
    print(f"Store Location:")
    print(f"  Latitude:  {store_lat}")
    print(f"  Longitude: {store_lon}")
    print()
    
    # Calculate distance
    distance = haversine_distance(user_lat, user_lon, store_lat, store_lon)
    print(f"Distance: {distance:.2f} km ({distance*1000:.0f} meters)")
    print()
    
    # Calculate coordinate differences
    lat_diff = store_lat - user_lat
    lon_diff = store_lon - user_lon
    print(f"Coordinate Differences:")
    print(f"  Latitude:  {lat_diff:.6f} degrees")
    print(f"  Longitude: {lon_diff:.6f} degrees")
    print()
    
    # Convert to approximate distances
    lat_km = lat_diff * 111
    lon_km = lon_diff * 111 * cos(radians(user_lat))
    print(f"Approximate distances:")
    print(f"  North-South: {abs(lat_km):.2f} km ({'NORTH' if lat_km > 0 else 'SOUTH'})")
    print(f"  East-West:   {abs(lon_km):.2f} km ({'EAST' if lon_km > 0 else 'WEST'})")
    print()
    
    # Generate Google Maps links
    print("=" * 80)
    print("GOOGLE MAPS LINKS:")
    print("=" * 80)
    print(f"Your location:")
    print(f"  https://www.google.com/maps?q={user_lat},{user_lon}")
    print()
    print(f"Store location:")
    print(f"  https://www.google.com/maps?q={store_lat},{store_lon}")
    print()
    print(f"Compare both locations:")
    print(f"  https://www.google.com/maps/dir/{user_lat},{user_lon}/{store_lat},{store_lon}")
    print()
    
    # Check if distance seems reasonable
    print("=" * 80)
    print("ANALYSIS:")
    print("=" * 80)
    if distance < 0.5:
        print("✅ Distance is reasonable for 'just after your road' (< 500m)")
    elif distance < 1.0:
        print("⚠️  Distance is close but might be slightly off (< 1km)")
    elif distance < 5.0:
        print("❌ Distance seems too large if store is 'just after your road' (1-5km)")
        print("   This suggests coordinates might be incorrect!")
        print()
        print("   Possible issues:")
        print("   - Coordinates were geocoded incorrectly from address")
        print("   - Coordinates were manually entered with an error")
        print("   - Latitude/longitude might be swapped")
        print("   - Wrong decimal precision or format")
    else:
        print("❌ Distance is very large (> 5km)")
        print("   Coordinates are likely incorrect!")
    print()
    print("=" * 80)
    print("RECOMMENDATIONS:")
    print("=" * 80)
    print()
    print("1. Open the Google Maps links above to verify the locations")
    print("2. Check if the store coordinates point to the correct location")
    print("3. If coordinates are wrong, get correct coordinates from Google Maps:")
    print("   - Right-click on the store location")
    print("   - Select 'What's here?'")
    print("   - Copy the coordinates (latitude, longitude)")
    print()
    print("4. Update store coordinates in database using the update store API:")
    print("   PUT /admin/stores/{store_id}")
    print("   Body: { 'latitude': <correct_lat>, 'longitude': <correct_lon> }")
    print()
    print("=" * 80)


if __name__ == "__main__":
    # Your coordinates
    user_lat = 24.901220587242335
    user_lon = 67.11548527924614
    
    # Store coordinates (from API)
    store_lat = 24.92179408181343
    store_lon = 67.1354512742636
    store_name = "naheed1"
    
    verify_coordinates(user_lat, user_lon, store_lat, store_lon, store_name)

