from __future__ import annotations

from collections.abc import Iterator
from datetime import UTC, date, datetime, timedelta
from uuid import UUID
from zoneinfo import ZoneInfo

import pytest

from finops_batches.domain.models import BatchExecutionContext
from finops_batches.providers.gcp.billing import GcpBillingExtractor
from finops_batches.providers.gcp.billing_types import GcpBillingExportRow


class FakeBillingClient:
    source_table = "p.d.t"
    location = "EU"
    export_timezone = "UTC"

    def __init__(self) -> None:
        self.closed = False
        self.requested_date: date | None = None

    def iter_export_rows(
        self,
        business_date: date,
    ) -> Iterator[GcpBillingExportRow]:
        self.requested_date = business_date
        yield GcpBillingExportRow(
            payload='{"billing_account_id":"A"}',
            export_time=datetime(2026, 8, 1, tzinfo=UTC),
            page_number=2,
            source_record_number=5,
        )

    def close(self) -> None:
        self.closed = True


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


def make_extractor(
    fake: FakeBillingClient,
    *,
    allow_current_day: bool = False,
) -> GcpBillingExtractor:
    return GcpBillingExtractor(
        client=fake,
        source_system="gcp_cloud_billing_bigquery",
        source_name="detailed_usage_cost",
        scope_type="billing_account",
        scope_id="ABC",
        source_schema_version="v1",
        allow_current_day=allow_current_day,
    )


def test_extractor_builds_raw_source_record() -> None:
    fake = FakeBillingClient()
    day = date(2026, 8, 1)
    row = make_extractor(fake).extract(context(day))[0]
    assert row["provider_code"] == "GCP"
    assert row["business_date"] == day
    assert row["page_number"] == 2
    assert row["source_record_number"] == 5
    assert row["source_uri_logical"] == "bigquery://p.d.t"
    assert row["payload"] == '{"billing_account_id":"A"}'
    assert fake.requested_date == day


def test_current_day_is_rejected_by_default() -> None:
    fake = FakeBillingClient()
    today = datetime.now(UTC).astimezone(ZoneInfo("UTC")).date()
    with pytest.raises(ValueError, match="CURRENT_DAY_DISABLED"):
        make_extractor(fake).extract(context(today))


def test_current_day_can_be_enabled() -> None:
    fake = FakeBillingClient()
    today = datetime.now(UTC).date()
    rows = make_extractor(fake, allow_current_day=True).extract(context(today))
    assert len(rows) == 1


def test_future_day_is_rejected() -> None:
    fake = FakeBillingClient()
    tomorrow = datetime.now(UTC).date() + timedelta(days=1)
    with pytest.raises(ValueError, match="FUTURE_DATE"):
        make_extractor(fake, allow_current_day=True).extract(context(tomorrow))


def test_invalid_timezone_is_rejected() -> None:
    fake = FakeBillingClient()
    fake.export_timezone = "No/Such_Zone"
    with pytest.raises(ValueError, match="Fuseau"):
        make_extractor(fake)


def test_close_delegates_to_client() -> None:
    fake = FakeBillingClient()
    extractor = make_extractor(fake)
    extractor.close()
    assert fake.closed is True


def test_blank_required_source_metadata_is_rejected() -> None:
    fake = FakeBillingClient()
    with pytest.raises(ValueError, match="source_system"):
        GcpBillingExtractor(
            client=fake,
            source_system=" ",
            source_name="detailed_usage_cost",
            scope_type="billing_account",
            scope_id=None,
            source_schema_version="v1",
            allow_current_day=False,
        )
