import csv
import os
from django.core.management.base import BaseCommand
from django.conf import settings
from icict_attendance.models import ICICTRegistrant


class Command(BaseCommand):
    help = 'Import ICICT registrations from CSV file'

    def add_arguments(self, parser):
        parser.add_argument(
            '--file',
            type=str,
            default='icict_attendance/registrations.csv',
            help='Path to the CSV file relative to project root'
        )
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be imported without actually importing'
        )

    def handle(self, *args, **options):
        file_path = os.path.join(settings.BASE_DIR, options['file'])
        dry_run = options['dry_run']
        
        if not os.path.exists(file_path):
            self.stdout.write(
                self.style.ERROR(f'CSV file not found: {file_path}')
            )
            return
        
        imported_count = 0
        updated_count = 0
        skipped_count = 0
        
        with open(file_path, 'r', encoding='utf-8') as csvfile:
            reader = csv.DictReader(csvfile)
            
            for row_num, row in enumerate(reader, 1):
                # Handle BOM in CSV header and get ID field
                id_field = 'ID'
                if '\ufeffID' in row:
                    id_field = '\ufeffID'
                
                # Skip empty rows
                if not row.get(id_field) or not row.get(id_field).strip():
                    continue
                
                try:
                    registration_id = int(row[id_field])
                    name = row['Name'].strip()
                    email = row['Email Address'].strip()
                    affiliation = row.get('Affiliation', '').strip() or None
                    phone_number = row.get('Phone Number', '').strip() or None
                    address = row.get('Address', '').strip() or None
                    payment_status_raw = row.get('Registration state', '').strip().lower()
                    
                    # Map payment status
                    if payment_status_raw == 'completed':
                        payment_status = 'completed'
                    else:
                        payment_status = 'awaiting_payment'
                    
                    if dry_run:
                        self.stdout.write(
                            f"Would import: {name} (ID: {registration_id}) - {payment_status}"
                        )
                        imported_count += 1
                        continue
                    
                    # Check if registrant already exists
                    registrant, created = ICICTRegistrant.objects.get_or_create(
                        registration_id=registration_id,
                        defaults={
                            'name': name,
                            'email': email,
                            'affiliation': affiliation,
                            'phone_number': phone_number,
                            'address': address,
                            'payment_status': payment_status,
                        }
                    )
                    
                    if created:
                        imported_count += 1
                        self.stdout.write(
                            self.style.SUCCESS(f'Imported: {name} (ID: {registration_id})')
                        )
                    else:
                        # Update existing record if data has changed
                        updated = False
                        if registrant.name != name:
                            registrant.name = name
                            updated = True
                        if registrant.email != email:
                            registrant.email = email
                            updated = True
                        if registrant.payment_status != payment_status:
                            registrant.payment_status = payment_status
                            updated = True
                        if registrant.affiliation != affiliation:
                            registrant.affiliation = affiliation
                            updated = True
                        if registrant.phone_number != phone_number:
                            registrant.phone_number = phone_number
                            updated = True
                        if registrant.address != address:
                            registrant.address = address
                            updated = True
                        
                        if updated:
                            registrant.save()
                            updated_count += 1
                            self.stdout.write(
                                self.style.WARNING(f'Updated: {name} (ID: {registration_id})')
                            )
                        else:
                            skipped_count += 1
                
                except ValueError as e:
                    self.stdout.write(
                        self.style.ERROR(f'Error processing row {row}: {e}')
                    )
                    continue
                except Exception as e:
                    self.stdout.write(
                        self.style.ERROR(f'Unexpected error processing row {row}: {e}')
                    )
                    continue
        
        # Summary
        if dry_run:
            self.stdout.write(
                self.style.SUCCESS(f'\nDry run completed. Would import {imported_count} registrants.')
            )
        else:
            self.stdout.write(
                self.style.SUCCESS(
                    f'\nImport completed:\n'
                    f'- Imported: {imported_count} new registrants\n'
                    f'- Updated: {updated_count} existing registrants\n'
                    f'- Skipped: {skipped_count} unchanged registrants'
                )
            )
