"""Validate complete job wiring with only external constructors doubled."""

from __future__ import annotations

from collections.abc import Callable
from importlib import import_module
from typing import Protocol, cast
from unittest.mock import MagicMock

import pytest

pytest.importorskip("det_sdk")

from finops_batches.application.base_job import DataBatchJob
from finops_batches.config import Settings


class JobTelemetry(Protocol):
    """Read-only metadata boundary, independent of the private SDK's stubs."""

    @property
    def telemetry(self) -> object:
        """Expose the constructed telemetry dependency for identity checks."""
        ...


def settings(**changes: object) -> Settings:
    """Supply explicit non-secret settings and override all external connection settings."""
    config = Settings(
        finops_database_url="sqlite://",
        azure_tenant_id="fake-tenant",
        azure_client_id="fake-client",
        azure_client_secret="fake-secret",
        azure_subscription_id="sub",
        azure_rate_card_currency="EUR",
        azure_retail_prices_currency_code="EUR",
        telemetry_config_path="no-real-det.yaml",
    )
    return config.model_copy(update=changes)


@pytest.mark.parametrize(
    "module_name,builder_name,dataset",
    [
        (
            "pricing_jobs",
            "build_azure_retail_prices_bronze_job",
            "azure_retail_prices_bronze",
        ),
        (
            "pricing_jobs",
            "build_azure_retail_prices_silver_job",
            "azure_retail_prices_silver",
        ),
        (
            "pricing_jobs",
            "build_azure_sponsorship_rate_card_bronze_job",
            "azure_sponsorship_rate_card_bronze",
        ),
        (
            "pricing_jobs",
            "build_azure_sponsorship_rate_card_silver_job",
            "azure_sponsorship_rate_card_silver",
        ),
        (
            "retail_price_catalog_job",
            "build_azure_retail_prices_job",
            "azure_retail_prices_bronze",
        ),
        (
            "sponsorship_focus_job",
            "build_azure_sponsorship_focus_job",
            "azure_sponsorship_focus_silver",
        ),
        (
            "sponsorship_usage_silver_job",
            "build_azure_sponsorship_usage_silver_job",
            "azure_sponsorship_usage_silver",
        ),
        (
            "sponsorship_tag_discovery_job",
            "build_azure_sponsorship_tag_discovery_job",
            "finops_tag_governance",
        ),
        ("gcp_billing_jobs", "build_gcp_billing_bronze_job", "gcp_billing_bronze"),
        ("gcp_billing_jobs", "build_gcp_billing_silver_job", "gcp_billing_silver"),
    ],
)
def test_factories_use_configured_dataset_database_and_telemetry(
    monkeypatch: pytest.MonkeyPatch, module_name: str, builder_name: str, dataset: str
) -> None:
    """Assert actual DataBatchJob composition, never call Azure/GCP/DET services."""
    module = import_module("finops_batches.application." + module_name)
    constructors = (
        "AzureArmTokenProvider",
        "AzureRetailPricesClient",
        "AzureRetailPriceCatalogClient",
        "AzureSponsorshipRateCardClient",
        "SqlAlchemyTableLoader",
        "HistoricalPricingSilverLoader",
        "PricingRawBronzeExtractor",
        "AzureRetailPriceHistoryLoader",
        "AzureSponsorshipFocusExtractor",
        "AzureSponsorshipFocusLoader",
        "AzureSponsorshipUsageBronzeExtractor",
        "SnapshotUsageExtractor",
        "SnapshotFocusExtractor",
        "AzureSnapshotLoader",
        "AzureTagGovernanceExtractor",
        "TagGovernanceLoader",
        "GcpDetailedBillingBigQueryClient",
        "GcpBillingBronzeExtractor",
        "SqlAlchemyReplaceByDayLoader",
        "GcpBillingExtractor",
    )
    doubles: dict[str, MagicMock] = {}
    for name in constructors:
        if hasattr(module, name):
            doubles[name] = MagicMock()
            monkeypatch.setattr(module, name, doubles[name])
    expected_telemetry = MagicMock()
    telemetry_factory = MagicMock(return_value=expected_telemetry)
    monkeypatch.setattr(module.DataTelemetryClient, "from_yaml", telemetry_factory)
    monkeypatch.setenv("GCP_BILLING_BQ_SOURCE", "p.d.t")
    builder = cast(Callable[[Settings], DataBatchJob], getattr(module, builder_name))
    config = settings()
    job = builder(config)
    try:
        assert isinstance(job, DataBatchJob)
        assert job.target_dataset == dataset
        telemetry_factory.assert_called_once_with(config.telemetry_config_path)
        assert cast(JobTelemetry, job).telemetry is expected_telemetry
        for name, double in doubles.items():
            for call in double.call_args_list:
                if "database_url" in call.kwargs:
                    assert call.kwargs["database_url"] == "sqlite://"
    finally:
        job.close()
    expected_telemetry.close.assert_called_once()


@pytest.mark.parametrize(
    "changes", [{"finops_database_url": ""}, {"azure_rate_card_currency": "USD"}]
)
def test_focus_factory_refuses_missing_database_and_cross_currency(
    changes: dict[str, object],
) -> None:
    from finops_batches.application.sponsorship_focus_job import (
        build_azure_sponsorship_focus_job,
    )

    with pytest.raises(ValueError):
        build_azure_sponsorship_focus_job(settings(**changes))


def test_bootstrap_requires_credentials_before_api_construction(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from finops_batches import bootstrap

    with pytest.raises(ValueError, match="AZURE_TENANT_ID"):
        bootstrap.build_azure_sponsorship_job(settings(azure_tenant_id=""))
    for name in (
        "AzureArmTokenProvider",
        "AzureSponsorshipUsageClient",
        "SnapshotBillingExtractor",
        "AzureSnapshotLoader",
    ):
        monkeypatch.setattr(bootstrap, name, MagicMock())
    telemetry = MagicMock()
    monkeypatch.setattr(
        "finops_batches.bootstrap.DataTelemetryClient.from_yaml", telemetry
    )
    job = bootstrap.build_azure_sponsorship_job(settings())
    try:
        assert job.target_dataset == "azure_sponsorship_billing_bronze"
        assert cast(JobTelemetry, job).telemetry is telemetry.return_value
    finally:
        job.close()
