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
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
"""
Protocol Workflow Tool - Data Models
======================================

Domain-agnostic models for multi-step workflow orchestration with state
machine execution, guard-protected transitions, and cross-tool actions.

Entities:
    - ProtocolDefinition: Reusable state machine blueprint
    - ProtocolRun: Active execution of a protocol on a case / subject
    - ProtocolStep: Current and historical step records within a run
    - ProtocolTransition: Immutable record of each state change
    - ProtocolEvent: Immutable audit trail of all changes

Concepts:
    - States:       Discrete phases (e.g. pre_op, timeout, incision, closure)
    - Transitions:  Guard-protected moves between states
    - Guards:       Conditions that MUST be met to transition
    - Actions:      Side-effects executed on transition (start checklist, etc.)
    - Timeouts:     Max time in state before auto-escalation

Standards: FDA 21 CFR Part 11 (audit trail), HIPAA (tenant isolation)
Performance: Indexed on tenant_id, case_id for <200ms transitions
"""

from __future__ import annotations

from datetime import datetime, timezone
from enum import Enum
from typing import Any, Dict, List, Optional
from uuid import UUID, uuid4

from pydantic import BaseModel, ConfigDict, Field as PydanticField
from sqlmodel import Column, Field, JSON, SQLModel


# ============================================================================
# ENUMS - Shared vocabulary for all protocol implementations
# ============================================================================

class ProtocolStatus(str, Enum):
    """Protocol run lifecycle states"""
    NOT_STARTED = "not_started"    # Created but not yet begun
    IN_PROGRESS = "in_progress"    # Actively executing steps
    PAUSED = "paused"              # Temporarily halted
    COMPLETED = "completed"        # Reached terminal state successfully
    ABORTED = "aborted"            # Terminated early
    FAILED = "failed"              # Failed due to error or violation


class StepStatus(str, Enum):
    """Status of individual protocol step"""
    PENDING = "pending"            # Not yet reached
    ACTIVE = "active"              # Currently in this step
    COMPLETED = "completed"        # Successfully completed
    SKIPPED = "skipped"            # Bypassed (guard allowed skip)
    FAILED = "failed"              # Step failed
    TIMED_OUT = "timed_out"        # Exceeded max duration


class GuardType(str, Enum):
    """Types of transition guards (domain-agnostic)"""
    CHECKLIST_COMPLETE = "checklist_complete"    # A checklist run must be done
    JOURNAL_ENTRY_EXISTS = "journal_entry_exists"  # A journal entry required
    PARAMETER_VALUE = "parameter_value"          # A monitor reading in range
    ALERT_RESOLVED = "alert_resolved"            # No active alerts
    TIME_ELAPSED = "time_elapsed"                # Min time in current step
    USER_ROLE = "user_role"                      # Specific role required
    APPROVAL_REQUIRED = "approval_required"      # Explicit approval needed
    CUSTOM = "custom"                            # Domain-specific guard


class ActionType(str, Enum):
    """Types of transition actions (domain-agnostic)"""
    INITIATE_CHECKLIST = "initiate_checklist"    # Start a checklist run
    CREATE_JOURNAL_ENTRY = "create_journal_entry"  # Add journal note
    START_MONITOR = "start_monitor"              # Begin monitoring
    STOP_MONITOR = "stop_monitor"                # Stop monitoring
    SEND_NOTIFICATION = "send_notification"      # Notify users/teams
    SET_VARIABLE = "set_variable"                # Store data on the run
    LOG_TIMESTAMP = "log_timestamp"              # Record time milestone
    CUSTOM = "custom"                            # Domain-specific action


class EventType(str, Enum):
    """Audit event types for State Bus"""
    PROTOCOL_CREATED = "protocol.created"
    PROTOCOL_STARTED = "protocol.started"
    PROTOCOL_PAUSED = "protocol.paused"
    PROTOCOL_RESUMED = "protocol.resumed"
    STEP_ACTIVATED = "protocol.step_activated"
    STEP_COMPLETED = "protocol.step_completed"
    TRANSITION_EXECUTED = "protocol.transition_executed"
    GUARD_EVALUATED = "protocol.guard_evaluated"
    ACTION_EXECUTED = "protocol.action_executed"
    PROTOCOL_COMPLETED = "protocol.completed"
    PROTOCOL_ABORTED = "protocol.aborted"
    PROTOCOL_FAILED = "protocol.failed"


# ============================================================================
# VALUE OBJECTS - Step, Guard, Action configuration
# ============================================================================

class GuardDef(BaseModel):
    """
    Guard definition — condition that must be met to allow a transition.
    Stored as JSON in step transitions.

    Domain-agnostic: works for surgical pathways, insurance claims,
    logistics routes, educational milestones, etc.
    """
    guard_type: GuardType = PydanticField(..., description="Type of guard check")
    description: str = PydanticField(default="", description="Human-readable description")
    params: Dict[str, Any] = PydanticField(default_factory=dict, description="Guard parameters")
    required: bool = PydanticField(default=True, description="If false, guard is advisory only")

    model_config = ConfigDict(json_schema_extra={
        "examples": [
            {"guard_type": "checklist_complete", "description": "WHO Sign-In done", "params": {"checklist_key": "who_ssc_signin"}, "required": True},
            {"guard_type": "time_elapsed", "description": "Min 5 min in timeout", "params": {"min_seconds": 300}, "required": True},
        ]
    })


class ActionDef(BaseModel):
    """
    Action definition — side-effect executed when transition fires.
    Stored as JSON in step transitions.

    Domain-agnostic: actions trigger checklists, journals, monitors,
    notifications, or custom domain logic.
    """
    action_type: ActionType = PydanticField(..., description="Type of action")
    description: str = PydanticField(default="", description="Human-readable description")
    params: Dict[str, Any] = PydanticField(default_factory=dict, description="Action parameters")

    model_config = ConfigDict(json_schema_extra={
        "examples": [
            {"action_type": "initiate_checklist", "description": "Start WHO Sign-In", "params": {"checklist_key": "who_ssc_signin"}},
            {"action_type": "start_monitor", "description": "Begin intra-op vitals", "params": {"monitor_key": "intraop_vitals"}},
        ]
    })


class TransitionDef(BaseModel):
    """
    Transition definition — how to move from one step to the next.
    Each step can have multiple outgoing transitions (branching).
    """
    to_step: str = PydanticField(..., description="Target step key")
    label: str = PydanticField(default="", description="Display label e.g. 'Proceed to Surgery'")
    guards: List[GuardDef] = PydanticField(default_factory=list, description="Conditions to check")
    actions: List[ActionDef] = PydanticField(default_factory=list, description="Side-effects on transition")
    is_default: bool = PydanticField(default=False, description="Default transition if multiple options")

    model_config = ConfigDict(json_schema_extra={
        "examples": [
            {
                "to_step": "surgery",
                "label": "Begin Surgery",
                "guards": [{"guard_type": "checklist_complete", "params": {"checklist_key": "who_timeout"}}],
                "actions": [{"action_type": "start_monitor", "params": {"monitor_key": "intraop_vitals"}}],
            }
        ]
    })


class StepDef(BaseModel):
    """
    Step definition — a discrete phase in the protocol workflow.
    Each step has transitions that define how to move forward.

    Domain-agnostic: a step can be a surgical phase, an insurance review
    stage, a logistics checkpoint, an educational module, etc.
    """
    key: str = PydanticField(..., description="Unique step key e.g. 'pre_op'")
    label: str = PydanticField(..., description="Display label e.g. 'Pre-Operative'")
    description: str = PydanticField(default="", description="Detailed step description")
    order: int = PydanticField(default=0, description="Display order")
    is_initial: bool = PydanticField(default=False, description="Starting step")
    is_terminal: bool = PydanticField(default=False, description="Ending step (protocol complete)")
    max_duration_sec: Optional[int] = PydanticField(default=None, description="Max time in this step")
    transitions: List[TransitionDef] = PydanticField(default_factory=list, description="Outgoing transitions")
    instructions: str = PydanticField(default="", description="Instructions for this step")
    metadata: Dict[str, Any] = PydanticField(default_factory=dict, description="Step-specific config")

    model_config = ConfigDict(json_schema_extra={
        "examples": [
            {
                "key": "timeout",
                "label": "Time-Out",
                "description": "WHO Surgical Safety Checklist Time-Out phase",
                "order": 2,
                "is_initial": False,
                "is_terminal": False,
                "max_duration_sec": 600,
                "transitions": [{"to_step": "surgery", "label": "Begin Surgery"}],
            }
        ]
    })


# ============================================================================
# DATABASE MODELS
# ============================================================================

class ProtocolDefinition(SQLModel, table=True):
    """
    Protocol template defining a multi-step workflow.
    Stores the state machine as a JSON array of steps.

    Domain-agnostic: surgical pathways, insurance claims processing,
    logistics tracking, educational progressions, etc.
    """
    __tablename__ = "protocol_definitions"
    __table_args__ = {"schema": "protocol"}

    id: UUID = Field(default_factory=uuid4, primary_key=True)
    tenant_id: UUID = Field(index=True, description="Owner tenant (SYSTEM for built-in)")
    key: str = Field(max_length=100, index=True, description="Unique template key")
    title: str = Field(max_length=200, description="Display title")
    description: str = Field(default="", max_length=2000)
    version: str = Field(default="1.0.0", max_length=20)
    domain: str = Field(default="general", max_length=50, index=True, description="Domain pack")
    category: str = Field(default="workflow", max_length=50)
    is_active: bool = Field(default=True)
    is_system: bool = Field(default=False, description="Platform-provided template")

    # State machine definition
    steps: Optional[List[Dict[str, Any]]] = Field(
        default=None, sa_column=Column(JSON),
        description="Array of StepDef objects defining the workflow",
    )

    # Metadata
    created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
    updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
    created_by: Optional[str] = Field(default=None, max_length=100)

    def get_steps(self) -> List[StepDef]:
        """Parse steps JSON into StepDef objects"""
        if not self.steps:
            return []
        return [StepDef(**s) for s in self.steps]

    def get_step(self, key: str) -> Optional[StepDef]:
        """Get a specific step by key"""
        for step in self.get_steps():
            if step.key == key:
                return step
        return None

    def get_initial_step(self) -> Optional[StepDef]:
        """Get the starting step"""
        for step in self.get_steps():
            if step.is_initial:
                return step
        steps = self.get_steps()
        return steps[0] if steps else None

    def get_terminal_steps(self) -> List[StepDef]:
        """Get all terminal (ending) steps"""
        return [s for s in self.get_steps() if s.is_terminal]


class ProtocolRun(SQLModel, table=True):
    """
    Active execution of a protocol definition.
    Tracks current step, variables, and timing.
    """
    __tablename__ = "protocol_runs"
    __table_args__ = {"schema": "protocol"}

    id: UUID = Field(default_factory=uuid4, primary_key=True)
    tenant_id: UUID = Field(index=True)
    definition_id: UUID = Field(index=True)
    case_id: Optional[UUID] = Field(default=None, index=True, description="Case/subject this runs on")
    subject_label: str = Field(default="", max_length=200, description="Display label for case")

    # State tracking
    status: str = Field(default=ProtocolStatus.NOT_STARTED.value, max_length=20)
    current_step_key: str = Field(default="", max_length=100, description="Key of active step")
    current_step_label: str = Field(default="", max_length=200, description="Label of active step")
    completed_steps: int = Field(default=0, description="Number of completed steps")
    total_steps: int = Field(default=0, description="Total number of steps")

    # Variables (cross-step data sharing)
    variables: Optional[Dict[str, Any]] = Field(
        default=None, sa_column=Column(JSON),
        description="Run-scoped variables set by actions",
    )

    # Step history (denormalized for fast reads)
    step_history: Optional[List[Dict[str, Any]]] = Field(
        default=None, sa_column=Column(JSON),
        description="Ordered list of completed step records",
    )

    # Timestamps
    started_at: Optional[datetime] = Field(default=None)
    completed_at: Optional[datetime] = Field(default=None)
    created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
    updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
    started_by: str = Field(default="", max_length=100)


class ProtocolTransition(SQLModel, table=True):
    """
    Immutable record of a state transition within a protocol run.
    Captures from/to steps, guard results, action results, and timing.
    """
    __tablename__ = "protocol_transitions"
    __table_args__ = {"schema": "protocol"}

    id: UUID = Field(default_factory=uuid4, primary_key=True)
    run_id: UUID = Field(index=True)
    tenant_id: UUID = Field(index=True)

    # Transition data
    from_step: str = Field(max_length=100, description="Source step key")
    to_step: str = Field(max_length=100, description="Target step key")
    from_label: str = Field(default="", max_length=200)
    to_label: str = Field(default="", max_length=200)

    # Guard evaluation results
    guards_passed: bool = Field(default=True, description="All required guards passed?")
    guard_results: Optional[List[Dict[str, Any]]] = Field(
        default=None, sa_column=Column(JSON),
        description="Individual guard evaluation results",
    )

    # Action execution results
    action_results: Optional[List[Dict[str, Any]]] = Field(
        default=None, sa_column=Column(JSON),
        description="Individual action execution results",
    )

    # Metadata
    triggered_by: str = Field(default="", max_length=100, description="User who triggered")
    reason: str = Field(default="", max_length=500, description="Reason for transition")
    transitioned_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))


class ProtocolEvent(SQLModel, table=True):
    """
    Immutable audit event — hash-chained for tamper evidence.
    Same pattern as ChecklistEvent, JournalEvent, MonitorEvent.
    """
    __tablename__ = "protocol_events"
    __table_args__ = {"schema": "protocol"}

    id: UUID = Field(default_factory=uuid4, primary_key=True)
    tenant_id: UUID = Field(index=True)
    run_id: UUID = Field(index=True)
    event_type: str = Field(max_length=50)

    # Payload
    data: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))

    # Audit fields
    actor_id: str = Field(default="", max_length=100)
    occurred_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
    hash: str = Field(default="", max_length=64, description="SHA-256 of event data")
    prev_hash: str = Field(default="", max_length=64, description="Hash of previous event")


# ============================================================================
# API SCHEMAS (Pydantic V2)
# ============================================================================

class RunCreateRequest(BaseModel):
    """Start a new protocol run"""
    definition_id: UUID
    case_id: Optional[UUID] = None
    subject_label: str = ""

    model_config = ConfigDict(json_schema_extra={
        "examples": [{"definition_id": "abc-123", "case_id": "def-456", "subject_label": "Patient John, Total Knee"}]
    })


class TransitionRequest(BaseModel):
    """Request to transition to next step"""
    to_step: str = PydanticField(..., description="Target step key")
    reason: str = PydanticField(default="", description="Reason for transition")
    force: bool = PydanticField(default=False, description="Skip advisory guards")

    model_config = ConfigDict(json_schema_extra={
        "examples": [{"to_step": "surgery", "reason": "Checklist complete, patient confirmed"}]
    })


class ProtocolDefinitionResponse(BaseModel):
    """Protocol definition API response"""
    id: UUID
    tenant_id: UUID
    key: str
    title: str
    description: str
    version: str
    domain: str
    category: str
    is_active: bool
    is_system: bool
    steps: Optional[List[Dict[str, Any]]] = None
    step_count: int = 0
    created_at: datetime

    model_config = ConfigDict(from_attributes=True)


class RunResponse(BaseModel):
    """Protocol run summary response"""
    id: UUID
    tenant_id: UUID
    definition_id: UUID
    case_id: Optional[UUID] = None
    subject_label: str = ""
    status: str
    current_step_key: str
    current_step_label: str
    completed_steps: int
    total_steps: int
    started_at: Optional[datetime] = None
    completed_at: Optional[datetime] = None
    created_at: datetime

    model_config = ConfigDict(from_attributes=True)


class TransitionResponse(BaseModel):
    """Transition result response"""
    id: UUID
    run_id: UUID
    from_step: str
    to_step: str
    from_label: str
    to_label: str
    guards_passed: bool
    guard_results: Optional[List[Dict[str, Any]]] = None
    action_results: Optional[List[Dict[str, Any]]] = None
    triggered_by: str
    reason: str
    transitioned_at: datetime

    model_config = ConfigDict(from_attributes=True)


class GuardResultResponse(BaseModel):
    """Individual guard evaluation result"""
    guard_type: str
    description: str
    passed: bool
    message: str = ""
    required: bool = True

    model_config = ConfigDict(from_attributes=True)


class RunDetailResponse(BaseModel):
    """Detailed protocol run with step info and transitions"""
    run: RunResponse
    definition: ProtocolDefinitionResponse
    current_step: Optional[Dict[str, Any]] = None
    available_transitions: List[Dict[str, Any]] = []
    recent_transitions: List[TransitionResponse] = []
    variables: Dict[str, Any] = {}

    model_config = ConfigDict(from_attributes=True)