from __future__ import annotations

import tempfile
import unittest
from pathlib import Path

from arr_ingestion.direct_postgres import PostgresDirectIngestionRepository
from arr_ingestion.direct_service import DirectSubmissionService
from arr_ingestion.direct_validation import DirectResultValidator
from arr_web.direct_ingestion_runtime import (
    DirectIngestionRuntime,
    compose_direct_ingestion,
)
from tests.test_arr_ingestion_validation import MemoryStore, policy


class DirectIngestionRuntimeTests(unittest.TestCase):
    def test_framework_neutral_composition_uses_direct_components(self) -> None:
        runtime = compose_direct_ingestion(
            object_store=MemoryStore({}),
            processor_policy=policy(),
            connect=lambda _dsn: None,
        )
        self.assertIsInstance(runtime.service, DirectSubmissionService)
        self.assertIsInstance(
            runtime.service._validator,
            DirectResultValidator,
        )
        self.assertIsInstance(
            runtime.service._repository,
            PostgresDirectIngestionRepository,
        )

    def test_close_callback_is_owned_by_runtime(self) -> None:
        calls: list[str] = []
        with tempfile.TemporaryDirectory() as temporary:
            root = Path(temporary)
            source = root / "source.xml"
            source.write_text("<RES_DETAIL/>", encoding="utf-8")
            runtime = DirectIngestionRuntime(
                service=compose_direct_ingestion(
                    object_store=MemoryStore({}),
                    processor_policy=policy(),
                    connect=lambda _dsn: None,
                ).service,
                close_callback=lambda: calls.append("closed"),
            )
            runtime.close()
        self.assertEqual(calls, ["closed"])


if __name__ == "__main__":
    unittest.main(verbosity=2)
