import django
import os
import sys
import json

def seed_india():
    from apps.master_data.models import Country, State, City

    # Create India country
    india, created = Country.objects.get_or_create(
        name="India",
        defaults={
            "iso2": "IN",
            "iso3": "IND",
            "phone_code": "+91",
            "region": "Asia",
            "subregion": "Southern Asia",
            "status": 1,
        }
    )
    if created:
        print("Created Country: India")
    else:
        print("Country India already exists.")

    # Load locations
    json_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "../frontend/public/data/india-locations.json")
    if not os.path.exists(json_path):
        # fallback path in case of execution differences
        json_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "frontend/public/data/india-locations.json")
        if not os.path.exists(json_path):
            print("Error: Could not locate india-locations.json")
            return

    with open(json_path, "r", encoding="utf-8") as f:
        locations = json.load(f)

    print(f"Loaded {len(locations)} locations from JSON.")

    states_cache = {}
    cities_to_create = []

    # Get existing states in DB to cache
    for state in State.objects.filter(country=india):
        states_cache[state.name] = state

    # Read distinct states first to create them
    unique_states = set(item["state"] for item in locations if item.get("state"))
    for state_name in unique_states:
        if state_name not in states_cache:
            state_obj = State.objects.create(
                name=state_name,
                country=india,
                country_code="IN"
            )
            states_cache[state_name] = state_obj

    print(f"Created/verified {len(states_cache)} states.")

    # Check existing cities to avoid duplicates
    existing_cities = set(
        City.objects.filter(country=india).values_list("name", "state__name")
    )

    for item in locations:
        city_name = item.get("name")
        state_name = item.get("state")
        if not city_name or not state_name:
            continue

        city_name = city_name.strip()
        state_name = state_name.strip()

        # Check duplicate
        if (city_name, state_name) in existing_cities:
            continue

        state_obj = states_cache.get(state_name)
        if not state_obj:
            continue

        cities_to_create.append(
            City(
                name=city_name,
                state=state_obj,
                country=india,
                country_code="IN"
            )
        )

    if cities_to_create:
        print(f"Inserting {len(cities_to_create)} cities...")
        # Bulk create cities in batches
        City.objects.bulk_create(cities_to_create, batch_size=1000)
        print("Cities insertion completed!")
    else:
        print("No new cities to insert.")

if __name__ == "__main__":
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.dev")
    django.setup()
    seed_india()
