"""Repository for codal_media — PostgreSQL-only inspection results."""

from __future__ import annotations

import uuid
from datetime import datetime, timezone
from typing import Any

from repo_core import BaseRepository

from .model import CodalMedia


class CodalMediaRepository(BaseRepository[CodalMedia]):
    """Repository for codal_media — upsert by web_media_id.

    PostgreSQL-only — no Elasticsearch or Doris backing.
    """

    TABLE = "codal_media"
    _backends = {"db"}

    async def upsert_by_web_media_id(
        self, web_media_id: str, data: dict[str, Any]
    ) -> CodalMedia:
        """Insert or update an inspection row by web_media_id.

        On first insert, auto-generates ``id``.  On update, all
        provided fields are overwritten — inspection is idempotent.
        """
        existing = await self.first(self.TABLE, {"web_media_id": web_media_id})
        if existing is not None:
            # Keep the original id and created_at
            data["id"] = existing.id
            data.pop("created_at", None)
            await self.update_by_id(self.TABLE, existing.id, data)
            return await self.find_by_id(self.TABLE, existing.id)

        # First insert — auto-generate id
        data.setdefault("id", str(uuid.uuid4()))
        return await self.insert_one(self.TABLE, data)

    async def find_by_web_media_id(
        self, web_media_id: str
    ) -> CodalMedia | None:
        """Return the inspection row for a given web_media_id, or None."""
        return await self.first(self.TABLE, {"web_media_id": web_media_id})
