"""
Debug script to test county determination with POI data from the Streamlit UI.
Run this script after encountering a 'Could not determine counties for the POIs'
error in the Streamlit UI.
"""
import os
import sys
import json
import logging
from pathlib import Path

# Set up logging to include debug messages
logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
    handlers=[
        logging.FileHandler("debug_county_lookup.log"),
        logging.StreamHandler()
    ]
)

# Add parent directory to path so we can import socialmapper modules
sys.path.insert(0, str(Path(__file__).parent))

from socialmapper.counties import get_county_fips_from_point, get_counties_from_pois

def test_with_direct_coordinates():
    """Try a direct test with coordinates in North Carolina."""
    print("\n=== Testing direct coordinates (Fuquay-Varina, NC) ===")
    test_lat = 35.584
    test_lon = -78.800
    print(f"Testing coordinates: ({test_lat}, {test_lon})")
    
    try:
        state_fips, county_fips = get_county_fips_from_point(test_lat, test_lon)
        if state_fips and county_fips:
            print(f"✅ Census API found county: State FIPS {state_fips}, County FIPS {county_fips}")
        else:
            print(f"❌ Census API could not determine county for coordinates.")
    except Exception as e:
        print(f"❌ Error determining county: {e}")
    
    # Create a simple POI structure and test get_counties_from_pois
    test_poi_data = {
        "pois": [
            {
                "id": "test1",
                "name": "Test Location",
                "lat": test_lat,
                "lon": test_lon,
                "tags": {}
            }
        ]
    }
    
    try:
        counties = get_counties_from_pois(test_poi_data, include_neighbors=True)
        if counties:
            print(f"✅ Found {len(counties)} counties (including neighbors)")
            for i, (state_fips, county_fips) in enumerate(counties[:5]):
                print(f"  - County {i+1}: State FIPS {state_fips}, County FIPS {county_fips}")
        else:
            print("❌ No counties found")
    except Exception as e:
        print(f"❌ Error getting counties: {e}")

def test_with_cached_poi_data():
    """Test with POI data from the UI, if it exists."""
    # Try to find the most recent POI data generated by the UI
    poi_files = []
    for root, dirs, files in os.walk("output/pois"):
        for file in files:
            if file.endswith('.json'):
                poi_files.append(os.path.join(root, file))
    
    if not poi_files:
        print("\n❌ No POI data files found in output/pois directory")
        return
    
    # Get the most recently modified file
    most_recent = max(poi_files, key=os.path.getmtime)
    print(f"\n=== Testing with most recent POI data: {most_recent} ===")
    
    try:
        with open(most_recent, 'r') as f:
            poi_data = json.load(f)
        
        print(f"Loaded POI data with keys: {list(poi_data.keys())}")
        pois = poi_data.get('pois', [])
        print(f"Found {len(pois)} POIs")
        
        if pois:
            print("\nSample POI data:")
            sample_poi = pois[0]
            for key, value in sample_poi.items():
                if key != 'tags':  # Skip tags for brevity
                    print(f"  {key}: {value}")
            
            # Print coordinates for first 3 POIs
            print("\nFirst 3 POI coordinates:")
            for i, poi in enumerate(pois[:3]):
                lat = poi.get('lat')
                lon = poi.get('lon')
                if lat is not None and lon is not None:
                    print(f"  POI {i+1}: ({lat}, {lon})")
                else:
                    print(f"  POI {i+1}: Missing coordinates!")
            
            # Test county determination
            print("\nTesting county determination:")
            try:
                counties = get_counties_from_pois(poi_data, include_neighbors=True)
                if counties:
                    print(f"✅ Found {len(counties)} counties (including neighbors)")
                    for i, (state_fips, county_fips) in enumerate(counties[:5]):
                        print(f"  - County {i+1}: State FIPS {state_fips}, County FIPS {county_fips}")
                else:
                    print("❌ No counties found")
            except Exception as e:
                print(f"❌ Error getting counties: {e}")
        else:
            print("❌ No POIs found in the data")
    except Exception as e:
        print(f"❌ Error processing POI data file: {e}")

if __name__ == "__main__":
    print("=== County Determination Debug Tool ===")
    
    # Test with direct coordinates first
    test_with_direct_coordinates()
    
    # Try to test with cached POI data from UI
    test_with_cached_poi_data()
    
    print("\nCompleted debugging tests. Check debug_county_lookup.log for details.") 