from __future__ import annotations

import unittest
from unittest.mock import MagicMock, patch

from govoplan_core.celery_app import (
    celery,
    reconcile_workflow_instances,
)
from govoplan_core.core.modules import ModuleContext, ModuleManifest
from govoplan_core.core.registry import PlatformRegistry
from govoplan_core.core.workflows import (
    CAPABILITY_WORKFLOW_DEFINITION_CONTRIBUTIONS,
    CAPABILITY_WORKFLOW_RUNTIME_WORKER,
    CAPABILITY_WORKFLOW_TRIGGER_DISPATCHER,
    WorkflowDefinitionContribution,
    WorkflowDefinitionContributionProvider,
    WorkflowRuntimeWorker,
    WorkflowTriggerDispatcher,
    workflow_definition_contribution_hash,
    workflow_definition_contribution_provider,
    workflow_runtime_worker,
    workflow_trigger_dispatcher,
)


class _Worker:
    def reconcile_pending(self, session, *, now=None, limit=50):
        return {"inspected": 0, "advanced": 0}


class _ContributionProvider:
    def reconcile(self, session, *, tenant_ids=()):
        return {"created": 0, "tenant_ids": tuple(tenant_ids)}


class _TriggerDispatcher:
    def dispatch_due(self, session, *, now=None, limit=50):
        return {"selected": 0}

    def ingest_event(self, session, *, event):
        return {"queued": 0}


class WorkflowRuntimeWorkerTests(unittest.TestCase):
    def test_contribution_contract_hash_and_provider_are_stable(self) -> None:
        contribution = WorkflowDefinitionContribution(
            origin_module_id="example",
            origin_module_version="1.0.0",
            definition_key="approval",
            name="Approval",
            graph={"schema_version": 1, "nodes": [], "edges": []},
        )
        self.assertEqual(
            workflow_definition_contribution_hash(contribution),
            workflow_definition_contribution_hash(contribution),
        )
        provider = _ContributionProvider()
        self.assertIsInstance(provider, WorkflowDefinitionContributionProvider)
        registry = PlatformRegistry()
        registry.register(
            ModuleManifest(
                id="workflow_engine_test",
                name="Workflow Engine test",
                version="test",
                capability_factories={
                    CAPABILITY_WORKFLOW_DEFINITION_CONTRIBUTIONS: (
                        lambda _context: provider
                    ),
                },
            )
        )
        registry.configure_capability_context(
            ModuleContext(registry=registry, settings=object())
        )
        self.assertIs(
            provider,
            workflow_definition_contribution_provider(registry),
        )

    def test_contract_is_runtime_checkable_and_resolved(self) -> None:
        worker = _Worker()
        self.assertIsInstance(worker, WorkflowRuntimeWorker)
        registry = PlatformRegistry()
        registry.register(
            ModuleManifest(
                id="workflow_runtime_test",
                name="Workflow runtime test",
                version="test",
                capability_factories={
                    CAPABILITY_WORKFLOW_RUNTIME_WORKER: (lambda _context: worker),
                },
            )
        )
        registry.configure_capability_context(
            ModuleContext(registry=registry, settings=object())
        )

        self.assertIs(worker, workflow_runtime_worker(registry))
        self.assertIsNone(workflow_runtime_worker(PlatformRegistry()))

    def test_trigger_dispatch_contract_is_runtime_checkable_and_resolved(self) -> None:
        dispatcher = _TriggerDispatcher()
        self.assertIsInstance(dispatcher, WorkflowTriggerDispatcher)
        registry = PlatformRegistry()
        registry.register(
            ModuleManifest(
                id="workflow_trigger_test",
                name="Workflow trigger test",
                version="test",
                capability_factories={
                    CAPABILITY_WORKFLOW_TRIGGER_DISPATCHER: (
                        lambda _context: dispatcher
                    ),
                },
            )
        )
        registry.configure_capability_context(
            ModuleContext(registry=registry, settings=object())
        )

        self.assertIs(dispatcher, workflow_trigger_dispatcher(registry))
        self.assertIsNone(workflow_trigger_dispatcher(PlatformRegistry()))

    def test_celery_task_commits_reconciliation(self) -> None:
        session = MagicMock()
        database = MagicMock()
        database.SessionLocal.return_value.__enter__.return_value = session
        worker = MagicMock()
        worker.reconcile_pending.return_value = {
            "inspected": 2,
            "advanced": 1,
        }

        with (
            patch(
                "govoplan_core.celery_app._workflow_runtime_worker",
                return_value=worker,
            ),
            patch(
                "govoplan_core.db.session.get_database",
                return_value=database,
            ),
        ):
            result = reconcile_workflow_instances.run(25)

        worker.reconcile_pending.assert_called_once_with(session, limit=25)
        session.commit.assert_called_once_with()
        self.assertEqual(1, result["advanced"])

    def test_route_and_periodic_job_are_registered(self) -> None:
        self.assertEqual(
            {"queue": "workflow"},
            celery.conf.task_routes["govoplan.workflow.reconcile"],
        )
        schedule = celery.conf.beat_schedule["workflow-reconcile-every-five-seconds"]
        self.assertEqual("govoplan.workflow.reconcile", schedule["task"])
        self.assertEqual(5.0, schedule["schedule"])


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