"""Memory feedback operations mixin."""
from __future__ import annotations

from typing import List

from cortex.storage._helpers import _now, _row_to_feedback
from cortex.types import MemoryFeedback


class ClaimFeedbackMixin:
    """Mixin providing feedback create/read/apply operations."""

    async def create_feedback(
        self,
        target_type: str,
        target_id: str,
        feedback_type: str,
        owner_id: str = "default",
        **kwargs,
    ) -> MemoryFeedback:
        async with self._write_lock:
            conn = await self._get_conn()
            now = _now()
            async with conn.execute(
                """
                INSERT INTO memory_feedback
                    (owner_id, target_type, target_id, feedback_type,
                     feedback_value, source, status, created_at)
                VALUES (?, ?, ?, ?, ?, ?, 'pending', ?)
                RETURNING *
                """,
                (
                    owner_id, target_type, target_id, feedback_type,
                    kwargs.get("feedback_value"),
                    kwargs.get("source", "operator"),
                    now,
                ),
            ) as cur:
                row = await cur.fetchone()
            await conn.commit()
            return _row_to_feedback(row)

    async def get_pending_feedback(
        self, owner_id: str = "default"
    ) -> List[MemoryFeedback]:
        conn = await self._get_conn()
        async with conn.execute(
            """
            SELECT * FROM memory_feedback
            WHERE owner_id = ? AND status = 'pending'
            ORDER BY created_at ASC
            """,
            (owner_id,),
        ) as cur:
            rows = await cur.fetchall()
        return [_row_to_feedback(r) for r in rows]

    async def apply_feedback(self, feedback_id: str) -> MemoryFeedback:
        async with self._write_lock:
            conn = await self._get_conn()
            now = _now()
            await conn.execute(
                """
                UPDATE memory_feedback
                   SET status = 'applied', applied_at = ?
                 WHERE id = ?
                """,
                (now, feedback_id),
            )
            await conn.commit()
            async with conn.execute(
                "SELECT * FROM memory_feedback WHERE id = ?", (feedback_id,)
            ) as cur:
                row = await cur.fetchone()
            assert row is not None
            return _row_to_feedback(row)
