"""Pipeline execution ORM models for PostgreSQL persistence."""

import uuid
from datetime import datetime, timezone

from sqlalchemy import Column, DateTime, Index, Integer, String, Text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import DeclarativeBase


class Base(DeclarativeBase):
    pass


class PipelineExecutionModel(Base):
    """Pipeline execution record — persisted final state."""

    __tablename__ = "pipeline_executions"

    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    pipeline_name = Column(String(128), nullable=False, index=True)
    status = Column(String(32), nullable=False, index=True)
    current_step = Column(String(128))
    completed_steps = Column(JSONB, default=list)
    step_results = Column(JSONB, default=dict)
    input_data = Column(JSONB)
    final_output = Column(JSONB)
    error_message = Column(Text)
    tenant_id = Column(String(64), index=True)
    created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
    updated_at = Column(
        DateTime,
        default=lambda: datetime.now(timezone.utc),
        onupdate=lambda: datetime.now(timezone.utc),
    )
    completed_at = Column(DateTime)

    __table_args__ = (
        Index("ix_pipeline_status_created", "status", "created_at"),
    )


class PipelineStepHistoryModel(Base):
    """Step execution history — audit trail."""

    __tablename__ = "pipeline_step_history"

    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    execution_id = Column(String(36), nullable=False, index=True)
    step_name = Column(String(128), nullable=False)
    step_index = Column(Integer, nullable=False)
    status = Column(String(32), nullable=False)
    input_data = Column(JSONB)
    output_data = Column(JSONB)
    error_message = Column(Text)
    duration_ms = Column(Integer)
    retry_attempt = Column(Integer, default=0)
    started_at = Column(DateTime)
    completed_at = Column(DateTime)
