"""Azure monthly carbon jobs targeting the same Gold and state as GCP."""

from __future__ import annotations

from det_sdk import DataTelemetryClient

from finops_batches.application.base_job import DataBatchJob
from finops_batches.config import Settings
from finops_batches.infrastructure.carbon_loader import CarbonMonthLoader
from finops_batches.providers.azure.auth import AzureArmTokenProvider
from finops_batches.providers.azure.carbon import (
    AzureCarbonBronzeExtractor,
    AzureCarbonClient,
    AzureCarbonSettings,
    AzureCarbonTransformer,
)
from finops_batches.providers.gcp.carbon import CarbonLocalExtractor


def build_azure_carbon_job(settings: Settings, stage: str) -> DataBatchJob:
    if not settings.finops_database_url.strip():
        raise ValueError("FINOPS_DATABASE_URL required")
    extractor: AzureCarbonBronzeExtractor | CarbonLocalExtractor
    if stage == "BRONZE":
        config = AzureCarbonSettings()
        subscriptions = config.subscriptions(settings.azure_subscription_id)
        credential = AzureArmTokenProvider(
            tenant_id=settings.azure_tenant_id,
            client_id=settings.azure_client_id,
            client_secret=settings.azure_client_secret,
        )
        try:
            client = AzureCarbonClient(
                config, credential.get_token, on_close=credential.close
            )
        except Exception:
            credential.close()
            raise
        extractor = AzureCarbonBronzeExtractor(client, subscriptions)
    elif stage in {"SILVER", "GOLD"}:
        extractor = CarbonLocalExtractor(
            database_url=settings.finops_database_url, stage=stage, provider="AZURE"
        )
    else:
        raise ValueError("CARBON_INVALID_STAGE")
    try:
        loader = CarbonMonthLoader(
            database_url=settings.finops_database_url, stage=stage, provider="AZURE"
        )
    except Exception:
        extractor.close()
        raise
    try:
        telemetry = DataTelemetryClient.from_yaml(settings.telemetry_config_path)
    except Exception:
        extractor.close()
        loader.close()
        raise
    return DataBatchJob(
        definition_key=f"azure.carbon.{stage.lower()}.monthly",
        provider="azure",
        source="carbon_optimization"
        if stage == "BRONZE"
        else "azure_carbon_bronze"
        if stage == "SILVER"
        else "azure_carbon_silver",
        target_dataset="finops_carbon_gold"
        if stage == "GOLD"
        else f"azure_carbon_{stage.lower()}",
        extractor=extractor,
        transformer=AzureCarbonTransformer(),
        loader=loader,
        telemetry=telemetry,
    )
