"""
Management command to reload Morizon parser configuration from JSON file into database.
"""
import json
from django.core.management.base import BaseCommand
from extractly.models import SourceManual


class Command(BaseCommand):
    help = 'Reload Morizon parser configuration from JSON file into database'

    def handle(self, *args, **options):
        config_path = 'manual_agregator/Config/morizon/Manual_config/morizon_manual.json'
        
        try:
            # Read the JSON file
            with open(config_path, 'r', encoding='utf-8') as f:
                config_data = json.load(f)
            
            # Find Morizon SourceManual record (ID=7)
            try:
                morizon_manual = SourceManual.objects.get(id=7, name='Morizon')
            except SourceManual.DoesNotExist:
                self.stdout.write(self.style.ERROR('Morizon SourceManual not found (ID=7)'))
                return
            
            # Update the selectors field
            morizon_manual.selectors = json.dumps(config_data, ensure_ascii=False)
            morizon_manual.save()
            
            self.stdout.write(self.style.SUCCESS(
                f'✓ Successfully reloaded Morizon configuration from {config_path}'
            ))
            self.stdout.write(f'  - Total fields: {len(config_data)}')
            self.stdout.write(f'  - Updated SourceManual ID: {morizon_manual.id}')
            
        except FileNotFoundError:
            self.stdout.write(self.style.ERROR(f'Configuration file not found: {config_path}'))
        except json.JSONDecodeError as e:
            self.stdout.write(self.style.ERROR(f'Invalid JSON in configuration file: {e}'))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'Error reloading configuration: {e}'))
