"""Grukk message REST API routes."""

from __future__ import annotations

import json
from uuid import UUID

from fastapi import APIRouter, Depends, Query

from peon_mcp.common.dependencies import get_db
from peon_mcp.grukk_messages.schemas import (
    GrukkMessageCreate,
    GrukkMessageResponse,
)


def _fix_jsonb(row: dict) -> dict:
    """Ensure JSONB fields are dicts, not strings."""
    if isinstance(row.get("metadata"), str):
        try:
            row["metadata"] = json.loads(row["metadata"])
        except (json.JSONDecodeError, TypeError):
            row["metadata"] = {}
    return row

router = APIRouter(tags=["Grukk Messages"])


@router.get("/api/grukk/messages", response_model=list[GrukkMessageResponse])
async def list_grukk_messages(
    limit: int = Query(default=50, ge=1, le=200),
    before: UUID | None = Query(default=None),
    db=Depends(get_db),
):
    """Paginated chat history, ordered by created_at DESC.

    Use `before` as a cursor: pass the id of the last message to get older ones.
    """
    params: list = []
    where = ""
    if before is not None:
        where = "WHERE gm.created_at < (SELECT created_at FROM grukk_messages WHERE id = ?)"
        params.append(str(before))

    rows = await db.execute_fetchall(
        f"SELECT gm.* FROM grukk_messages gm {where} ORDER BY gm.created_at DESC LIMIT ?",
        params + [limit],
    )
    return [_fix_jsonb(dict(r)) for r in rows]


@router.post("/api/grukk/messages", response_model=GrukkMessageResponse, status_code=201)
async def create_grukk_message(
    body: GrukkMessageCreate,
    db=Depends(get_db),
):
    """Send a message in the King/Grukk chat."""
    rows = await db.execute_fetchall(
        "INSERT INTO grukk_messages (user_id, role, content, metadata)"
        " VALUES (?, ?, ?, ?::jsonb)"
        " RETURNING *",
        (body.user_id, body.role.value, body.content, json.dumps(body.metadata)),
    )
    await db.commit()
    return _fix_jsonb(dict(rows[0]))


@router.get("/api/grukk/messages/pending", response_model=list[GrukkMessageResponse])
async def get_pending_grukk_messages(
    db=Depends(get_db),
):
    """Get unanswered King messages (newer than the last Grukk message).

    This is what Grukk polls to see if the King has said something new.
    """
    rows = await db.execute_fetchall(
        "SELECT * FROM grukk_messages"
        " WHERE role = 'king'"
        "   AND created_at > COALESCE("
        "     (SELECT MAX(created_at) FROM grukk_messages WHERE role = 'grukk'),"
        "     '1970-01-01'::timestamptz"
        "   )"
        " ORDER BY created_at ASC",
        (),
    )
    return [_fix_jsonb(dict(r)) for r in rows]
