"""Test the RAW Bronze extractor with local UsageAggregates pages."""

from __future__ import annotations

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

import pytest

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


class FakeAzureSponsorshipUsageClient:
    """Supply raw pages without HTTP requests or Azure authentication."""

    api_version = "2015-06-01-preview"

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

    def list_usage_aggregate_pages(
        self, request: UsageAggregatesRequest
    ) -> Iterator[UsageAggregatesPage]:
        """Record the request and yield raw JSON page envelopes."""
        self.requests.append(request)
        yield from self.pages

    def close(self) -> None:
        """Record resource cleanup."""
        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 _page(
    payload: Mapping[str, object], *, url: str = "https://example.invalid/usage?page=1"
) -> UsageAggregatesPage:
    return UsageAggregatesPage(request_url=url, payload=payload)


@pytest.fixture
def frozen_clock(monkeypatch: pytest.MonkeyPatch) -> None:
    """Make completed-day checks independent of the actual date."""

    class FixedDateTime(datetime):
        @classmethod
        def now(cls, tz: tzinfo | None = None) -> Self:
            del tz
            return cls(2026, 8, 6, 12, tzinfo=UTC)

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


def test_constructor_rejects_empty_subscription_id() -> None:
    """An Azure subscription is required even when the source is mocked."""
    with pytest.raises(ValueError, match="subscription_id est obligatoire"):
        _extractor(FakeAzureSponsorshipUsageClient(), subscription_id="")


def test_constructor_stores_dependencies() -> None:
    """Keep the caller-supplied client and subscription."""
    client = FakeAzureSponsorshipUsageClient()
    extractor = _extractor(client)
    assert extractor.subscription_id == "subscription-123"
    assert extractor.client is cast(AzureSponsorshipUsageClient, client)


def test_extract_builds_daily_midnight_request(frozen_clock: None) -> None:
    """Request the complete UTC day using the raw-page API."""
    client = FakeAzureSponsorshipUsageClient()
    assert _extractor(client).extract(_context(date(2026, 8, 1))) == []
    assert client.requests == [
        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_raw_records(frozen_clock: None) -> None:
    """Retain opaque source objects inside the Bronze envelope and their page lineage."""
    first: dict[str, object] = {
        "id": "usage-1",
        "name": "first",
        "type": "Microsoft.Commerce/usageAggregates",
        "properties": {"subscriptionId": "subscription-123", "quantity": 12.5},
    }
    second: dict[str, object] = {"id": "usage-2", "properties": {"quantity": 3}}
    page = _page({"value": [first, second]})
    client = FakeAzureSponsorshipUsageClient([page])
    records = _extractor(client).extract(_context(date(2026, 8, 1)))
    assert len(records) == 2
    assert [row["payload"] for row in records] == [first, second]
    assert records[0]["payload"] is not first
    assert records[1]["payload"] is not second
    assert [row["source_record_number"] for row in records] == [1, 2]
    assert records[0] == {
        "provider_code": "AZURE",
        "source_system": "MICROSOFT.COMMERCE",
        "source_name": "USAGE_AGGREGATES",
        "scope_type": "SUBSCRIPTION",
        "scope_id": "subscription-123",
        "business_date": date(2026, 8, 1),
        "source_uri_logical": "/subscriptions/subscription-123/providers/Microsoft.Commerce/UsageAggregates",
        "request_url": page.request_url,
        "page_number": 1,
        "source_record_number": 1,
        "api_version": client.api_version,
        "request_context": {
            "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,
        },
        "payload": first,
    }


def test_extract_keeps_page_urls_and_resets_record_numbers(frozen_clock: None) -> None:
    """Keep source positions per page, including when Azure returns an empty page."""
    client = FakeAzureSponsorshipUsageClient(
        [
            _page({"value": [{"id": "one"}]}, url="https://example.invalid/1"),
            _page({"value": []}, url="https://example.invalid/2"),
            _page({"value": [{"id": "three"}]}, url="https://example.invalid/3"),
        ]
    )
    rows = _extractor(client).extract(_context(date(2026, 8, 1)))
    assert [row["page_number"] for row in rows] == [1, 3]
    assert [row["source_record_number"] for row in rows] == [1, 1]
    assert [row["request_url"] for row in rows] == [
        "https://example.invalid/1",
        "https://example.invalid/3",
    ]
    assert len(client.requests) == 1


def test_extract_rejects_current_unfinished_day(frozen_clock: None) -> None:
    """Reject the current day before calling the client."""
    client = FakeAzureSponsorshipUsageClient()
    with pytest.raises(
        ValueError, match="La journée demandée n'est pas encore entièrement terminée"
    ):
        _extractor(client).extract(_context(date(2026, 8, 6)))
    assert client.requests == []


def test_extract_accepts_previous_completed_day(frozen_clock: None) -> None:
    """Accept yesterday and request its full UTC interval."""
    client = FakeAzureSponsorshipUsageClient()
    assert _extractor(client).extract(_context(date(2026, 8, 5))) == []
    assert 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,
        )
    ]


@pytest.mark.parametrize(
    ("payload", "error", "message"),
    [
        ({}, BatchExecutionError, "value"),
        ({"value": None}, BatchExecutionError, "value"),
        ({"value": "wrong"}, TypeError, "liste"),
        ({"value": [None]}, TypeError, "objet JSON"),
        ({"value": [{1: "wrong-key"}]}, TypeError, "chaînes"),
    ],
)
def test_extract_rejects_invalid_page_shapes(
    frozen_clock: None,
    payload: dict[str, object],
    error: type[Exception],
    message: str,
) -> None:
    """Fail explicitly when technical envelopes cannot be converted to raw records."""
    client = FakeAzureSponsorshipUsageClient([_page(payload)])
    with pytest.raises(error, match=message):
        _extractor(client).extract(_context(date(2026, 8, 1)))


def test_close_closes_client() -> None:
    """Release the client through the extractor lifecycle."""
    client = FakeAzureSponsorshipUsageClient()
    _extractor(client).close()
    assert client.close_calls == 1
