"""
Request/Response models for pipeline runs dashboard endpoints.
"""

from __future__ import annotations

from datetime import datetime

from pydantic import BaseModel, Field


class PipelineRunResponse(BaseModel):
    """Response model for a single pipeline run record."""

    id: str = Field(..., description="Record UUID")
    run_id: str = Field(..., description="Short run identifier")
    pipeline_name: str | None = Field(None, description="Pipeline name")
    status: str = Field(..., description="Run status: success, failed, partial")

    # Row metrics
    rows_extracted: int = Field(0, description="Rows extracted from source")
    rows_transformed: int = Field(0, description="Rows after transform")
    rows_loaded: int = Field(0, description="Rows loaded to destination")
    rows_failed: int = Field(0, description="Rows that failed to load")
    rows_quarantined: int = Field(0, description="Total quarantined rows")
    batches_processed: int = Field(0, description="Number of batches processed")

    # Timing
    started_at: datetime | None = Field(None, description="Run start time")
    completed_at: datetime | None = Field(None, description="Run completion time")
    duration_seconds: float | None = Field(None, description="Duration in seconds")

    # Quality: contract (row-based) vs pipeline (column/dataset-based)
    contract_quality_score: float | None = Field(
        None, description="Contract (row-based) quality score 0-100; null if not run"
    )
    contract_quality_passed: bool | None = Field(
        None, description="Contract quality threshold passed; null if not run"
    )
    pipeline_quality_passed: bool | None = Field(
        None,
        description="Pipeline (column/dataset) quality checks passed; null if not run",
    )

    # Context
    extractor_type: str | None = Field(None, description="Extractor type used")
    loader_type: str | None = Field(None, description="Loader type used")
    trigger: str = Field("api", description="How the run was triggered")

    # Details
    errors: list[str] | None = Field(None, description="Error messages")

    created_at: datetime | None = Field(None, description="Record creation time")


class PipelineRunListResponse(BaseModel):
    """Paginated list of pipeline runs."""

    runs: list[PipelineRunResponse] = Field(
        default_factory=list, description="Pipeline run records"
    )
    total: int = Field(0, description="Total matching records")
    limit: int = Field(50, description="Page size")
    offset: int = Field(0, description="Page offset")


class RunStatsResponse(BaseModel):
    """Aggregated statistics for pipeline runs."""

    total_runs: int = Field(0, description="Total number of runs")
    successful_runs: int = Field(0, description="Runs with status=success")
    failed_runs: int = Field(0, description="Runs with status=failed")
    success_rate: float = Field(0.0, description="Success rate as percentage 0-100")
    avg_duration_seconds: float | None = Field(None, description="Average run duration")
    total_rows_loaded: int = Field(0, description="Total rows loaded across all runs")
    total_rows_failed: int = Field(0, description="Total rows failed across all runs")
    avg_rows_per_run: float = Field(0.0, description="Average rows loaded per run")


class TimeseriesBucket(BaseModel):
    """A single time bucket for timeseries data."""

    timestamp: str = Field(..., description="Bucket start time (ISO 8601)")
    total: int = Field(0, description="Total runs in bucket")
    successful: int = Field(0, description="Successful runs")
    failed: int = Field(0, description="Failed runs")
    avg_duration: float | None = Field(None, description="Avg duration in bucket")
    rows_loaded: int = Field(0, description="Total rows loaded in bucket")


class RunTimeseriesResponse(BaseModel):
    """Timeseries data for dashboard charts."""

    granularity: str = Field("day", description="Bucket granularity: hour or day")
    buckets: list[TimeseriesBucket] = Field(
        default_factory=list, description="Time-bucketed data"
    )


class PipelineSummary(BaseModel):
    """Summary stats for a single pipeline."""

    pipeline_name: str = Field(..., description="Pipeline name")
    total_runs: int = Field(0, description="Total runs")
    successful_runs: int = Field(0, description="Successful runs")
    failed_runs: int = Field(0, description="Failed runs")
    success_rate: float = Field(0.0, description="Success rate percentage")
    last_run_at: datetime | None = Field(None, description="Last run timestamp")
    last_status: str | None = Field(None, description="Last run status")
    avg_duration_seconds: float | None = Field(None, description="Average duration")


class PipelineListResponse(BaseModel):
    """List of distinct pipelines with summary stats."""

    pipelines: list[PipelineSummary] = Field(
        default_factory=list, description="Pipeline summaries"
    )
