"""EDA Agent database persistence models."""
import uuid
from datetime import datetime
from typing import Any, Dict, Optional

from sqlalchemy import DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import Mapped, mapped_column

from eda_agent.db.connection import Base


class AgentProfile(Base):
    """Persistent profile for one EDA agent instance."""

    __tablename__ = "eda_agents"

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )
    agent_id: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
    agent_role: Mapped[str] = mapped_column(String(100), nullable=False)

    llm_provider: Mapped[str] = mapped_column(String(50), nullable=False)
    llm_model: Mapped[str] = mapped_column(String(255), nullable=False)
    llm_embedding_model: Mapped[str] = mapped_column(String(255), nullable=False)
    llm_base_url: Mapped[Optional[str]] = mapped_column(String(512))
    llm_secret_ref: Mapped[Optional[str]] = mapped_column(String(255))

    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, default=datetime.utcnow, onupdate=datetime.utcnow
    )


class AgentStateSnapshot(Base):
    """Latest state snapshot for an EDA agent."""

    __tablename__ = "eda_agent_states"

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )
    agent_id: Mapped[str] = mapped_column(
        String(100),
        ForeignKey("eda_agents.agent_id", ondelete="CASCADE"),
        unique=True,
        nullable=False,
    )

    beliefs: Mapped[Any] = mapped_column(JSONB, default=dict)
    norm_bindings: Mapped[Any] = mapped_column(JSONB, default=list)
    value_weights: Mapped[Any] = mapped_column(JSONB, default=list)
    active_fields: Mapped[Any] = mapped_column(JSONB, default=list)
    current_intention: Mapped[Optional[str]] = mapped_column(Text)
    trust_score: Mapped[float] = mapped_column(default=0.8)

    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, default=datetime.utcnow, onupdate=datetime.utcnow
    )


class DecisionTrace(Base):
    """Auditable decision trace entries for EDA agent operations."""

    __tablename__ = "eda_decision_traces"

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )
    agent_id: Mapped[str] = mapped_column(
        String(100),
        ForeignKey("eda_agents.agent_id", ondelete="CASCADE"),
        nullable=False,
    )
    stage: Mapped[str] = mapped_column(String(50), nullable=False)
    input_payload: Mapped[Any] = mapped_column(JSONB, default=dict)
    norms_applied: Mapped[Any] = mapped_column(JSONB, default=list)
    compliance_result: Mapped[Any] = mapped_column(JSONB, default=dict)
    value_ranking: Mapped[Any] = mapped_column(JSONB, default=list)
    final_action: Mapped[Optional[Any]] = mapped_column(JSONB)
    result_payload: Mapped[Any] = mapped_column(JSONB, default=dict)
    latency_ms: Mapped[Optional[int]] = mapped_column(Integer)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)

