from datetime import datetime
from enum import StrEnum

from repo_core.base.models import DomainModel


class WebUrlStatus(StrEnum):
    """Lifecycle status for discovered URLs."""

    NEW = "NEW"
    QUEUED = "QUEUED"
    FETCHING = "FETCHING"
    FETCHED = "FETCHED"
    FAILED = "FAILED"


class WebUrlType(StrEnum):
    """Content type classification for discovered URLs."""

    FETCHABLE = "fetchable"
    DOWNLOADABLE = "downloadable"
    UNKNOWN = "unknown"

    @classmethod
    def _missing_(cls, value: object) -> "WebUrlType | None":
        """Accept case-insensitive values (e.g. 'FETCHABLE' → FETCHABLE)."""
        if isinstance(value, str):
            lower = value.lower()
            for member in cls:
                if member.value == lower:
                    return member
        return None


class WebDiscoveredUrl(DomainModel):
    """Discovered URL awaiting crawl or revisit."""

    id: str
    seed_id: str
    url: str
    parent_url: str | None = None
    normalized_url: str | None = None
    depth: int = 0
    status: WebUrlStatus = WebUrlStatus.NEW
    url_type: WebUrlType = WebUrlType.UNKNOWN
    priority: int = 100
    attempt_number: int = 0
    fair_priority: int = 100
    next_crawl: datetime | None = None
    metadata: dict | None = None
    created_at: datetime | None = None
    updated_at: datetime | None = None
