"""Persisted chat rows tied to a codegen run (assistant + user mirror)."""
from __future__ import annotations
from typing import Any, Optional
from uuid import UUID, uuid4

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from src.domain.codegen.models import RunChatMessage


class RunChatMessageRepository:
    def __init__(self, db: AsyncSession):
        self._db = db

    async def create(
        self,
        *,
        project_id: UUID,
        session_id: UUID,
        run_id: UUID,
        role: str,
        content: str,
        message_type: str = "message",
        payload: Optional[dict[str, Any]] = None,
        prompt_id: Optional[UUID] = None,
        message_id: Optional[UUID] = None,
    ) -> RunChatMessage:
        row = RunChatMessage(
            id=message_id or uuid4(),
            project_id=project_id,
            session_id=session_id,
            run_id=run_id,
            role=role,
            message_type=message_type,
            content=content or "",
            payload=payload,
            prompt_id=prompt_id,
        )
        self._db.add(row)
        await self._db.flush()
        await self._db.refresh(row)
        return row

    async def list_for_session(self, session_id: UUID) -> list[RunChatMessage]:
        result = await self._db.execute(
            select(RunChatMessage)
            .where(RunChatMessage.session_id == session_id)
            .order_by(RunChatMessage.created_at)
        )
        return list(result.scalars().all())
