from __future__ import annotations

from collections.abc import Iterator
from datetime import UTC, date, datetime
from typing import Protocol, cast
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError

from finops_batches.domain.models import BatchExecutionContext, Record
from finops_batches.providers.gcp.billing_types import GcpBillingExportRow


class GcpBillingClientProtocol(Protocol):
    @property
    def source_table(self) -> str: ...

    @property
    def location(self) -> str: ...

    @property
    def export_timezone(self) -> str: ...

    def iter_export_rows(
        self,
        business_date: date,
    ) -> Iterator[GcpBillingExportRow]: ...

    def close(self) -> None: ...


class GcpBillingExtractor:
    """Extract one completed export-time day from GCP Cloud Billing BigQuery."""

    def __init__(
        self,
        *,
        client: GcpBillingClientProtocol,
        source_system: str,
        source_name: str,
        scope_type: str,
        scope_id: str | None,
        source_schema_version: str,
        allow_current_day: bool,
    ) -> None:
        self._client = client
        self._source_system = self._required_string(source_system, "source_system")
        self._source_name = self._required_string(source_name, "source_name")
        self._scope_type = self._required_string(scope_type, "scope_type")
        self._scope_id = scope_id.strip() if scope_id is not None else None
        self._source_schema_version = self._required_string(
            source_schema_version,
            "source_schema_version",
        )
        self._allow_current_day = allow_current_day

        try:
            self._timezone = ZoneInfo(client.export_timezone)
        except ZoneInfoNotFoundError as exc:
            raise ValueError(
                f"Fuseau GCP_BILLING_EXPORT_TIMEZONE inconnu: "
                f"{client.export_timezone!r}."
            ) from exc

    def extract(self, context: BatchExecutionContext) -> list[Record]:
        self._validate_business_date(context)

        request_context: dict[str, object] = {
            "source_table": self._client.source_table,
            "location": self._client.location,
            "export_timezone": self._client.export_timezone,
            "incremental_field": "export_time",
        }
        source_uri = f"bigquery://{self._client.source_table}"

        result: list[Record] = []
        for row in self._client.iter_export_rows(context.business_date):
            result.append(
                cast(
                    Record,
                    {
                        "provider_code": "GCP",
                        "source_system": self._source_system,
                        "source_name": self._source_name,
                        "scope_type": self._scope_type,
                        "scope_id": self._scope_id,
                        "business_date": context.business_date,
                        "source_uri_logical": source_uri,
                        "request_url": None,
                        "page_number": row.page_number,
                        "source_record_number": row.source_record_number,
                        "api_version": self._source_schema_version,
                        "request_context": request_context,
                        "payload": row.payload,
                    },
                )
            )

        return result

    def close(self) -> None:
        self._client.close()

    def _validate_business_date(self, context: BatchExecutionContext) -> None:
        today = datetime.now(UTC).astimezone(self._timezone).date()
        requested = context.business_date

        if requested > today:
            raise ValueError(
                "GCP_BILLING_FUTURE_DATE: la date demandée est future dans "
                f"le fuseau {self._client.export_timezone}."
            )
        if requested == today and not self._allow_current_day:
            raise ValueError(
                "GCP_BILLING_CURRENT_DAY_DISABLED: la journée export_time "
                "courante peut être incomplète."
            )

    @staticmethod
    def _required_string(value: str, field: str) -> str:
        normalized = value.strip()
        if not normalized:
            raise ValueError(f"{field} ne peut pas être vide.")
        return normalized
