import json
from django.core.management.base import BaseCommand
from extractly.models import SourceHtml
from django.core.serializers.json import DjangoJSONEncoder

class Command(BaseCommand):
    help = "Eksportuje wszystkie źródła HtmlNetworkSource do pliku JSON (domyślnie network_sources.json)"

    def add_arguments(self, parser):
        parser.add_argument(
            '--output', '-o',
            default='network_sources.json',
            help='Ścieżka do pliku wynikowego'
        )

    def handle(self, *args, **options):
        output_path = options['output']
        sources = SourceHtml.objects.select_related('source').all()
        data = []

        for s in sources:
            # Pola z NetworkSource (poziom 1)
            ns = s.source
            ns_dict = {
                'id': str(ns.id),
                'title': ns.title,
                'type': ns.type,
                'name': ns.name,
                'base_url': ns.base_url,
                'structure': ns.structure,
                'skip_when_less': ns.skip_when_less,
                'params': ns.params,
                'pagination': ns.pagination,
                'selectors': ns.selectors,
                'is_ai': ns.is_ai,
                'enabled': ns.enabled,
                'last_checked': ns.last_checked.isoformat() if ns.last_checked else None,
                'last_status': ns.last_status,
                'created_at': ns.created_at.isoformat() if ns.created_at else None,
            }

            # Pola z HtmlNetworkSource (poziom 2)
            html_dict = {
                'type': s.type,
                'title': s.title,
                'name': s.name,
                'actions': s.actions,
                'selectors': s.selectors,
            }

            data.append({
                "network_source": ns_dict,
                "html_config": html_dict,
            })

        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=2, ensure_ascii=False, cls=DjangoJSONEncoder)

        self.stdout.write(self.style.SUCCESS(
            f"Wyeksportowano {len(data)} HtmlNetworkSource do pliku {output_path}"
        ))
