"""Heuristics for identifying parked or placeholder websites."""

from dataclasses import dataclass
from typing import Iterable, Optional


@dataclass
class ParkedDetectionResult:
    """Result of parked domain detection."""

    is_parked: bool
    indicator: Optional[str] = None


class ParkedDomainDetector:
    """Detect whether fetched website content corresponds to a parked domain."""

    PARKING_INDICATORS: tuple[str, ...] = (
        "this domain is for sale",
        "buy this domain",
        "domain for sale",
        "domain is for sale",
        "domain available",
        "premium domain",
        "coming soon",
        "under construction",
        "website coming soon",
        "under construction page",
        "domain parking",
        "parked domain",
        "powered by godaddy",
        "powered by sedo",
        "powered by dan.com",
        "sedo.com",
        "afternic",
        "parkingcrew",
        "this site is parked",
        "this domain has been purchased",
        "create your website with wordpress",
        "hello world!",
    )

    MIN_CONTENT_LENGTH = 40  # Very short pages are often placeholders

    def detect(
        self,
        *,
        title: Optional[str],
        description: Optional[str],
        body_snippet: Optional[str],
        extra_text: Optional[Iterable[str]] = None,
    ) -> ParkedDetectionResult:
        """
        Detect if the provided content corresponds to a parked domain.

        Args:
            title: Page title
            description: Meta description
            body_snippet: Visible body snippet
            extra_text: Additional strings to include in detection (e.g., H1 text)
        """
        text_parts = [
            title or "",
            description or "",
            body_snippet or "",
        ]

        if extra_text:
            text_parts.extend(filter(None, extra_text))

        combined = " ".join(text_parts).lower().strip()

        # Heuristic 1: keyword indicators
        for indicator in self.PARKING_INDICATORS:
            if indicator in combined:
                return ParkedDetectionResult(is_parked=True, indicator=indicator)

        # Heuristic 2: extremely short body content plus generic language
        body_length = len((body_snippet or "").strip())
        if body_length < self.MIN_CONTENT_LENGTH and self._looks_generic(combined):
            return ParkedDetectionResult(
                is_parked=True, indicator="generic_placeholder"
            )

        return ParkedDetectionResult(is_parked=False)

    @staticmethod
    def _looks_generic(text: str) -> bool:
        """Check for very generic placeholder phrases."""
        generic_markers = (
            "coming soon",
            "website coming soon",
            "site under construction",
            "hello world",
            "just another wordpress site",
        )
        return any(marker in text for marker in generic_markers)
