import sys
import asyncio
import json
from uuid import UUID
from django.core.management.base import BaseCommand, CommandError
from link_agregator.source_managment import scrape_all_sources
from extractly.models import SourceNetwork

class Command(BaseCommand):
    help = "Uruchamia scraper Playwright dla źródeł (po id lub name, wielkość liter nie ma znaczenia)"

    def add_arguments(self, parser):
        # Make source_id and source_name mutually exclusive
        group = parser.add_mutually_exclusive_group()
        group.add_argument('--source_id', type=str, default=None, help='UUID źródła (opcjonalnie)')
        group.add_argument('--source_name', type=str, default=None, help='Nazwa źródła (opcjonalnie, case-insensitive)')

        parser.add_argument('--params', type=str, default=None, help='Parametry w formacie JSON (opcjonalnie)')
        parser.add_argument('--headless', action='store_true', default=False, help="Uruchom bez UI (headless)")
        parser.add_argument('--mode', type=str, default="fetch", choices=["fetch", "check"],
                            help='Tryb działania: fetch (domyślnie) lub check (tylko status)')

    def handle(self, *args, **options):
        source_id_opt = options['source_id']
        source_name = options['source_name']
        params_raw = options['params']
        headless = options['headless']
        mode = options['mode']

        # Parse params JSON if provided
        params = None
        if params_raw:
            try:
                params = json.loads(params_raw)
            except Exception as e:
                raise CommandError(f"Nieprawidłowy JSON w --params: {e}")

        source_uuid = None

        # Case 1: source_id provided -> validate UUID
        if source_id_opt:
            try:
                source_uuid = UUID(source_id_opt)
            except ValueError:
                raise CommandError("Parametr --source_id nie jest poprawnym UUID.")

            # Validate that source exists
            if not SourceNetwork.objects.filter(id=source_uuid).exists():
                raise CommandError(f"Nie znaleziono źródła o ID {source_uuid}")

        # Case 2: source_name provided -> resolve to single ID
        elif source_name:
            qs = SourceNetwork.objects.filter(title__iexact=source_name)
            if not qs.exists():
                qs = SourceNetwork.objects.filter(title__icontains=source_name)
            if not qs.exists():
                raise CommandError(f"Nie znaleziono źródła o nazwie '{source_name}' (case-insensitive / partial).")
            if qs.count() > 1:
                self.stdout.write(self.style.WARNING(
                    f"Znaleziono wiele źródeł dla '{source_name}'. Wybrane pierwsze: {qs[0].title} (ID: {qs[0].id})"
                ))
            source_uuid = qs.first().id

        # Log start (no NOTICE style in Django)
        self.stdout.write(f"▶️ Start: source_id={source_uuid}, source_name={source_name}, params={params}, mode={mode}, headless={headless}")

        # Run the scraper
        asyncio.run(scrape_all_sources(source_id=source_uuid, params=params, mode=mode, headless=headless))

        self.stdout.write(self.style.SUCCESS("✅ Agregator zakończył działanie."))
