mockforge-http 0.3.116

HTTP/REST protocol support for MockForge
Documentation
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
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! Consistency engine API handlers
//!
//! This module provides HTTP handlers for managing unified state across protocols.

use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    response::Json,
};
// ChaosScenario is now serde_json::Value to avoid circular dependency
use mockforge_core::consistency::{
    enrich_order_response, enrich_user_response, get_user_orders_via_graph, ConsistencyEngine,
    EntityState, UnifiedState,
};
use mockforge_core::reality::RealityLevel;
use mockforge_data::{LifecyclePreset, LifecycleState, PersonaLifecycle, PersonaProfile};
use serde::Deserialize;
use serde_json::Value as JsonValue;
use serde_json::Value;
use std::sync::Arc;
use tracing::{error, info};

/// State for consistency handlers
#[derive(Clone)]
pub struct ConsistencyState {
    /// Consistency engine
    pub engine: Arc<ConsistencyEngine>,
}

/// Request to set active persona
#[derive(Debug, Deserialize)]
pub struct SetPersonaRequest {
    /// Persona profile
    pub persona: PersonaProfile,
}

/// Request to set active scenario
#[derive(Debug, Deserialize)]
pub struct SetScenarioRequest {
    /// Scenario ID
    pub scenario_id: String,
}

/// Request to set reality level
#[derive(Debug, Deserialize)]
pub struct SetRealityLevelRequest {
    /// Reality level (1-5)
    pub level: u8,
}

/// Request to set reality ratio
#[derive(Debug, Deserialize)]
pub struct SetRealityRatioRequest {
    /// Reality ratio (0.0-1.0)
    pub ratio: f64,
}

/// Request to register an entity
#[derive(Debug, Deserialize)]
pub struct RegisterEntityRequest {
    /// Entity type
    pub entity_type: String,
    /// Entity ID
    pub entity_id: String,
    /// Entity data (JSON)
    pub data: Value,
    /// Optional persona ID
    pub persona_id: Option<String>,
}

/// Request to activate chaos rule
#[derive(Debug, Deserialize)]
pub struct ActivateChaosRuleRequest {
    /// Chaos scenario
    pub rule: JsonValue, // ChaosScenario as JSON value
}

/// Request to deactivate chaos rule
#[derive(Debug, Deserialize)]
pub struct DeactivateChaosRuleRequest {
    /// Rule name
    pub rule_name: String,
}

/// Request to set persona lifecycle state
#[derive(Debug, Deserialize)]
pub struct SetPersonaLifecycleRequest {
    /// Persona ID
    pub persona_id: String,
    /// Initial lifecycle state
    pub initial_state: String,
}

/// Request to apply a lifecycle preset to a persona
#[derive(Debug, Deserialize)]
pub struct ApplyLifecyclePresetRequest {
    /// Persona ID
    pub persona_id: String,
    /// Lifecycle preset name (e.g., "subscription", "loan", "order_fulfillment", "user_engagement")
    pub preset: String,
}

/// Query parameters for workspace operations
#[derive(Debug, Deserialize)]
pub struct WorkspaceQuery {
    /// Workspace ID (defaults to "default" if not provided)
    #[serde(default = "default_workspace")]
    pub workspace: String,
}

fn default_workspace() -> String {
    "default".to_string()
}

/// Get unified state for a workspace
///
/// GET /api/v1/consistency/state?workspace={workspace_id}
pub async fn get_state(
    State(state): State<ConsistencyState>,
    Query(params): Query<WorkspaceQuery>,
) -> Result<Json<UnifiedState>, StatusCode> {
    let unified_state = state.engine.get_state(&params.workspace).await.ok_or_else(|| {
        error!("State not found for workspace: {}", params.workspace);
        StatusCode::NOT_FOUND
    })?;

    Ok(Json(unified_state))
}

/// Set active persona for a workspace
///
/// POST /api/v1/consistency/persona?workspace={workspace_id}
pub async fn set_persona(
    State(state): State<ConsistencyState>,
    Query(params): Query<WorkspaceQuery>,
    Json(request): Json<SetPersonaRequest>,
) -> Result<Json<Value>, StatusCode> {
    // Clone persona_id before moving request.persona
    let persona_id = request.persona.id.clone();

    state
        .engine
        .set_active_persona(&params.workspace, request.persona)
        .await
        .map_err(|e| {
            error!("Failed to set persona: {}", e);
            StatusCode::INTERNAL_SERVER_ERROR
        })?;

    // Record pillar usage for persona activation
    mockforge_core::pillar_tracking::record_reality_usage(
        Some(params.workspace.clone()),
        None,
        "smart_personas_usage",
        serde_json::json!({
            "persona_id": persona_id,
            "action": "activated"
        }),
    )
    .await;

    info!("Set persona for workspace: {}", params.workspace);
    Ok(Json(serde_json::json!({
        "success": true,
        "workspace": params.workspace,
    })))
}

/// Set active scenario for a workspace
///
/// POST /api/v1/consistency/scenario?workspace={workspace_id}
pub async fn set_scenario(
    State(state): State<ConsistencyState>,
    Query(params): Query<WorkspaceQuery>,
    Json(request): Json<SetScenarioRequest>,
) -> Result<Json<Value>, StatusCode> {
    state
        .engine
        .set_active_scenario(&params.workspace, request.scenario_id)
        .await
        .map_err(|e| {
            error!("Failed to set scenario: {}", e);
            StatusCode::INTERNAL_SERVER_ERROR
        })?;

    info!("Set scenario for workspace: {}", params.workspace);
    Ok(Json(serde_json::json!({
        "success": true,
        "workspace": params.workspace,
    })))
}

/// Set reality level for a workspace
///
/// POST /api/v1/consistency/reality-level?workspace={workspace_id}
pub async fn set_reality_level(
    State(state): State<ConsistencyState>,
    Query(params): Query<WorkspaceQuery>,
    Json(request): Json<SetRealityLevelRequest>,
) -> Result<Json<Value>, StatusCode> {
    let level = RealityLevel::from_value(request.level).ok_or_else(|| {
        error!("Invalid reality level: {}", request.level);
        StatusCode::BAD_REQUEST
    })?;

    state.engine.set_reality_level(&params.workspace, level).await.map_err(|e| {
        error!("Failed to set reality level: {}", e);
        StatusCode::INTERNAL_SERVER_ERROR
    })?;

    info!("Set reality level for workspace: {}", params.workspace);
    Ok(Json(serde_json::json!({
        "success": true,
        "workspace": params.workspace,
        "level": request.level,
    })))
}

/// Set reality continuum ratio for a workspace
///
/// POST /api/v1/consistency/reality-ratio?workspace={workspace_id}
pub async fn set_reality_ratio(
    State(state): State<ConsistencyState>,
    Query(params): Query<WorkspaceQuery>,
    Json(request): Json<SetRealityRatioRequest>,
) -> Result<Json<Value>, StatusCode> {
    if !(0.0..=1.0).contains(&request.ratio) {
        return Err(StatusCode::BAD_REQUEST);
    }

    state
        .engine
        .set_reality_ratio(&params.workspace, request.ratio)
        .await
        .map_err(|e| {
            error!("Failed to set reality ratio: {}", e);
            StatusCode::INTERNAL_SERVER_ERROR
        })?;

    info!("Set reality ratio for workspace: {}", params.workspace);
    Ok(Json(serde_json::json!({
        "success": true,
        "workspace": params.workspace,
        "ratio": request.ratio,
    })))
}

/// Register or update an entity
///
/// POST /api/v1/consistency/entities?workspace={workspace_id}
pub async fn register_entity(
    State(state): State<ConsistencyState>,
    Query(params): Query<WorkspaceQuery>,
    Json(request): Json<RegisterEntityRequest>,
) -> Result<Json<Value>, StatusCode> {
    let mut entity = EntityState::new(request.entity_type, request.entity_id, request.data);
    if let Some(persona_id) = request.persona_id {
        entity.persona_id = Some(persona_id);
    }

    state
        .engine
        .register_entity(&params.workspace, entity.clone())
        .await
        .map_err(|e| {
            error!("Failed to register entity: {}", e);
            StatusCode::INTERNAL_SERVER_ERROR
        })?;

    info!(
        "Registered entity {}:{} for workspace: {}",
        entity.entity_type, entity.entity_id, params.workspace
    );
    Ok(Json(serde_json::json!({
        "success": true,
        "workspace": params.workspace,
        "entity": entity,
    })))
}

/// Get entity by type and ID
///
/// GET /api/v1/consistency/entities/{entity_type}/{entity_id}?workspace={workspace_id}
pub async fn get_entity(
    State(state): State<ConsistencyState>,
    Path((entity_type, entity_id)): Path<(String, String)>,
    Query(params): Query<WorkspaceQuery>,
) -> Result<Json<EntityState>, StatusCode> {
    let entity = state
        .engine
        .get_entity(&params.workspace, &entity_type, &entity_id)
        .await
        .ok_or_else(|| {
            error!(
                "Entity not found: {}:{} in workspace: {}",
                entity_type, entity_id, params.workspace
            );
            StatusCode::NOT_FOUND
        })?;

    Ok(Json(entity))
}

/// List all entities for a workspace
///
/// GET /api/v1/consistency/entities?workspace={workspace_id}
pub async fn list_entities(
    State(state): State<ConsistencyState>,
    Query(params): Query<WorkspaceQuery>,
) -> Result<Json<Value>, StatusCode> {
    let unified_state = state.engine.get_state(&params.workspace).await.ok_or_else(|| {
        error!("State not found for workspace: {}", params.workspace);
        StatusCode::NOT_FOUND
    })?;

    let entities: Vec<&EntityState> = unified_state.entity_state.values().collect();
    Ok(Json(serde_json::json!({
        "workspace": params.workspace,
        "entities": entities,
        "count": entities.len(),
    })))
}

/// Activate a chaos rule
///
/// POST /api/v1/consistency/chaos/activate?workspace={workspace_id}
pub async fn activate_chaos_rule(
    State(state): State<ConsistencyState>,
    Query(params): Query<WorkspaceQuery>,
    Json(request): Json<ActivateChaosRuleRequest>,
) -> Result<Json<Value>, StatusCode> {
    state
        .engine
        .activate_chaos_rule(&params.workspace, request.rule)
        .await
        .map_err(|e| {
            error!("Failed to activate chaos rule: {}", e);
            StatusCode::INTERNAL_SERVER_ERROR
        })?;

    info!("Activated chaos rule for workspace: {}", params.workspace);
    Ok(Json(serde_json::json!({
        "success": true,
        "workspace": params.workspace,
    })))
}

/// Deactivate a chaos rule
///
/// POST /api/v1/consistency/chaos/deactivate?workspace={workspace_id}
pub async fn deactivate_chaos_rule(
    State(state): State<ConsistencyState>,
    Query(params): Query<WorkspaceQuery>,
    Json(request): Json<DeactivateChaosRuleRequest>,
) -> Result<Json<Value>, StatusCode> {
    state
        .engine
        .deactivate_chaos_rule(&params.workspace, &request.rule_name)
        .await
        .map_err(|e| {
            error!("Failed to deactivate chaos rule: {}", e);
            StatusCode::INTERNAL_SERVER_ERROR
        })?;

    info!("Deactivated chaos rule for workspace: {}", params.workspace);
    Ok(Json(serde_json::json!({
        "success": true,
        "workspace": params.workspace,
        "rule_name": request.rule_name,
    })))
}

/// Set persona lifecycle state
///
/// POST /api/v1/consistency/persona/lifecycle?workspace={workspace_id}
pub async fn set_persona_lifecycle(
    State(state): State<ConsistencyState>,
    Query(params): Query<WorkspaceQuery>,
    Json(request): Json<SetPersonaLifecycleRequest>,
) -> Result<Json<Value>, StatusCode> {
    // Parse lifecycle state
    let lifecycle_state = match request.initial_state.to_lowercase().as_str() {
        "new" | "new_signup" => LifecycleState::NewSignup,
        "active" => LifecycleState::Active,
        "power_user" | "poweruser" => LifecycleState::PowerUser,
        "churn_risk" | "churnrisk" => LifecycleState::ChurnRisk,
        "churned" => LifecycleState::Churned,
        "upgrade_pending" | "upgradepending" => LifecycleState::UpgradePending,
        "payment_failed" | "paymentfailed" => LifecycleState::PaymentFailed,
        _ => {
            error!("Invalid lifecycle state: {}", request.initial_state);
            return Err(StatusCode::BAD_REQUEST);
        }
    };

    // Get unified state to access active persona
    let unified_state = state.engine.get_state(&params.workspace).await.ok_or_else(|| {
        error!("State not found for workspace: {}", params.workspace);
        StatusCode::NOT_FOUND
    })?;

    // Update persona lifecycle if active persona matches
    if let Some(ref persona) = unified_state.active_persona {
        if persona.id == request.persona_id {
            let mut persona_mut = persona.clone();
            let lifecycle = PersonaLifecycle::new(request.persona_id.clone(), lifecycle_state);
            persona_mut.set_lifecycle(lifecycle);

            // Apply lifecycle effects to persona traits
            if let Some(ref lifecycle) = persona_mut.lifecycle {
                let effects = lifecycle.apply_lifecycle_effects();
                for (key, value) in effects {
                    persona_mut.set_trait(key, value);
                }
            }

            // Update the persona in the engine
            state
                .engine
                .set_active_persona(&params.workspace, persona_mut)
                .await
                .map_err(|e| {
                    error!("Failed to set persona lifecycle: {}", e);
                    StatusCode::INTERNAL_SERVER_ERROR
                })?;

            info!(
                "Set lifecycle state {} for persona {} in workspace: {}",
                request.initial_state, request.persona_id, params.workspace
            );

            return Ok(Json(serde_json::json!({
                "success": true,
                "workspace": params.workspace,
                "persona_id": request.persona_id,
                "lifecycle_state": request.initial_state,
            })));
        }
    }

    error!(
        "Persona {} not found or not active in workspace: {}",
        request.persona_id, params.workspace
    );
    Err(StatusCode::NOT_FOUND)
}

/// Get user by ID with persona graph enrichment
///
/// GET /api/v1/consistency/users/{id}?workspace={workspace_id}
/// This endpoint uses the persona graph to enrich the user response with related entities.
pub async fn get_user_with_graph(
    State(state): State<ConsistencyState>,
    Path(user_id): Path<String>,
    Query(params): Query<WorkspaceQuery>,
) -> Result<Json<Value>, StatusCode> {
    // Get user entity
    let user_entity = state
        .engine
        .get_entity(&params.workspace, "user", &user_id)
        .await
        .ok_or_else(|| {
            error!("User not found: {} in workspace: {}", user_id, params.workspace);
            StatusCode::NOT_FOUND
        })?;

    // Enrich response with persona graph data
    let mut response = user_entity.data.clone();
    enrich_user_response(&state.engine, &params.workspace, &user_id, &mut response).await;

    Ok(Json(response))
}

/// Get orders for a user using persona graph
///
/// GET /api/v1/consistency/users/{id}/orders?workspace={workspace_id}
/// This endpoint uses the persona graph to find all orders related to the user.
pub async fn get_user_orders_with_graph(
    State(state): State<ConsistencyState>,
    Path(user_id): Path<String>,
    Query(params): Query<WorkspaceQuery>,
) -> Result<Json<Value>, StatusCode> {
    // Verify user exists
    state
        .engine
        .get_entity(&params.workspace, "user", &user_id)
        .await
        .ok_or_else(|| {
            error!("User not found: {} in workspace: {}", user_id, params.workspace);
            StatusCode::NOT_FOUND
        })?;

    // Get orders via persona graph
    let orders = get_user_orders_via_graph(&state.engine, &params.workspace, &user_id).await;

    // Convert to JSON response
    let orders_json: Vec<Value> = orders.iter().map(|e| e.data.clone()).collect();

    Ok(Json(serde_json::json!({
        "user_id": user_id,
        "orders": orders_json,
        "count": orders_json.len(),
    })))
}

/// Get order by ID with persona graph enrichment
///
/// GET /api/v1/consistency/orders/{id}?workspace={workspace_id}
/// This endpoint uses the persona graph to enrich the order response with related entities.
pub async fn get_order_with_graph(
    State(state): State<ConsistencyState>,
    Path(order_id): Path<String>,
    Query(params): Query<WorkspaceQuery>,
) -> Result<Json<Value>, StatusCode> {
    // Get order entity
    let order_entity = state
        .engine
        .get_entity(&params.workspace, "order", &order_id)
        .await
        .ok_or_else(|| {
            error!("Order not found: {} in workspace: {}", order_id, params.workspace);
            StatusCode::NOT_FOUND
        })?;

    // Enrich response with persona graph data
    let mut response = order_entity.data.clone();
    enrich_order_response(&state.engine, &params.workspace, &order_id, &mut response).await;

    Ok(Json(response))
}

/// Update persona lifecycle states based on current virtual time
///
/// POST /api/v1/consistency/persona/update-lifecycles?workspace={workspace_id}
/// This endpoint checks all active personas and updates their lifecycle states
/// based on elapsed time since state entry, using virtual time if time travel is enabled.
pub async fn update_persona_lifecycles(
    State(state): State<ConsistencyState>,
    Query(params): Query<WorkspaceQuery>,
) -> Result<Json<Value>, StatusCode> {
    use mockforge_core::time_travel::now as get_virtual_time;

    // Get unified state
    let mut unified_state = state.engine.get_state(&params.workspace).await.ok_or_else(|| {
        error!("State not found for workspace: {}", params.workspace);
        StatusCode::NOT_FOUND
    })?;

    // Get current time (virtual if time travel is enabled, real otherwise)
    let current_time = get_virtual_time();

    // Update lifecycle state for active persona if present
    let mut updated = false;
    if let Some(ref mut persona) = unified_state.active_persona {
        let old_state = persona
            .lifecycle
            .as_ref()
            .map(|l| l.current_state)
            .unwrap_or(LifecycleState::Active);

        // Update lifecycle state based on elapsed time
        persona.update_lifecycle_state(current_time);

        let new_state = persona
            .lifecycle
            .as_ref()
            .map(|l| l.current_state)
            .unwrap_or(LifecycleState::Active);

        if old_state != new_state {
            updated = true;
            info!(
                "Persona {} lifecycle state updated: {:?} -> {:?}",
                persona.id, old_state, new_state
            );

            // Update the persona in the engine
            state
                .engine
                .set_active_persona(&params.workspace, persona.clone())
                .await
                .map_err(|e| {
                    error!("Failed to update persona lifecycle: {}", e);
                    StatusCode::INTERNAL_SERVER_ERROR
                })?;
        }
    }

    Ok(Json(serde_json::json!({
        "success": true,
        "workspace": params.workspace,
        "updated": updated,
        "current_time": current_time.to_rfc3339(),
    })))
}

/// List all available lifecycle presets
///
/// GET /api/v1/consistency/lifecycle-presets
pub async fn list_lifecycle_presets() -> Json<Value> {
    let presets: Vec<Value> = LifecyclePreset::all()
        .iter()
        .map(|preset| {
            serde_json::json!({
                "name": preset.name(),
                "id": format!("{:?}", preset).to_lowercase(),
                "description": preset.description(),
            })
        })
        .collect();

    Json(serde_json::json!({
        "presets": presets,
    }))
}

/// Get details of a specific lifecycle preset
///
/// GET /api/v1/consistency/lifecycle-presets/{preset_name}
pub async fn get_lifecycle_preset_details(
    Path(preset_name): Path<String>,
) -> Result<Json<Value>, StatusCode> {
    // Parse preset name
    let preset = match preset_name.to_lowercase().as_str() {
        "subscription" => LifecyclePreset::Subscription,
        "loan" => LifecyclePreset::Loan,
        "order_fulfillment" | "orderfulfillment" => LifecyclePreset::OrderFulfillment,
        "user_engagement" | "userengagement" => LifecyclePreset::UserEngagement,
        _ => {
            error!("Unknown lifecycle preset: {}", preset_name);
            return Err(StatusCode::NOT_FOUND);
        }
    };

    // Create a sample lifecycle to get the structure
    let sample_lifecycle = PersonaLifecycle::from_preset(preset, "sample".to_string());

    // Build response with preset details
    let response = serde_json::json!({
        "preset": {
            "name": preset.name(),
            "id": format!("{:?}", preset).to_lowercase(),
            "description": preset.description(),
        },
        "initial_state": format!("{:?}", sample_lifecycle.current_state),
        "states": sample_lifecycle
            .transition_rules
            .iter()
            .map(|rule| {
                serde_json::json!({
                    "from": format!("{:?}", sample_lifecycle.current_state),
                    "to": format!("{:?}", rule.to),
                    "after_days": rule.after_days,
                    "condition": rule.condition,
                })
            })
            .collect::<Vec<_>>(),
        "affected_endpoints": match preset {
            LifecyclePreset::Subscription => vec!["billing", "support", "subscription"],
            LifecyclePreset::Loan => vec!["loan", "loans", "credit", "application"],
            LifecyclePreset::OrderFulfillment => vec!["order", "orders", "fulfillment", "shipment", "delivery"],
            LifecyclePreset::UserEngagement => vec!["profile", "user", "users", "activity", "engagement", "notifications"],
        },
    });

    Ok(Json(response))
}

/// Apply a lifecycle preset to a persona
///
/// POST /api/v1/consistency/lifecycle-presets/apply?workspace={workspace_id}
pub async fn apply_lifecycle_preset(
    State(state): State<ConsistencyState>,
    Query(params): Query<WorkspaceQuery>,
    Json(request): Json<ApplyLifecyclePresetRequest>,
) -> Result<Json<Value>, StatusCode> {
    // Parse preset name
    let preset = match request.preset.to_lowercase().as_str() {
        "subscription" => LifecyclePreset::Subscription,
        "loan" => LifecyclePreset::Loan,
        "order_fulfillment" | "orderfulfillment" => LifecyclePreset::OrderFulfillment,
        "user_engagement" | "userengagement" => LifecyclePreset::UserEngagement,
        _ => {
            error!("Unknown lifecycle preset: {}", request.preset);
            return Err(StatusCode::BAD_REQUEST);
        }
    };

    // Get unified state
    let mut unified_state = state.engine.get_state(&params.workspace).await.ok_or_else(|| {
        error!("State not found for workspace: {}", params.workspace);
        StatusCode::NOT_FOUND
    })?;

    // Check if persona exists and is active
    if let Some(ref mut persona) = unified_state.active_persona {
        if persona.id != request.persona_id {
            error!(
                "Persona {} not found or not active in workspace: {}",
                request.persona_id, params.workspace
            );
            return Err(StatusCode::NOT_FOUND);
        }

        // Create lifecycle from preset
        let lifecycle = PersonaLifecycle::from_preset(preset, request.persona_id.clone());

        // Apply lifecycle to persona
        persona.set_lifecycle(lifecycle.clone());

        // Apply lifecycle effects to persona traits
        let effects = lifecycle.apply_lifecycle_effects();
        for (key, value) in effects {
            persona.set_trait(key, value);
        }

        // Update the persona in the engine
        state
            .engine
            .set_active_persona(&params.workspace, persona.clone())
            .await
            .map_err(|e| {
                error!("Failed to apply lifecycle preset: {}", e);
                StatusCode::INTERNAL_SERVER_ERROR
            })?;

        info!(
            "Applied lifecycle preset {:?} to persona {} in workspace: {}",
            preset, request.persona_id, params.workspace
        );

        return Ok(Json(serde_json::json!({
            "success": true,
            "workspace": params.workspace,
            "persona_id": request.persona_id,
            "preset": preset.name(),
            "lifecycle_state": format!("{:?}", lifecycle.current_state),
        })));
    }

    error!("No active persona found in workspace: {}", params.workspace);
    Err(StatusCode::NOT_FOUND)
}

/// Create consistency router
pub fn consistency_router(state: ConsistencyState) -> axum::Router {
    use axum::routing::{get, post};

    axum::Router::new()
        // State management
        .route("/api/v1/consistency/state", get(get_state))
        // Persona management
        .route("/api/v1/consistency/persona", post(set_persona))
        .route("/api/v1/consistency/persona/lifecycle", post(set_persona_lifecycle))
        .route("/api/v1/consistency/persona/update-lifecycles", post(update_persona_lifecycles))
        // Lifecycle preset management
        .route("/api/v1/consistency/lifecycle-presets", get(list_lifecycle_presets))
        .route("/api/v1/consistency/lifecycle-presets/{preset_name}", get(get_lifecycle_preset_details))
        .route("/api/v1/consistency/lifecycle-presets/apply", post(apply_lifecycle_preset))
        // Scenario management
        .route("/api/v1/consistency/scenario", post(set_scenario))
        // Reality level management
        .route("/api/v1/consistency/reality-level", post(set_reality_level))
        // Reality ratio management
        .route("/api/v1/consistency/reality-ratio", post(set_reality_ratio))
        // Entity management
        .route("/api/v1/consistency/entities", get(list_entities).post(register_entity))
        .route(
            "/api/v1/consistency/entities/{entity_type}/{entity_id}",
            get(get_entity),
        )
        // Persona graph-enabled endpoints
        .route("/api/v1/consistency/users/{id}", get(get_user_with_graph))
        .route("/api/v1/consistency/users/{id}/orders", get(get_user_orders_with_graph))
        .route("/api/v1/consistency/orders/{id}", get(get_order_with_graph))
        // Chaos rule management
        .route("/api/v1/consistency/chaos/activate", post(activate_chaos_rule))
        .route("/api/v1/consistency/chaos/deactivate", post(deactivate_chaos_rule))
        .with_state(state)
}