"""Repository for downloaded web media — dual-backend (PostgreSQL + Doris).

Insert-only — every successful download creates a new row in both backends.
"""

from __future__ import annotations

import logging
from typing import Any

from repo_core import BaseRepository

from .model import WebMedia

logger = logging.getLogger(__name__)


class WebMediaRepository(BaseRepository[WebMedia]):
    """Repository for persisting downloaded web media metadata.

    Dual-backend: PostgreSQL and Doris (identical column sets).
    Insert-only — every download creates a new row.  Re-downloading
    the same ``source_url`` creates a separate row with an incremented
    ``version``.  If ``content_hash`` is unchanged from the latest row,
    the insert is skipped (no new version).

    Usage::

        repo = WebMediaRepository(model=WebMedia)
        async with repo:
            await repo.insert_one(repo.TABLE, data)
            await repo.warehouse_insert_one(repo.TABLE, data)
    """

    TABLE = "web_media"
    _backends = {"db", "doris"}

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

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

        Used by the persistence layer to decide whether an incoming
        media download represents a content change (→ new version)
        or is unchanged (→ skip).  Queries PostgreSQL (the primary
        backend).
        """
        results = await self.find(
            self.TABLE,
            {"source_url": source_url},
            order_by=["-version"],
            limit=1,
        )
        if not results:
            logger.debug(
                "get_latest_media_version_first_download source_url=%s "
                "— no prior version exists",
                source_url,
            )
            return None
        row = results[0]
        row_id = getattr(row, "id", None)
        latest_version = getattr(row, "version", 1)
        latest_hash = getattr(row, "content_hash", None)
        logger.info(
            "get_latest_media_version_revisit source_url=%s latest_row_id=%s "
            "latest_version=%s latest_content_hash=%s",
            source_url,
            row_id,
            latest_version,
            latest_hash[:12] if latest_hash else None,
        )
        return {
            "version": latest_version,
            "content_hash": latest_hash,
        }
