import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from core.models import Voter, Tenant
from decimal import Decimal

# Ensure we have a tenant
tenant, _ = Tenant.objects.get_or_create(name="Test Tenant", slug="test-tenant")

# 1. Create a voter with no coordinates
voter = Voter.objects.create(
    tenant=tenant,
    first_name="Manual",
    last_name="Test",
    address_street="1600 Amphitheatre Parkway",
    city="Mountain View",
    state="CA",
    zip_code="94043"
)

print(f"Initial voter: {voter.first_name} {voter.last_name}")
print(f"Coordinates: {voter.latitude}, {voter.longitude}")

# 2. Simulate manual geocode (updating latitude/longitude before save)
manual_lat = Decimal("37.422476400")
manual_lon = Decimal("-122.084249900")

# Simulate what happens in voter_edit view
# The form instance will have the new coordinates from request.POST
voter.latitude = manual_lat
voter.longitude = manual_lon

print(f"Updating coordinates manually to: {voter.latitude}, {voter.longitude}")
voter.save()

# 3. Reload from DB and verify
voter.refresh_from_db()
print(f"After save, coordinates in DB: {voter.latitude}, {voter.longitude}")

if voter.latitude == manual_lat and voter.longitude == manual_lon:
    print("SUCCESS: Manual coordinates preserved.")
else:
    print("FAILURE: Manual coordinates overwritten or not saved.")
    
# 4. Now test if changing address but NOT coordinates triggers geocode (which might overwrite)
voter.address_street = "1 Infinite Loop"
voter.city = "Cupertino"
# Note: we are NOT changing latitude/longitude here, so coords_provided should be False in save()
print(f"Changing address to {voter.address_street} but keeping coordinates.")
voter.save()

voter.refresh_from_db()
print(f"After address change, coordinates in DB: {voter.latitude}, {voter.longitude}")
# It should have updated coordinates to Apple's HQ if geocoding worked, 
# OR at least it shouldn't be the old Google HQ coordinates if it triggered geocode.
# Actually, it SHOULD have triggered geocode.

if voter.latitude != manual_lat:
    print("SUCCESS: Auto-geocode triggered for address change.")
else:
    print("INFO: Auto-geocode might not have triggered or returned same coordinates (unlikely).")
