Spaces:
Paused

File size: 6,879 Bytes
a418bb2
d80907b
a418bb2
d80907b
 
a418bb2
d80907b
 
 
 
 
 
a418bb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d80907b
 
 
 
 
 
 
a418bb2
 
 
d80907b
a418bb2
 
 
 
 
 
 
 
d80907b
a418bb2
 
 
 
 
 
 
 
d80907b
a418bb2
 
 
2e7af6d
d80907b
2e7af6d
 
a418bb2
 
 
 
d80907b
 
 
 
 
 
 
a418bb2
 
 
d80907b
a418bb2
 
 
 
2e7af6d
d80907b
2e7af6d
 
a418bb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d80907b
 
 
 
 
 
 
 
 
 
 
a418bb2
d80907b
 
a418bb2
 
 
d80907b
a418bb2
 
d80907b
 
a418bb2
 
 
 
 
 
 
 
d80907b
a418bb2
 
 
 
 
d80907b
 
 
a418bb2
 
d80907b
a418bb2
2e7af6d
a418bb2
 
 
 
 
d80907b
 
a418bb2
d80907b
 
 
 
 
 
 
 
 
 
 
 
 
a418bb2
 
 
 
d80907b
 
 
 
 
 
 
 
 
a418bb2
d80907b
 
a418bb2
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""
Educa — Education & Training Intelligence Engine

Domain: Education
Version: 1.0.0

Manages: Courses, simulations, certifications, skill assessments,
         training modules, competencies, CME credits.

Standards: ACGME, CME, WFME

Follows the DomainEngine pattern established by SurgioEngine.
"""

from __future__ import annotations

from pathlib import Path
from typing import Any, Dict, Optional, Set
from uuid import UUID, uuid4

import structlog

from core.engines.base_engine import BaseEngine

logger = structlog.get_logger(__name__)

_APP_ROOT = Path(__file__).resolve().parent


class EducaEngine(BaseEngine):
    """
    Education & Training Intelligence Engine.

    Orchestrates curriculum management, resident training, simulation
    labs, competency assessment, CME tracking, and learning analytics.

    Lifecycle:
        register → initialize → READY → handle_event / create_case → shutdown

    Pillars composed:
        journal, protocol, assessment, skill, report, analytics
        (optional: scheduling, notification, communication, document, workflow)
    """

    def __init__(self) -> None:
        super().__init__(app_root=_APP_ROOT)

    # ── Lifecycle hooks ───────────────────────────────────────────

    async def _setup(self) -> None:
        """Initialise education-specific services and competency frameworks."""
        logger.info(
            "educa_services_initialized",
            version=self.manifest.version,
        )

    async def _teardown(self) -> None:
        logger.info("educa_services_teardown")

    # ── Event routing ─────────────────────────────────────────────

    def get_subscribed_event_types(self) -> Set[str]:
        return {
            "surgio.surgery_completed",  # Log case as residency experience
            "surgio.complication_recorded",  # Flag for debrief / learning event
            "platform.tenant_activated",  # Load default training curricula
            "platform.user_created",  # Enrol new user in onboarding programme
        }

    def get_emitted_event_types(self) -> Set[str]:
        return {
            "educa.training_started",
            "educa.training_completed",
            "educa.certification_issued",
            "educa.competency_assessed",
            "educa.cme_credit_awarded",
            "educa.milestone_reached",
            "educa.simulation_completed",
        }

    async def handle_event(self, event: Dict[str, Any]) -> None:
        """Route platform events to internal handlers. Never raises."""
        event_type = event.get("event_type", "")
        tenant_id = event.get("tenant_id", "")

        handlers = {
            "surgio.surgery_completed": self._on_surgery_completed,
            "surgio.complication_recorded": self._on_complication_recorded,
            "platform.tenant_activated": self._on_tenant_activated,
            "platform.user_created": self._on_user_created,
        }

        handler = handlers.get(event_type)
        if handler:
            try:
                await handler(event)
            except Exception as exc:
                logger.error(
                    "educa_event_handler_error",
                    event_type=event_type,
                    tenant_id=tenant_id,
                    error=str(exc),
                )

    # ── Case Management ───────────────────────────────────────────

    async def create_case(
        self,
        data: Dict[str, Any],
        tenant_id: UUID,
        actor_id: UUID,
    ) -> UUID:
        """
        Create a training or certification case.

        Args:
            data: Case payload (case_type, course_id, trainee_id, target_competencies…)
            tenant_id: Tenant isolation.
            actor_id: Creating educator/supervisor.

        Returns:
            UUID of the new training case.
        """
        case_id = uuid4()
        case_type = data.get("case_type", "training")

        logger.info(
            "educa_case_created",
            case_id=str(case_id),
            case_type=case_type,
            tenant_id=str(tenant_id),
            actor_id=str(actor_id),
            course_id=data.get("course_id", ""),
            trainee_id=data.get("trainee_id", ""),
        )
        return case_id

    async def get_case(
        self,
        case_id: UUID,
        tenant_id: UUID,
    ) -> Optional[Dict[str, Any]]:
        """Retrieve a training case with tenant isolation."""
        logger.debug(
            "educa_get_case",
            case_id=str(case_id),
            tenant_id=str(tenant_id),
        )
        return None  # wired to EducaService in production

    # ── API Router ────────────────────────────────────────────────

    def get_router(self):
        """Return Educa FastAPI router."""
        from apps.educa.router import router

        return router

    # ── Internal Event Handlers ───────────────────────────────────

    async def _on_surgery_completed(self, event: Dict[str, Any]) -> None:
        """Log a completed surgery as a residency case experience."""
        data = event.get("data", {})
        logger.info(
            "educa_logging_case_experience",
            case_id=data.get("case_id"),
            procedure_code=data.get("procedure_code"),
            tenant_id=event.get("tenant_id"),
        )

    async def _on_complication_recorded(self, event: Dict[str, Any]) -> None:
        """Create a structured debrief / learning event for the complication."""
        data = event.get("data", {})
        logger.info(
            "educa_scheduling_debrief",
            case_id=data.get("case_id"),
            complication_type=data.get("complication_type"),
            tenant_id=event.get("tenant_id"),
        )

    async def _on_tenant_activated(self, event: Dict[str, Any]) -> None:
        """Load default training curricula for a newly activated tenant."""
        logger.info(
            "educa_loading_default_curricula",
            tenant_id=event.get("tenant_id"),
        )

    async def _on_user_created(self, event: Dict[str, Any]) -> None:
        """Enrol a new user into the institution's onboarding programme."""
        data = event.get("data", {})
        logger.info(
            "educa_enrolling_new_user",
            user_id=data.get("user_id"),
            tenant_id=event.get("tenant_id"),
        )


# Module-level engine instance — auto-discovered by EngineRegistry
engine = EducaEngine()