"""Build the shared GCP directory using the standard DET ETL lifecycle."""

from __future__ import annotations

import google.auth
from det_sdk import DataTelemetryClient
from google.auth.transport.requests import AuthorizedSession

from finops_batches.application.base_job import DataBatchJob
from finops_batches.config import Settings
from finops_batches.infrastructure.gcp_project_discovery_repository import (
    ProjectDirectory,
)
from finops_batches.providers.gcp.project_discovery import (
    DiscoverySettings,
    ProjectDiscoveryExtractor,
    ProjectDiscoveryTransformer,
)
from finops_batches.providers.gcp.rest_client import GcpRestClient


def build_gcp_project_discovery_job(settings: Settings) -> DataBatchJob:
    if not settings.finops_database_url.strip():
        raise ValueError("FINOPS_DATABASE_URL required")
    discovery = DiscoverySettings()
    discovery.validate_scope()
    credentials, _ = google.auth.default(
        scopes=["https://www.googleapis.com/auth/cloud-platform"]
    )
    extractor = ProjectDiscoveryExtractor(
        GcpRestClient(AuthorizedSession(credentials)), discovery
    )
    try:
        loader = ProjectDirectory(settings.finops_database_url)
    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="gcp.projects.discovery.daily",
        provider="gcp",
        source="gcp_resource_manager_service_usage",
        target_dataset="finops_gcp_project_directory",
        extractor=extractor,
        transformer=ProjectDiscoveryTransformer(),
        loader=loader,
        telemetry=telemetry,
    )
