from django.core.management.base import BaseCommand
from django.db import transaction
from extractly.models import SourceManual, SourceNetwork


OTODOM_INACTIVE_RULES = [
    {
        "when": {
            "any": [
                {
                    "selector_exists_any": [
                        "div[data-cy='expired-ad-alert']",
                        "[data-testid='ad-not-available']",
                        "[data-cy='ads-not-available']",
                        "div:-soup-contains('Ogłoszenie wygasło')",
                        "div:-soup-contains('ogłoszenie jest już niedostępne')",
                    ]
                },
                {
                    "text_contains_any": [
                        "ogłoszenie wygasło",
                        "ogloszenie wygaslo",
                        "oferta została usunięta",
                        "ogłoszenie jest już niedostępne",
                        "ogloszenie jest juz niedostepne",
                        "nie znaleziono ogłoszenia",
                        "nie znaleziono ogloszenia",
                    ]
                }
            ]
        },
        "reason": "otodom_expired_banner_or_text"
    },
    {
        "when": {
            "any": [
                {"url_contains": "/nie-znaleziono"},
                {"url_contains": "/404"},
                {"url_contains": "ad-not-available"}
            ]
        },
        "reason": "url_404_like"
    }
]


class Command(BaseCommand):
    help = "Fix/Update inactive rules for Otodom in SourceManual to robust selectors and text checks."

    def add_arguments(self, parser):
        parser.add_argument("--source-name", default="Otodom", help="SourceNetwork.name of Otodom (default: Otodom)")

    @transaction.atomic
    def handle(self, *args, **options):
        # Django converts dashes to underscores in option names
        name = options.get("source_name") or options.get("source-name") or "Otodom"
        src = SourceNetwork.objects.filter(name__iexact=name).first()
        if not src:
            self.stderr.write(self.style.ERROR(f"SourceNetwork with name '{name}' not found."))
            return

        sm: SourceManual | None = getattr(src, "manual_data_source_fetcher", None)
        if not sm:
            self.stderr.write(self.style.ERROR("SourceManual not attached to this SourceNetwork."))
            return

        sm.inactive = OTODOM_INACTIVE_RULES
        sm.save(update_fields=["inactive"])
        self.stdout.write(self.style.SUCCESS("Updated Otodom inactive rules on SourceManual."))