from __future__ import annotations

from collections.abc import Iterator
from datetime import UTC, date, datetime
from typing import cast
from uuid import UUID

import pytest

from finops_batches.domain.models import (
    BatchExecutionContext,
)
from finops_batches.providers.azure.sponsorship_billing import (
    AzureSponsorshipBillingExtractor,
)
from finops_batches.providers.azure.sponsorship_client import (
    AzureSponsorshipUsageClient,
    UsageAggregate,
    UsageAggregatesRequest,
)


class FakeAzureSponsorshipUsageClient:
    def __init__(
        self,
        aggregates: list[UsageAggregate] | None = None,
    ) -> None:
        self.aggregates = aggregates if aggregates is not None else []
        self.requests: list[UsageAggregatesRequest] = []
        self.close_calls = 0

    def list_usage_aggregates(
        self,
        request: UsageAggregatesRequest,
    ) -> Iterator[UsageAggregate]:
        self.requests.append(request)
        yield from self.aggregates

    def close(self) -> None:
        self.close_calls += 1


def _context(
    business_date: date,
) -> BatchExecutionContext:
    return BatchExecutionContext(
        trigger_type="MANUAL",
        business_date=business_date,
        attempt_number=1,
        logical_run_id=UUID("11111111-2222-3333-4444-555555555555"),
    )


def _extractor(
    fake_client: FakeAzureSponsorshipUsageClient,
    *,
    subscription_id: str = "subscription-123",
) -> AzureSponsorshipBillingExtractor:
    return AzureSponsorshipBillingExtractor(
        client=cast(
            AzureSponsorshipUsageClient,
            fake_client,
        ),
        subscription_id=subscription_id,
    )


def test_constructor_rejects_empty_subscription_id() -> None:
    fake_client = FakeAzureSponsorshipUsageClient()

    with pytest.raises(
        ValueError,
        match="subscription_id est obligatoire",
    ):
        _extractor(
            fake_client,
            subscription_id="",
        )


def test_constructor_stores_dependencies() -> None:
    fake_client = FakeAzureSponsorshipUsageClient()

    extractor = _extractor(fake_client)

    assert extractor.subscription_id == "subscription-123"
    assert extractor.client is fake_client


def test_extract_builds_daily_midnight_request() -> None:
    fake_client = FakeAzureSponsorshipUsageClient()
    extractor = _extractor(fake_client)

    result = extractor.extract(_context(date(2026, 8, 1)))

    assert result == []
    assert len(fake_client.requests) == 1

    request = fake_client.requests[0]

    assert request == UsageAggregatesRequest(
        subscription_id="subscription-123",
        reported_start_time="2026-08-01T00:00:00Z",
        reported_end_time="2026-08-02T00:00:00Z",
        aggregation_granularity="Daily",
        show_details=True,
    )


def test_extract_copies_all_aggregates_to_records() -> None:
    first: UsageAggregate = {
        "id": "usage-1",
        "name": "first",
        "type": "Microsoft.Commerce/usageAggregates",
        "properties": {
            "subscriptionId": "subscription-123",
            "quantity": 12.5,
        },
    }
    second: UsageAggregate = {
        "id": "usage-2",
        "properties": {
            "subscriptionId": "subscription-123",
            "quantity": 3,
        },
    }

    fake_client = FakeAzureSponsorshipUsageClient([first, second])
    extractor = _extractor(fake_client)

    records = extractor.extract(_context(date(2026, 8, 1)))

    assert records == [
        {
            "id": "usage-1",
            "name": "first",
            "type": "Microsoft.Commerce/usageAggregates",
            "properties": {
                "subscriptionId": "subscription-123",
                "quantity": 12.5,
            },
        },
        {
            "id": "usage-2",
            "properties": {
                "subscriptionId": "subscription-123",
                "quantity": 3,
            },
        },
    ]

    assert records[0] is not first
    assert records[1] is not second


def test_extract_rejects_current_unfinished_day(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    fake_client = FakeAzureSponsorshipUsageClient()
    extractor = _extractor(fake_client)

    fixed_now = datetime(
        2026,
        8,
        6,
        12,
        tzinfo=UTC,
    )

    class FixedDateTime(datetime):
        @classmethod
        def now(
            cls,
            tz: object | None = None,
        ) -> datetime:
            del cls, tz
            return fixed_now

    monkeypatch.setattr(
        "finops_batches.providers.azure.sponsorship_billing.datetime",
        FixedDateTime,
    )

    with pytest.raises(
        ValueError,
        match=("La journée demandée n'est pas encore entièrement terminée"),
    ):
        extractor.extract(_context(date(2026, 8, 6)))

    assert fake_client.requests == []


def test_extract_accepts_previous_completed_day(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    fake_client = FakeAzureSponsorshipUsageClient()
    extractor = _extractor(fake_client)

    fixed_now = datetime(
        2026,
        8,
        6,
        12,
        tzinfo=UTC,
    )

    class FixedDateTime(datetime):
        @classmethod
        def now(
            cls,
            tz: object | None = None,
        ) -> datetime:
            del cls, tz
            return fixed_now

    monkeypatch.setattr(
        "finops_batches.providers.azure.sponsorship_billing.datetime",
        FixedDateTime,
    )

    result = extractor.extract(_context(date(2026, 8, 5)))

    assert result == []
    assert fake_client.requests == [
        UsageAggregatesRequest(
            subscription_id="subscription-123",
            reported_start_time="2026-08-05T00:00:00Z",
            reported_end_time="2026-08-06T00:00:00Z",
            aggregation_granularity="Daily",
            show_details=True,
        )
    ]


def test_close_closes_client() -> None:
    fake_client = FakeAzureSponsorshipUsageClient()
    extractor = _extractor(fake_client)

    extractor.close()

    assert fake_client.close_calls == 1
