from __future__ import annotations

import uuid
from datetime import datetime
from typing import Any

from sqlalchemy import DateTime, Index, Integer, String, Text, func
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.types import JSON

from app.db.base_class import Base


class AgentOperationFeedback(Base):
    __tablename__ = "agent_operation_feedback"
    __table_args__ = (
        Index("ix_agent_operation_feedback_user_created", "user_id", "created_at"),
        Index("ix_agent_operation_feedback_run_rating", "run_id", "rating"),
    )

    id: Mapped[str] = mapped_column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    feedback_id: Mapped[str] = mapped_column(
        String(50),
        unique=True,
        index=True,
        default=lambda: f"fb_{uuid.uuid4().hex[:16]}",
    )
    run_id: Mapped[str | None] = mapped_column(String(50), nullable=True, index=True)
    conversation_id: Mapped[str | None] = mapped_column(String(50), nullable=True, index=True)
    user_id: Mapped[str | None] = mapped_column(String(100), nullable=True, index=True)
    agent: Mapped[str] = mapped_column(String(30), default="", index=True)
    source: Mapped[str] = mapped_column(String(30), default="", index=True)
    session_type: Mapped[str] = mapped_column(String(30), default="", index=True)
    operation_type: Mapped[str] = mapped_column(String(50), default="assistant_round", index=True)
    operation_status: Mapped[str] = mapped_column(String(20), default="", index=True)
    rating: Mapped[int] = mapped_column(Integer, index=True)
    reason: Mapped[str | None] = mapped_column(Text(), nullable=True)
    context_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict)
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), index=True)
