"""Factory and registry checks using mocked telemetry and SQL components."""

from __future__ import annotations

from unittest.mock import MagicMock

import pytest

pytest.importorskip("det_sdk")

from finops_batches.application import sponsorship_usage_gold_job as module
from finops_batches.bootstrap import build_registry
from finops_batches.config import Settings, load_batch_catalog


def test_factory_uses_existing_settings_and_telemetry(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setenv(
        "GCP_BILLING_BQ_SOURCE",
        "test-project.test_dataset.test_table",
    )
    """Reuse FINOPS_DATABASE_URL and DET settings without new credentials."""
    extractor_factory = MagicMock()
    loader_factory = MagicMock()
    telemetry_factory = MagicMock()
    monkeypatch.setattr(module, "SnapshotGoldExtractor", extractor_factory)
    monkeypatch.setattr(module, "AzureSnapshotGoldLoader", loader_factory)
    monkeypatch.setattr(module.DataTelemetryClient, "from_yaml", telemetry_factory)
    settings = Settings(
        finops_database_url="sqlite://", telemetry_config_path="local-telemetry.yaml"
    )
    job = module.build_azure_sponsorship_usage_gold_job(settings)
    try:
        assert job.definition_key == "azure.sponsorship.usage.gold.daily"
        assert job.target_dataset == "azure_sponsorship_usage_gold"
        extractor_factory.assert_called_once_with(database_url="sqlite://")
        loader_factory.assert_called_once_with(database_url="sqlite://")
        telemetry_factory.assert_called_once_with("local-telemetry.yaml")
    finally:
        job.close()
    extractor_factory.return_value.close.assert_called_once()
    loader_factory.return_value.close.assert_called_once()
    telemetry_factory.return_value.close.assert_called_once()


def test_factory_validates_database_and_closes_on_failure(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setenv(
        "GCP_BILLING_BQ_SOURCE",
        "test-project.test_dataset.test_table",
    )
    """Reject missing settings and close pools if later construction fails."""
    with pytest.raises(ValueError, match="FINOPS_DATABASE_URL"):
        module.build_azure_sponsorship_usage_gold_job(Settings(finops_database_url=" "))
    extractor_factory = MagicMock()
    loader_factory = MagicMock(side_effect=ValueError("DDL absent"))
    monkeypatch.setattr(module, "SnapshotGoldExtractor", extractor_factory)
    monkeypatch.setattr(module, "AzureSnapshotGoldLoader", loader_factory)
    with pytest.raises(ValueError, match="DDL absent"):
        module.build_azure_sponsorship_usage_gold_job(
            Settings(finops_database_url="sqlite://")
        )
    extractor_factory.return_value.close.assert_called_once()
    extractor_factory.reset_mock()
    loader_factory.side_effect = None
    monkeypatch.setattr(
        module.DataTelemetryClient,
        "from_yaml",
        MagicMock(side_effect=ValueError("DET absent")),
    )
    with pytest.raises(ValueError, match="DET absent"):
        module.build_azure_sponsorship_usage_gold_job(
            Settings(finops_database_url="sqlite://")
        )
    extractor_factory.return_value.close.assert_called_once()
    loader_factory.return_value.close.assert_called_once()


def test_catalog_and_registry_are_consistent(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv(
        "GCP_BILLING_BQ_SOURCE",
        "test-project.test_dataset.test_table",
    )
    """Ensure the new key is discoverable and resolves to the integrated factory."""
    from pathlib import Path

    from finops_batches import bootstrap

    expected = MagicMock()
    factory = MagicMock(return_value=expected)
    monkeypatch.setattr(bootstrap, "build_azure_sponsorship_usage_gold_job", factory)
    registry = build_registry(Settings())
    key = "azure.sponsorship.usage.gold.daily"
    assert key in registry.list_keys()
    assert registry.build(key) is expected
    catalog = load_batch_catalog(
        Path(__file__).resolve().parents[1] / "config/batches.yaml"
    )
    assert catalog.batches[key].target_dataset == "azure_sponsorship_usage_gold"
