from __future__ import annotations

from datetime import date
from uuid import uuid4

from det_sdk.exceptions import TransportError
from sqlalchemy.exc import SQLAlchemyError

from finops_batches.application.execution_planner import (
    ExecutionMode,
    ExecutionPlanner,
)
from finops_batches.application.registry import BatchRegistry
from finops_batches.domain.models import (
    BatchExecutionContext,
    BatchRunSummary,
    MissingDate,
    TriggerType,
)
from finops_batches.exceptions import BatchExecutionError

EXPECTED_BATCH_ERRORS = (
    BatchExecutionError,
    TransportError,
    SQLAlchemyError,
    ValueError,
    TypeError,
)


def run_batch_for_date(
    *,
    registry: BatchRegistry,
    definition_key: str,
    business_date: date,
    trigger_type: TriggerType,
    attempt_number: int = 1,
) -> bool:
    job = registry.build(definition_key)

    context = BatchExecutionContext(
        trigger_type=trigger_type,
        business_date=business_date,
        attempt_number=attempt_number,
        logical_run_id=uuid4(),
    )

    try:
        job.run(context)
    except EXPECTED_BATCH_ERRORS:
        return False
    finally:
        job.close()

    return True


def run_range(
    *,
    registry: BatchRegistry,
    planner: ExecutionPlanner,
    definition_key: str,
    start_date: date,
    end_date: date,
    mode: ExecutionMode,
) -> BatchRunSummary:
    if end_date < start_date:
        raise ValueError("end_date doit être supérieure ou égale à start_date.")

    trigger_type: TriggerType = "BACKFILL" if mode == "BACKFILL" else "MANUAL"

    planned = planner.plan(
        definition_key=definition_key,
        start_date=start_date,
        end_date=end_date,
        mode=mode,
    )

    succeeded: list[str] = []
    failed: list[str] = []

    for execution in planned:
        execution_key = f"{definition_key}@{execution.business_date.isoformat()}"

        success = run_batch_for_date(
            registry=registry,
            definition_key=definition_key,
            business_date=execution.business_date,
            trigger_type=trigger_type,
            attempt_number=execution.attempt_number,
        )

        if success:
            succeeded.append(execution_key)
        else:
            failed.append(execution_key)

    return BatchRunSummary(
        succeeded=succeeded,
        failed=failed,
    )


def find_missing(
    *,
    planner: ExecutionPlanner,
    definition_key: str,
    start_date: date,
    end_date: date,
) -> list[MissingDate]:
    if end_date < start_date:
        raise ValueError("end_date doit être supérieure ou égale à start_date.")

    return planner.missing(
        definition_key=definition_key,
        start_date=start_date,
        end_date=end_date,
    )
