from __future__ import annotations

from dataclasses import dataclass
from datetime import date
from typing import Protocol

from sqlalchemy import (
    Column,
    Date,
    Integer,
    MetaData,
    String,
    Table,
    and_,
    case,
    create_engine,
    func,
    select,
)
from sqlalchemy.engine import Engine


@dataclass(frozen=True, slots=True)
class ExecutionState:
    business_date: date
    has_success: bool
    latest_attempt: int


class TelemetryRepository(Protocol):
    def execution_states(
        self,
        *,
        definition_key: str,
        start_date: date,
        end_date: date,
    ) -> dict[date, ExecutionState]: ...

    def close(self) -> None: ...


class SqlAlchemyTelemetryRepository:
    def __init__(
        self,
        database_url: str,
        *,
        schema: str | None = "det",
    ) -> None:
        self.engine: Engine = create_engine(database_url, pool_pre_ping=True)
        metadata = MetaData(schema=schema)
        self.execution_run = Table(
            "execution_run",
            metadata,
            Column("definition_key", String(255), nullable=False),
            Column("business_date", Date(), nullable=True),
            Column("attempt_number", Integer(), nullable=False),
            Column("operational_status", String(50), nullable=False),
        )

    def execution_states(
        self,
        *,
        definition_key: str,
        start_date: date,
        end_date: date,
    ) -> dict[date, ExecutionState]:
        success_score = func.max(
            case(
                (self.execution_run.c.operational_status == "SUCCESS", 1),
                else_=0,
            )
        )
        statement = (
            select(
                self.execution_run.c.business_date,
                success_score.label("has_success"),
                func.max(self.execution_run.c.attempt_number).label("latest_attempt"),
            )
            .where(
                and_(
                    self.execution_run.c.definition_key == definition_key,
                    self.execution_run.c.business_date.is_not(None),
                    self.execution_run.c.business_date >= start_date,
                    self.execution_run.c.business_date <= end_date,
                )
            )
            .group_by(self.execution_run.c.business_date)
        )
        result: dict[date, ExecutionState] = {}
        with self.engine.connect() as connection:
            for row in connection.execute(statement):
                business_date = row.business_date
                if not isinstance(business_date, date):
                    continue
                result[business_date] = ExecutionState(
                    business_date=business_date,
                    has_success=bool(row.has_success),
                    latest_attempt=int(row.latest_attempt),
                )
        return result

    def close(self) -> None:
        self.engine.dispose()
