"""
SQLAlchemy model for pipeline_runs table.

Stores historical pipeline execution results for dashboard analytics.
"""

from __future__ import annotations

import uuid

from sqlalchemy import JSON, Boolean, Column, DateTime, Float, Integer, String
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func

from pycharter.db.models.base import Base


class PipelineRunModel(Base):
    """SQLAlchemy model for pipeline_runs table."""

    __tablename__ = "pipeline_runs"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)

    # Pipeline identity
    run_id = Column(String(8), nullable=False, unique=True, index=True)
    pipeline_name = Column(String(255), nullable=True, index=True)

    # Status: success, failed, partial
    status = Column(String(20), nullable=False, index=True, default="success")

    # Row metrics
    rows_extracted = Column(Integer, nullable=False, default=0)
    rows_transformed = Column(Integer, nullable=False, default=0)
    rows_loaded = Column(Integer, nullable=False, default=0)
    rows_failed = Column(Integer, nullable=False, default=0)
    rows_quarantined = Column(Integer, nullable=False, default=0)
    batches_processed = Column(Integer, nullable=False, default=0)

    # Timing
    started_at = Column(DateTime(timezone=True), nullable=True)
    completed_at = Column(DateTime(timezone=True), nullable=True)
    duration_seconds = Column(Float, nullable=True)

    # Quality: contract (row-based) vs pipeline (column/dataset-based)
    contract_quality_score = Column(Float, nullable=True)
    contract_quality_passed = Column(Boolean, nullable=True)
    pipeline_quality_passed = Column(Boolean, nullable=True)

    # Pipeline context
    extractor_type = Column(String(50), nullable=True)
    loader_type = Column(String(50), nullable=True)
    trigger = Column(String(20), nullable=False, default="api")

    # Detail storage
    errors = Column(JSON, nullable=True)
    batch_results = Column(JSON, nullable=True)
    config_snapshot = Column(JSON, nullable=True)

    # Audit fields
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )
    created_by = Column(String(255), nullable=True)

    __table_args__ = ({"schema": "pycharter"},)
