"""Production composition for direct MCP structured-result ingestion."""

from __future__ import annotations

import os
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Optional

from arr_ingestion.artifacts import ArtifactStore
from arr_ingestion.direct_postgres import PostgresDirectIngestionRepository
from arr_ingestion.direct_service import DirectSubmissionService
from arr_ingestion.direct_validation import DirectResultValidator
from arr_ingestion.postgres import DatabaseConfig
from arr_ingestion.validation import ProcessorPolicy
from arr_processing.policy import load_legacy_direct_processor_policy
from arr_storage.aliyun_oss_v2 import AliyunOssConfig, AliyunOssV2Client
from arr_storage.contracts import ObjectKeyPolicy
from arr_storage.remote import CloudObjectBackend
from arr_storage.store import ManagedObjectStore


@dataclass
class DirectIngestionRuntime:
    """Own the direct service and its optional provider cleanup callback."""

    service: DirectSubmissionService
    close_callback: Optional[Callable[[], None]] = None

    def close(self) -> None:
        if self.close_callback is not None:
            self.close_callback()


def compose_direct_ingestion(
    *,
    object_store: ArtifactStore,
    processor_policy: ProcessorPolicy,
    connect: Optional[Callable[[str], Any]] = None,
) -> DirectIngestionRuntime:
    """Compose the business service without binding it to an MCP framework."""

    database_config = (
        DatabaseConfig("controlled")
        if connect is not None
        else DatabaseConfig.from_environment()
    )
    repository = PostgresDirectIngestionRepository(
        database_config,
        connect=connect,
    )
    return DirectIngestionRuntime(
        DirectSubmissionService(
            DirectResultValidator(object_store, processor_policy),
            repository,
        )
    )


def compose_oss_direct_ingestion(
    *,
    project_root: Path,
    connect: Optional[Callable[[str], Any]] = None,
) -> DirectIngestionRuntime:
    """Compose the direct service with the guarded private Aliyun OSS reader."""

    oss_client = AliyunOssV2Client(AliyunOssConfig.from_environment())
    try:
        oss_client.assert_immutable_writes_supported()
        object_store = ManagedObjectStore(
            CloudObjectBackend(oss_client),
            ObjectKeyPolicy(os.environ.get("ARR_OBJECT_PREFIX", "arr")),
        )
        runtime = compose_direct_ingestion(
            object_store=object_store,
            processor_policy=load_legacy_direct_processor_policy(project_root),
            connect=connect,
        )
        runtime.close_callback = oss_client.close
        return runtime
    except Exception:
        try:
            oss_client.close()
        except Exception:
            pass
        raise
