from __future__ import annotations

from dataclasses import dataclass
from datetime import date
from typing import Literal

from finops_batches.domain.models import MissingDate

from .date_range import iter_dates
from .telemetry_repository import TelemetryRepository

ExecutionMode = Literal["RUN", "BACKFILL"]


@dataclass(frozen=True, slots=True)
class PlannedExecution:
    business_date: date
    attempt_number: int


class ExecutionPlanner:
    def __init__(self, telemetry_repository: TelemetryRepository) -> None:
        self.telemetry_repository = telemetry_repository

    def plan(
        self,
        *,
        definition_key: str,
        start_date: date,
        end_date: date,
        mode: ExecutionMode,
    ) -> list[PlannedExecution]:
        dates = iter_dates(start_date, end_date)
        if mode == "RUN":
            return [
                PlannedExecution(business_date=item, attempt_number=1) for item in dates
            ]
        states = self.telemetry_repository.execution_states(
            definition_key=definition_key,
            start_date=start_date,
            end_date=end_date,
        )
        planned: list[PlannedExecution] = []
        for business_date in dates:
            state = states.get(business_date)
            if state is not None and state.has_success:
                continue
            planned.append(
                PlannedExecution(
                    business_date=business_date,
                    attempt_number=(
                        state.latest_attempt + 1 if state is not None else 1
                    ),
                )
            )
        return planned

    def missing(
        self,
        *,
        definition_key: str,
        start_date: date,
        end_date: date,
    ) -> list[MissingDate]:
        states = self.telemetry_repository.execution_states(
            definition_key=definition_key,
            start_date=start_date,
            end_date=end_date,
        )
        result: list[MissingDate] = []
        for business_date in iter_dates(start_date, end_date):
            state = states.get(business_date)
            if state is None:
                result.append(
                    MissingDate(business_date=business_date, status="MISSING")
                )
            elif not state.has_success:
                result.append(
                    MissingDate(
                        business_date=business_date,
                        status="FAILED",
                        latest_attempt=state.latest_attempt,
                    )
                )
        return result
