"""Warehouse-only repository for raw fetched HTML.

All queries run against Doris — no PostgreSQL or Elasticsearch backends.
"""

from __future__ import annotations

import logging
import time
from typing import Any

from repo_core import BaseRepository

from .model import WebHtmlRaw

logger = logging.getLogger(__name__)


class WebHtmlRawRepository(BaseRepository[WebHtmlRaw]):
    """Repository for persisting raw fetched HTML in the Doris warehouse.

    Warehouse-only — no database or search backends.  Uses UNIQUE KEY
    on ``id`` (UUID) so every fetch creates a new unique row.

    Usage::

        repo = WebHtmlRawRepository(model=WebHtmlRaw)
        async with repo:
            await repo.warehouse_insert_one(repo.TABLE, data)
    """

    TABLE = "web_html_raw"
    _backends = {"doris"}

    # ------------------------------------------------------------------
    # Version / hash lookup
    # ------------------------------------------------------------------

    async def get_latest_version(self, url: str) -> dict | None:
        """Return the latest ``version`` and ``raw_hash`` for *url*, or ``None``.

        Used by the persistence layer to decide whether incoming HTML
        represents a content change (→ new version) or is unchanged (→ skip).
        """
        results = await self.warehouse_find(
            self.TABLE,
            {"url": url},
            order_by=["-version"],
            limit=1,
        )
        if not results:
            logger.debug(
                "get_latest_version_first_fetch url=%s — no prior version exists",
                url,
            )
            return None
        row = results[0]
        row_id = getattr(row, "id", None)
        latest_version = getattr(row, "version", 1)
        latest_hash = getattr(row, "raw_hash", None)
        logger.info(
            "get_latest_version_revisit url=%s latest_row_id=%s latest_version=%s "
            "latest_raw_hash=%s",
            url,
            row_id,
            latest_version,
            latest_hash[:12] if latest_hash else None,
        )
        return {
            "version": latest_version,
            "raw_hash": latest_hash,
        }

    # ------------------------------------------------------------------
    # Timestamp injection (Unix int seconds, not datetime)
    # ------------------------------------------------------------------

    def _inject_model_timestamps(self, data: dict[str, Any]) -> dict[str, Any]:
        """Inject ``created_at`` as Unix int seconds (Doris convention)."""
        if self.model is None:
            return data
        now = int(time.time())
        if "created_at" in self.model.model_fields and "created_at" not in data:
            data["created_at"] = now
        return data

    def _inject_model_updated_at(self, values: dict[str, Any]) -> dict[str, Any]:
        """No-op — warehouse-only models use ``created_at`` only."""
        return values
