from __future__ import annotations

import re

from pydantic import Field, field_validator

from finops_batches.config import BaseApplicationSettings

_MARIADB_TABLE_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")


class GcpBillingSettings(BaseApplicationSettings):
    """Externalized configuration for the GCP Cloud Billing pipeline."""

    gcp_billing_bq_project_id: str = Field(
        default="",
        validation_alias="GCP_BILLING_BQ_PROJECT_ID",
    )
    gcp_billing_bq_source: str = Field(
        default="",
        validation_alias="GCP_BILLING_BQ_SOURCE",
    )
    gcp_billing_bq_location: str = Field(
        default="EU",
        validation_alias="GCP_BILLING_BQ_LOCATION",
    )
    gcp_billing_export_timezone: str = Field(
        default="UTC",
        validation_alias="GCP_BILLING_EXPORT_TIMEZONE",
    )
    gcp_billing_page_size: int = Field(
        default=1000,
        ge=1,
        le=100_000,
        validation_alias="GCP_BILLING_PAGE_SIZE",
    )
    gcp_billing_query_timeout_seconds: float = Field(
        default=300.0,
        gt=0,
        validation_alias="GCP_BILLING_QUERY_TIMEOUT_SECONDS",
    )
    gcp_billing_max_pages: int = Field(
        default=10_000,
        ge=1,
        validation_alias="GCP_BILLING_MAX_PAGES",
    )
    gcp_billing_maximum_bytes_billed: int = Field(
        default=0,
        ge=0,
        validation_alias="GCP_BILLING_MAXIMUM_BYTES_BILLED",
    )
    gcp_billing_allow_current_day: bool = Field(
        default=False,
        validation_alias="GCP_BILLING_ALLOW_CURRENT_DAY",
    )
    gcp_billing_source_system: str = Field(
        default="gcp_cloud_billing_bigquery",
        validation_alias="GCP_BILLING_SOURCE_SYSTEM",
    )
    gcp_billing_source_name: str = Field(
        default="detailed_usage_cost",
        validation_alias="GCP_BILLING_SOURCE_NAME",
    )
    gcp_billing_scope_type: str = Field(
        default="billing_account",
        validation_alias="GCP_BILLING_SCOPE_TYPE",
    )
    gcp_billing_scope_id: str = Field(
        default="",
        validation_alias="GCP_BILLING_SCOPE_ID",
    )
    gcp_billing_source_schema_version: str = Field(
        default="gcp-detailed-export-v1",
        validation_alias="GCP_BILLING_SOURCE_SCHEMA_VERSION",
    )
    gcp_billing_bronze_table: str = Field(
        default="gcp_billing_bronze",
        validation_alias="GCP_BILLING_BRONZE_TABLE",
    )
    gcp_billing_silver_table: str = Field(
        default="gcp_billing_silver",
        validation_alias="GCP_BILLING_SILVER_TABLE",
    )
    gcp_billing_reject_empty: bool = Field(
        default=True,
        validation_alias="GCP_BILLING_REJECT_EMPTY",
    )

    @field_validator(
        "gcp_billing_bq_source",
        "gcp_billing_bq_location",
        "gcp_billing_export_timezone",
        "gcp_billing_source_system",
        "gcp_billing_source_name",
        "gcp_billing_scope_type",
        "gcp_billing_source_schema_version",
    )
    @classmethod
    def _non_empty(cls, value: str) -> str:
        normalized = value.strip()
        if not normalized:
            raise ValueError("La valeur ne peut pas être vide.")
        return normalized

    @field_validator(
        "gcp_billing_bronze_table",
        "gcp_billing_silver_table",
    )
    @classmethod
    def _safe_mariadb_table(cls, value: str) -> str:
        normalized = value.strip()
        if not _MARIADB_TABLE_RE.fullmatch(normalized):
            raise ValueError(
                "Le nom de table MariaDB doit contenir uniquement lettres, "
                "chiffres et underscore, et commencer par une lettre."
            )
        return normalized

    @property
    def maximum_bytes_billed(self) -> int | None:
        value = self.gcp_billing_maximum_bytes_billed
        return value if value > 0 else None

    @property
    def query_project_id(self) -> str | None:
        value = self.gcp_billing_bq_project_id.strip()
        return value or None

    @property
    def scope_id(self) -> str | None:
        value = self.gcp_billing_scope_id.strip()
        return value or None
