"""SQL execution-state aggregation and legacy contracts with external boundaries mocked."""

from datetime import timedelta
from unittest.mock import MagicMock

import pytest

from finops_batches.application.telemetry_repository import (
    SqlAlchemyTelemetryRepository,
)
from finops_batches.domain.models import Record
from finops_batches.providers.azure.raw_bronze import RawJsonBronzeTransformer
from finops_batches.providers.azure.reservations import AzureReservationsExtractor
from finops_batches.providers.azure.sponsorship_billing_loader import (
    AzureSponsorshipBillingLoader,
)
from finops_batches.providers.azure.types import UsageAggregate, UsageAggregatesResponse

from .helpers import DAY, Store


def test_telemetry_aggregates_success_and_attempts_in_the_requested_scope(
    store: Store,
) -> None:
    repository = SqlAlchemyTelemetryRepository(store.url, schema=None)
    repository.execution_run.create(store.engine)
    with store.engine.begin() as conn:
        conn.execute(
            repository.execution_run.insert(),
            [
                {
                    "definition_key": "job",
                    "business_date": DAY,
                    "attempt_number": 1,
                    "operational_status": "FAILED",
                },
                {
                    "definition_key": "job",
                    "business_date": DAY,
                    "attempt_number": 2,
                    "operational_status": "SUCCESS",
                },
                {
                    "definition_key": "job",
                    "business_date": DAY + timedelta(days=1),
                    "attempt_number": 1,
                    "operational_status": "FAILED",
                },
                {
                    "definition_key": "other",
                    "business_date": DAY,
                    "attempt_number": 9,
                    "operational_status": "SUCCESS",
                },
                {
                    "definition_key": "job",
                    "business_date": None,
                    "attempt_number": 10,
                    "operational_status": "SUCCESS",
                },
            ],
        )
    try:
        states = repository.execution_states(
            definition_key="job", start_date=DAY, end_date=DAY + timedelta(days=1)
        )
        assert states[DAY].has_success is True and states[DAY].latest_attempt == 2
        assert states[DAY + timedelta(days=1)].has_success is False
        assert (
            repository.execution_states(
                definition_key="absent", start_date=DAY, end_date=DAY
            )
            == {}
        )
    finally:
        repository.close()


def test_typed_usage_contract_can_be_preserved_as_raw_bronze() -> None:
    aggregate: UsageAggregate = {
        "id": "usage",
        "properties": {"quantity": 2, "infoFields": {"nested": [1, None]}},
    }
    envelope: UsageAggregatesResponse = {
        "value": [aggregate],
        "nextLink": "https://example.invalid/next",
    }
    records: list[Record] = [{"payload": item} for item in envelope["value"]]
    (row,) = RawJsonBronzeTransformer().transform(records)
    assert "nested" in str(row["payload"])
    assert row["source_hash"] is not None


@pytest.mark.parametrize("nonempty", [False, True])
def test_legacy_billing_loader_keeps_day_delete_and_insert_in_one_transaction(
    monkeypatch: pytest.MonkeyPatch, nonempty: bool
) -> None:
    engine = MagicMock()
    connection = engine.begin.return_value.__enter__.return_value
    monkeypatch.setattr(
        "finops_batches.providers.azure.sponsorship_billing_loader.create_engine",
        MagicMock(return_value=engine),
    )
    loader = AzureSponsorshipBillingLoader(
        database_url="unused://", table_name="billing"
    )
    rows: list[Record] = [{"source_id": "one"}] if nonempty else []
    assert loader.load(rows, business_date=DAY) == len(rows)
    assert connection.execute.call_count == (2 if nonempty else 1)
    delete = connection.execute.call_args_list[0]
    assert delete.args[1] == {"start_date": DAY}
    assert "DELETE FROM billing" in str(delete.args[0])
    if nonempty:
        assert connection.execute.call_args_list[1].args[1] == rows
    engine.begin.return_value.__exit__.assert_called_once_with(None, None, None)
    loader.close()
    engine.dispose.assert_called_once()


def test_reservations_placeholder_does_not_query_azure(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    credential = MagicMock()
    monkeypatch.setattr(
        "finops_batches.providers.azure.reservations.DefaultAzureCredential", credential
    )
    extractor = AzureReservationsExtractor("sub")
    assert extractor.subscription_id == "sub"
    assert extractor.extract() == []
    credential.return_value.get_token.assert_not_called()
