import csv
from django.core.management.base import BaseCommand
from career.models import City, State

class Command(BaseCommand):
    help = 'Import cities from CSV and assign state by id'

    def handle(self, *args, **options):
        with open('/var/www/apihucms/City-2025-07-30.csv', newline='', encoding='utf-8') as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                city_name = row['city_name']
                state_id = int(row['state'])
                try:
                    state = State.objects.get(pk=state_id)
                    City.objects.get_or_create(name=city_name, state=state)
                except State.DoesNotExist:
                    self.stdout.write(self.style.WARNING(f'State id {state_id} not found for city {city_name}'))
        self.stdout.write(self.style.SUCCESS('Cities imported successfully.'))
