from __future__ import annotations

from collections.abc import Iterable, Iterator
from datetime import UTC, date, datetime
from typing import Protocol, cast
from unittest.mock import MagicMock

import pytest
from google.cloud import bigquery
from google.cloud.bigquery import QueryJobConfig, ScalarQueryParameter

from finops_batches.providers.gcp.billing_client import (
    BigQueryClientProtocol,
    GcpDetailedBillingBigQueryClient,
)


class ApiReprProtocol(Protocol):
    def to_api_repr(self) -> dict[str, object]: ...


class FakeRow:
    def __init__(self, values: dict[str, object]) -> None:
        self.values = values

    def __getitem__(self, key: str) -> object:
        return self.values[key]


class FakeRows:
    def __init__(self, pages: list[list[FakeRow]]) -> None:
        self._pages = pages

    @property
    def pages(self) -> Iterator[Iterable[FakeRow]]:
        return iter(self._pages)


class FakeJob:
    def __init__(self, rows: FakeRows) -> None:
        self.rows = rows
        self.timeout: float | None = None
        self.page_size: int | None = None

    def result(
        self,
        *,
        timeout: float | None = None,
        page_size: int | None = None,
    ) -> FakeRows:
        self.timeout = timeout
        self.page_size = page_size
        return self.rows


class FakeClient:
    def __init__(self, pages: list[list[FakeRow]]) -> None:
        self.job = FakeJob(FakeRows(pages))
        self.query_text: str | None = None
        self.job_config: bigquery.QueryJobConfig | None = None
        self.location: str | None = None
        self.closed = False

    def query(
        self,
        query: str,
        *,
        job_config: bigquery.QueryJobConfig | None = None,
        location: str | None = None,
    ) -> FakeJob:
        self.query_text = query
        self.job_config = job_config
        self.location = location
        return self.job

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


def make_client(
    fake: FakeClient,
    *,
    max_pages: int = 10,
) -> GcpDetailedBillingBigQueryClient:
    return GcpDetailedBillingBigQueryClient(
        source_table="billing-project.dataset.billing_view",
        project_id="query-project",
        location="EU",
        export_timezone="UTC",
        page_size=2,
        query_timeout_seconds=30.0,
        max_pages=max_pages,
        maximum_bytes_billed=123456,
        client=cast(BigQueryClientProtocol, fake),
    )


def test_iter_export_rows_paginates_and_preserves_positions() -> None:
    fake = FakeClient(
        [
            [
                FakeRow(
                    {
                        "payload": '{"cost":1}',
                        "export_time": datetime(2026, 8, 1, tzinfo=UTC),
                    }
                ),
                FakeRow(
                    {
                        "payload": '{"cost":2}',
                        "export_time": "2026-08-01T01:00:00Z",
                    }
                ),
            ],
            [
                FakeRow(
                    {
                        "payload": '{"cost":3}',
                        "export_time": datetime(2026, 8, 1, 2, 0, tzinfo=UTC),
                    }
                )
            ],
        ]
    )
    client = make_client(fake)

    rows = list(client.iter_export_rows(date(2026, 8, 1)))

    assert [(row.page_number, row.source_record_number) for row in rows] == [
        (1, 1),
        (1, 2),
        (2, 1),
    ]
    assert rows[1].export_time.tzinfo == UTC
    assert rows[2].export_time.tzinfo == UTC
    assert fake.job.timeout == 30.0
    assert fake.job.page_size == 2
    assert fake.location == "EU"
    assert fake.job_config is not None
    assert fake.job_config.maximum_bytes_billed == 123456
    assert fake.query_text is not None
    assert "TO_JSON_STRING(src)" in fake.query_text
    assert "src.export_time >= TIMESTAMP(@business_date" in fake.query_text
    assert "ORDER BY export_time, source_row_hash" in fake.query_text


def test_iter_export_rows_rejects_too_many_pages() -> None:
    fake = FakeClient([[], []])
    client = make_client(fake, max_pages=1)
    with pytest.raises(RuntimeError, match="MAX_PAGES_EXCEEDED"):
        list(client.iter_export_rows(date(2026, 8, 1)))


def test_iter_export_rows_rejects_empty_payload() -> None:
    fake = FakeClient(
        [[FakeRow({"payload": " ", "export_time": "2026-08-01T00:00:00Z"})]]
    )
    with pytest.raises(ValueError, match="payload"):
        list(make_client(fake).iter_export_rows(date(2026, 8, 1)))


def test_iter_export_rows_rejects_invalid_datetime() -> None:
    fake = FakeClient([[FakeRow({"payload": "{}", "export_time": "bad"})]])
    with pytest.raises(ValueError, match="ISO"):
        list(make_client(fake).iter_export_rows(date(2026, 8, 1)))


def test_iter_export_rows_rejects_wrong_datetime_type() -> None:
    fake = FakeClient([[FakeRow({"payload": "{}", "export_time": 42})]])
    with pytest.raises(TypeError, match="datetime"):
        list(make_client(fake).iter_export_rows(date(2026, 8, 1)))


@pytest.mark.parametrize(
    "source",
    [
        "",
        "project.dataset",
        "project.dataset.table.extra",
        "project.data set.table",
        "*.d.t",
    ],
)
def test_source_table_validation(source: str) -> None:
    fake = FakeClient([])
    with pytest.raises(ValueError, match="GCP_BILLING_BQ_SOURCE"):
        GcpDetailedBillingBigQueryClient(
            source_table=source,
            project_id=None,
            location="EU",
            export_timezone="UTC",
            page_size=1,
            query_timeout_seconds=1.0,
            max_pages=1,
            maximum_bytes_billed=None,
            client=cast(BigQueryClientProtocol, fake),
        )


def _make_with_numeric_values(
    *,
    page_size: int = 1,
    query_timeout_seconds: float = 1.0,
    max_pages: int = 1,
    maximum_bytes_billed: int | None = 1,
) -> GcpDetailedBillingBigQueryClient:
    return GcpDetailedBillingBigQueryClient(
        source_table="p.d.t",
        project_id=None,
        location="EU",
        export_timezone="UTC",
        page_size=page_size,
        query_timeout_seconds=query_timeout_seconds,
        max_pages=max_pages,
        maximum_bytes_billed=maximum_bytes_billed,
        client=cast(BigQueryClientProtocol, FakeClient([])),
    )


def test_page_size_guard() -> None:
    with pytest.raises(ValueError, match="page_size"):
        _make_with_numeric_values(page_size=0)


def test_timeout_guard() -> None:
    with pytest.raises(ValueError, match="query_timeout_seconds"):
        _make_with_numeric_values(query_timeout_seconds=0.0)


def test_max_pages_guard() -> None:
    with pytest.raises(ValueError, match="max_pages"):
        _make_with_numeric_values(max_pages=0)


def test_maximum_bytes_billed_guard() -> None:
    with pytest.raises(ValueError, match="maximum_bytes_billed"):
        _make_with_numeric_values(maximum_bytes_billed=0)


def test_required_string_guard() -> None:
    with pytest.raises(ValueError, match="location"):
        GcpDetailedBillingBigQueryClient(
            source_table="p.d.t",
            project_id=None,
            location=" ",
            export_timezone="UTC",
            page_size=1,
            query_timeout_seconds=1.0,
            max_pages=1,
            maximum_bytes_billed=None,
            client=cast(BigQueryClientProtocol, FakeClient([])),
        )


def test_close_delegates_to_google_client() -> None:
    fake = FakeClient([])
    client = make_client(fake)
    client.close()
    assert fake.closed is True


def test_default_google_client_path_and_properties(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """Exercise the default construction branch without real Google credentials."""
    fake = FakeClient([])
    factory = MagicMock(return_value=fake)
    credential_lookup = MagicMock(
        side_effect=AssertionError("Unexpected Google credential lookup")
    )
    monkeypatch.setattr(
        "finops_batches.providers.gcp.billing_client.GoogleBigQueryClient", factory
    )
    monkeypatch.setattr("google.auth.default", credential_lookup)
    client = GcpDetailedBillingBigQueryClient(
        source_table="p.d.t",
        project_id="query-project",
        location="EU",
        export_timezone="UTC",
        page_size=1,
        query_timeout_seconds=1.0,
        max_pages=1,
        maximum_bytes_billed=None,
    )
    factory.assert_called_once_with(project="query-project", location="EU")
    credential_lookup.assert_not_called()
    assert client.source_table == "p.d.t"
    assert client.location == "EU"
    assert client.export_timezone == "UTC"
    client.close()
    assert fake.closed is True


def test_query_job_config_omits_maximum_bytes_billed_when_not_configured() -> None:
    job_config = QueryJobConfig(
        query_parameters=[
            ScalarQueryParameter(
                "business_date",
                "DATE",
                date(2026, 11, 3),
            ),
            ScalarQueryParameter(
                "export_timezone",
                "STRING",
                "UTC",
            ),
        ],
        use_legacy_sql=False,
    )

    typed_job_config = cast(ApiReprProtocol, job_config)
    payload = typed_job_config.to_api_repr()
    query = cast(dict[str, object], payload["query"])

    assert "maximumBytesBilled" not in query


def test_query_job_config_sets_maximum_bytes_billed_when_configured() -> None:
    job_config = QueryJobConfig(
        query_parameters=[
            ScalarQueryParameter(
                "business_date",
                "DATE",
                date(2026, 11, 3),
            ),
            ScalarQueryParameter(
                "export_timezone",
                "STRING",
                "UTC",
            ),
        ],
        use_legacy_sql=False,
    )

    job_config.maximum_bytes_billed = 10_737_418_240

    typed_job_config = cast(ApiReprProtocol, job_config)
    payload = typed_job_config.to_api_repr()
    query = cast(dict[str, object], payload["query"])

    assert query["maximumBytesBilled"] == "10737418240"
