import uuid
from datetime import datetime

from sqlalchemy import Boolean, DateTime, ForeignKey, String, Text, func
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column

from ..db import Base


class Escalation(Base):
    __tablename__ = "escalations"

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    job_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), ForeignKey("analysis_jobs.id"), nullable=False, index=True
    )
    reason: Mapped[str] = mapped_column(String, nullable=False)
    assigned_engineer: Mapped[str | None] = mapped_column(String, nullable=True)
    resolution: Mapped[str | None] = mapped_column(Text, nullable=True)
    # Real column as of the V1.1 Knowledge Base PRD — replaces the
    # `[root_cause_tag=...]` prefix that used to live inside `resolution`.
    root_cause_tag: Mapped[str | None] = mapped_column(String, nullable=True)
    resolution_fed_back_to_kb: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
    kb_opt_in: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
    # Set from services/incidents.py::create_incident's response when
    # INCIDENT_IO_API_KEY is configured; null when it isn't, or when the
    # call failed (log-only, never blocks the escalation itself — see #2).
    incident_io_id: Mapped[str | None] = mapped_column(String, nullable=True)
    incident_io_url: Mapped[str | None] = mapped_column(String, nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
    resolved_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
