"""Web download metric repository — warehouse-only persistence.

INSERT-only — every download creates a new row for per-download history.
"""

from __future__ import annotations

import logging
from typing import Any

from repo_core import BaseRepository

from .model import WebDownloadMetric

logger = logging.getLogger(__name__)


class WebDownloadMetricRepository(BaseRepository[WebDownloadMetric]):
    """Repository for persisting web download metrics in Doris.

    Warehouse-only — no database or search backends.  The table uses
    DUPLICATE KEY so every download creates a new row — re-downloading
    the same ``source_url`` produces a separate metrics row.  Query
    the latest by ``ORDER BY created_at DESC LIMIT 1``.

    Usage::

        repo = WebDownloadMetricRepository(model=WebDownloadMetric)
        async with repo:
            await repo.upsert_metric(
                source_url="https://example.com/photo.jpg",
                payload={"status": "downloaded", "download_duration_ms": 1500},
            )
    """

    TABLE = "web_metrics"
    _backends = {"doris"}

    async def upsert_metric(
        self, source_url: str, payload: dict[str, Any]
    ) -> None:
        """Insert a new metric row for *source_url*.

        Every call creates a new row — DUPLICATE KEY tables do not
        support UPDATE, so re-downloads produce separate rows.  Query
        the latest by ``ORDER BY created_at DESC LIMIT 1``.
        """
        data = dict(payload)
        data.setdefault("source_url", source_url)
        data.setdefault("status", "unknown")
        await self.warehouse_insert_one(
            self.TABLE,
            data,
            returning=["*"],
        )
