"""
Management command to load biotope codes from CSV file.
Usage: python manage.py load_biotope_codes /path/to/csv/file.csv
"""
import csv
from django.core.management.base import BaseCommand, CommandError
from habitats_and_biotopes.models import BiotopeCode


class Command(BaseCommand):
    help = 'Load biotope codes from CSV file'

    def add_arguments(self, parser):
        parser.add_argument('csv_file', type=str, help='Path to the CSV file')

    def handle(self, *args, **options):
        csv_file = options['csv_file']
        
        try:
            with open(csv_file, 'r', encoding='utf-8') as f:
                reader = csv.DictReader(f)
                
                # Clear existing data
                BiotopeCode.objects.all().delete()
                self.stdout.write(self.style.WARNING('Cleared existing biotope codes'))
                
                created_count = 0
                
                for row in reader:
                    level = int(row['Level']) if row['Level'] else None
                    title = row['Title'].strip() if row['Title'] else ''
                    
                    if not title:
                        continue
                    
                    # Extract code from the appropriate column based on level
                    code = None
                    
                    if level == 2:
                        code = row['Broad Habitat Code'].strip()
                    elif level == 3:
                        code = row['Habitat Complex Code'].strip()
                    elif level == 4:
                        code = row['Biotope Complex Code'].strip()
                    elif level == 5:
                        code = row['Biotope Code'].strip()
                    elif level == 6:
                        code = row['Sub-biotope Code'].strip()
                    
                    if not code:
                        continue
                    
                    # Determine parent code (remove last part)
                    parts = code.split('.')
                    parent_code = '.'.join(parts[:-1]) if len(parts) > 1 else None
                    
                    # Create or update the biotope code
                    biotope_code, created = BiotopeCode.objects.get_or_create(
                        code=code,
                        defaults={
                            'level': level,
                            'title': title,
                            'parent_code': parent_code,
                        }
                    )
                    
                    if not created:
                        # Update existing record
                        biotope_code.level = level
                        biotope_code.title = title
                        biotope_code.parent_code = parent_code
                        biotope_code.save()
                    
                    if created:
                        created_count += 1
                
                self.stdout.write(
                    self.style.SUCCESS(
                        f'Successfully loaded {created_count} biotope codes'
                    )
                )
                
        except FileNotFoundError:
            raise CommandError(f'CSV file not found: {csv_file}')
        except Exception as e:
            raise CommandError(f'Error loading CSV: {str(e)}')

