from __future__ import annotations

from det_sdk import DataTelemetryClient

from finops_batches.application.base_job import DataBatchJob
from finops_batches.application.registry import BatchRegistry
from finops_batches.config import Settings
from finops_batches.infrastructure.mariadb_partition_manager import (
    MariaDbMonthlyPartitionManager,
)
from finops_batches.infrastructure.partition_aware_loader import (
    PartitionAwareReplaceByDayLoader,
)
from finops_batches.infrastructure.replace_by_day_loader import (
    SqlAlchemyReplaceByDayLoader,
)
from finops_batches.providers.gcp.billing import GcpBillingExtractor
from finops_batches.providers.gcp.billing_client import (
    GcpDetailedBillingBigQueryClient,
)
from finops_batches.providers.gcp.billing_silver import (
    GcpBillingBronzeExtractor,
    GcpBillingSilverTransformer,
)
from finops_batches.providers.gcp.config import GcpBillingSettings
from finops_batches.providers.gcp.focus_silver import (
    GcpFocusBronzeExtractor,
    GcpFocusSilverTransformer,
)
from finops_batches.providers.gcp.raw_bronze import GcpRawJsonBronzeTransformer

GCP_BILLING_BRONZE_JOB = "gcp.billing.daily"
GCP_BILLING_SILVER_JOB = "gcp.billing.silver.daily"


def build_gcp_billing_bronze_job(
    settings: Settings,
    gcp_settings: GcpBillingSettings | None = None,
) -> DataBatchJob:
    """Build BigQuery -> RAW Bronze with DET instrumentation."""
    config = gcp_settings or GcpBillingSettings()
    database_url = _required_database_url(settings)

    client = GcpDetailedBillingBigQueryClient(
        source_table=config.gcp_billing_bq_source,
        project_id=config.query_project_id,
        location=config.gcp_billing_bq_location,
        export_timezone=config.gcp_billing_export_timezone,
        page_size=config.gcp_billing_page_size,
        query_timeout_seconds=config.gcp_billing_query_timeout_seconds,
        max_pages=config.gcp_billing_max_pages,
        maximum_bytes_billed=config.maximum_bytes_billed,
    )

    return DataBatchJob(
        definition_key=GCP_BILLING_BRONZE_JOB,
        provider="gcp",
        source=config.gcp_billing_source_name,
        target_dataset=config.gcp_billing_bronze_table,
        extractor=GcpBillingExtractor(
            client=client,
            source_system=config.gcp_billing_source_system,
            source_name=config.gcp_billing_source_name,
            scope_type=config.gcp_billing_scope_type,
            scope_id=config.scope_id,
            source_schema_version=config.gcp_billing_source_schema_version,
            allow_current_day=config.gcp_billing_allow_current_day,
        ),
        transformer=GcpRawJsonBronzeTransformer(),
        loader=SqlAlchemyReplaceByDayLoader(
            database_url=database_url,
            table_name=config.gcp_billing_bronze_table,
            date_column="business_date",
            reject_empty=config.gcp_billing_reject_empty,
        ),
        telemetry=DataTelemetryClient.from_yaml(settings.telemetry_config_path),
    )


def build_gcp_billing_silver_job(
    settings: Settings,
    gcp_settings: GcpBillingSettings | None = None,
) -> DataBatchJob:
    """Build local RAW Bronze -> provider Silver; no remote API is called."""
    config = gcp_settings or GcpBillingSettings()
    database_url = _required_database_url(settings)

    return DataBatchJob(
        definition_key=GCP_BILLING_SILVER_JOB,
        provider="gcp",
        source="billing_bronze",
        target_dataset=config.gcp_billing_silver_table,
        extractor=GcpBillingBronzeExtractor(
            database_url=database_url,
            table_name=config.gcp_billing_bronze_table,
        ),
        transformer=GcpBillingSilverTransformer(),
        loader=SqlAlchemyReplaceByDayLoader(
            database_url=database_url,
            table_name=config.gcp_billing_silver_table,
            date_column="business_date",
            reject_empty=config.gcp_billing_reject_empty,
        ),
        telemetry=DataTelemetryClient.from_yaml(settings.telemetry_config_path),
    )


def register_gcp_billing_jobs(
    *,
    registry: BatchRegistry,
    settings: Settings,
    gcp_settings: GcpBillingSettings | None = None,
) -> None:
    """Register both GCP billing jobs in the existing application registry."""
    config = gcp_settings or GcpBillingSettings()
    registry.register(
        GCP_BILLING_BRONZE_JOB,
        lambda: build_gcp_billing_bronze_job(settings, config),
    )
    registry.register(
        GCP_BILLING_SILVER_JOB,
        lambda: build_gcp_billing_silver_job(settings, config),
    )
    registry.register(
        "gcp.focus.daily",
        lambda: build_gcp_focus_job(settings),
    )


def build_gcp_focus_job(
    settings: Settings,
) -> DataBatchJob:
    base_loader = SqlAlchemyReplaceByDayLoader(
        database_url=settings.finops_database_url,
        table_name="gcp_focus_silver",
        date_column="business_date",
    )

    loader = PartitionAwareReplaceByDayLoader(
        delegate=base_loader,
        partition_manager=(
            MariaDbMonthlyPartitionManager(
                database_url=settings.finops_database_url,
                table_name="gcp_focus_silver",
            )
        ),
        date_column="business_date",
    )

    return DataBatchJob(
        definition_key="gcp.focus.daily",
        provider="gcp",
        source="gcp_billing_bronze",
        target_dataset="gcp_focus_silver",
        extractor=GcpFocusBronzeExtractor(
            database_url=settings.finops_database_url,
            table_name="gcp_billing_bronze",
        ),
        transformer=GcpFocusSilverTransformer(),
        loader=loader,
        telemetry=DataTelemetryClient.from_yaml(settings.telemetry_config_path),
    )


def _required_database_url(settings: Settings) -> str:
    value = settings.finops_database_url.strip()
    if not value:
        raise ValueError("FINOPS_DATABASE_URL est obligatoire.")
    return value
