reasonkit-web 0.1.7

High-performance MCP server for browser automation, web capture, and content extraction. Rust-powered CDP client for AI agents.
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
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
//! Orchestrator API endpoints for the ReasonKit system
//!
//! This module provides comprehensive REST API endpoints for managing and monitoring
//! the entire ReasonKit ecosystem, including service management, task execution,
//! configuration, monitoring, and health checking for all integrated services.
//!
//! # Integrated Services
//!
//! - **listmonk** - Newsletter and mailing list management
//! - **postiz** - Social media scheduling and management
//! - **OpenWebUI** - Web-based UI for AI interactions
//! - **n8n** - Workflow automation platform
//! - **Metabase** - Business intelligence and analytics
//! - **Typesense** - Search engine and database

use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    response::{IntoResponse, Json, Response},
    routing::get,
    Router,
};
use chrono::{DateTime, Utc};
use metrics::counter;
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use std::time::Instant;
use std::{collections::HashMap, sync::Arc};
use tokio::sync::RwLock;
use tracing::{debug, error, info, instrument};
use uuid::Uuid;

use crate::handlers::AppState;

// ============================================================================
// Configuration Types
// ============================================================================

/// Configuration for all integrated services
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct ServiceConfig {
    /// Listmonk configuration
    #[serde(default)]
    pub listmonk: ServiceEndpointConfig,

    /// Postiz configuration
    #[serde(default)]
    pub postiz: ServiceEndpointConfig,

    /// OpenWebUI configuration
    #[serde(default)]
    pub openwebui: ServiceEndpointConfig,

    /// n8n configuration
    #[serde(default)]
    pub n8n: ServiceEndpointConfig,

    /// Metabase configuration
    #[serde(default)]
    pub metabase: ServiceEndpointConfig,

    /// Typesense configuration
    #[serde(default)]
    pub typesense: ServiceEndpointConfig,
}

/// Configuration for individual service endpoints
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct ServiceEndpointConfig {
    /// Service URL
    pub url: Option<String>,

    /// API key or token for authentication
    pub api_key: Option<String>,

    /// Whether the service is enabled
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// Timeout in seconds
    #[serde(default = "default_timeout")]
    pub timeout_secs: u64,
}

fn default_true() -> bool {
    true
}
fn default_timeout() -> u64 {
    30
}

// ============================================================================
// Task Management Types
// ============================================================================

/// Task execution request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskRequest {
    /// Task name/type
    pub task_type: String,

    /// Task parameters
    #[serde(default)]
    pub parameters: HashMap<String, JsonValue>,

    /// Priority level (1-10)
    #[serde(default = "default_priority")]
    pub priority: u8,

    /// Optional deadline
    pub deadline: Option<DateTime<Utc>>,
}

fn default_priority() -> u8 {
    5
}

/// Task execution response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskResponse {
    /// Task ID
    pub task_id: Uuid,

    /// Task status
    pub status: TaskStatus,

    /// Creation timestamp
    pub created_at: DateTime<Utc>,

    /// Last updated timestamp
    pub updated_at: DateTime<Utc>,

    /// Task result (if completed)
    pub result: Option<JsonValue>,

    /// Task error (if failed)
    pub error: Option<String>,
}

/// Task status enumeration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum TaskStatus {
    /// Task has been queued
    Queued,

    /// Task is currently running
    Running,

    /// Task completed successfully
    Completed,

    /// Task failed
    Failed,

    /// Task was cancelled
    Cancelled,
}

/// Task filtering parameters
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TaskFilter {
    /// Filter by status
    pub status: Option<TaskStatus>,

    /// Filter by task type
    pub task_type: Option<String>,

    /// Limit number of results
    pub limit: Option<u32>,

    /// Offset for pagination
    pub offset: Option<u32>,
}

// ============================================================================
// Service Management Types
// ============================================================================

/// Service health status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceHealth {
    /// Service name
    pub name: String,

    /// Current status
    pub status: ServiceStatus,

    /// Last checked timestamp
    pub last_checked: DateTime<Utc>,

    /// Response time in milliseconds
    pub response_time_ms: Option<u64>,

    /// Additional details
    pub details: Option<JsonValue>,
}

/// Service status enumeration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ServiceStatus {
    /// Service is healthy and operational
    Healthy,

    /// Service is degraded but partially functional
    Degraded,

    /// Service is unhealthy and not responding
    Unhealthy,

    /// Service is disabled
    Disabled,

    /// Service status is unknown
    Unknown,
}

/// Service control command
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ServiceCommand {
    /// Start the service
    Start,

    /// Stop the service
    Stop,

    /// Restart the service
    Restart,

    /// Enable the service
    Enable,

    /// Disable the service
    Disable,
}

// ============================================================================
// Monitoring and Metrics Types
// ============================================================================

/// System metrics snapshot
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemMetrics {
    /// CPU usage percentage
    pub cpu_usage_percent: f64,

    /// Memory usage in bytes
    pub memory_usage_bytes: u64,

    /// Disk usage percentage
    pub disk_usage_percent: f64,

    /// Network throughput in bytes/sec
    pub network_throughput_bytes_sec: u64,

    /// Timestamp of metrics collection
    pub timestamp: DateTime<Utc>,
}

/// Service metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceMetrics {
    /// Service name
    pub service_name: String,

    /// Request count
    pub request_count: u64,

    /// Error count
    pub error_count: u64,

    /// Average response time in milliseconds
    pub avg_response_time_ms: f64,

    /// Uptime in seconds
    pub uptime_seconds: u64,
}

// ============================================================================
// Error Types
// ============================================================================

/// Orchestrator API errors
#[derive(Debug, thiserror::Error)]
pub enum OrchestratorError {
    /// Invalid request parameters
    #[error("Invalid request: {0}")]
    InvalidRequest(String),

    /// Service not found
    #[error("Service not found: {0}")]
    ServiceNotFound(String),

    /// Service unavailable
    #[error("Service unavailable: {0}")]
    ServiceUnavailable(String),

    /// Task not found
    #[error("Task not found: {0}")]
    TaskNotFound(Uuid),

    /// Task execution failed
    #[error("Task execution failed: {0}")]
    TaskExecutionFailed(String),

    /// Configuration error
    #[error("Configuration error: {0}")]
    ConfigurationError(String),

    /// Authentication required
    #[error("Authentication required: {0}")]
    AuthenticationRequired(String),

    /// Permission denied
    #[error("Permission denied: {0}")]
    PermissionDenied(String),

    /// Internal server error
    #[error("Internal server error: {0}")]
    InternalError(String),
}

impl IntoResponse for OrchestratorError {
    fn into_response(self) -> Response {
        let (status, error_message) = match &self {
            OrchestratorError::InvalidRequest(_) => (StatusCode::BAD_REQUEST, self.to_string()),
            OrchestratorError::ServiceNotFound(_) => (StatusCode::NOT_FOUND, self.to_string()),
            OrchestratorError::ServiceUnavailable(_) => {
                (StatusCode::SERVICE_UNAVAILABLE, self.to_string())
            }
            OrchestratorError::TaskNotFound(_) => (StatusCode::NOT_FOUND, self.to_string()),
            OrchestratorError::TaskExecutionFailed(_) => {
                (StatusCode::BAD_REQUEST, self.to_string())
            }
            OrchestratorError::ConfigurationError(_) => (StatusCode::BAD_REQUEST, self.to_string()),
            OrchestratorError::AuthenticationRequired(_) => {
                (StatusCode::UNAUTHORIZED, self.to_string())
            }
            OrchestratorError::PermissionDenied(_) => (StatusCode::FORBIDDEN, self.to_string()),
            OrchestratorError::InternalError(_) => {
                (StatusCode::INTERNAL_SERVER_ERROR, self.to_string())
            }
        };

        // Increment error counter
        let error_type = std::any::type_name::<Self>();
        counter!("orchestrator_errors_total", "type" => error_type).increment(1);

        let body = serde_json::json!({
            "error": {
                "type": error_type,
                "message": error_message,
            }
        });

        (status, Json(body)).into_response()
    }
}

// ============================================================================
// Shared State
// ============================================================================

/// Shared state for orchestrator handlers
#[derive(Clone)]
pub struct OrchestratorState {
    /// Application state for metrics
    pub app_state: Arc<AppState>,

    /// Service configuration
    pub config: Arc<RwLock<ServiceConfig>>,

    /// Task storage
    pub tasks: Arc<RwLock<HashMap<Uuid, TaskResponse>>>,

    /// Service health cache
    pub service_health: Arc<RwLock<HashMap<String, ServiceHealth>>>,
}

impl OrchestratorState {
    /// Create new orchestrator state
    pub fn new(app_state: Arc<AppState>) -> Self {
        Self {
            app_state,
            config: Arc::new(RwLock::new(ServiceConfig::default())),
            tasks: Arc::new(RwLock::new(HashMap::new())),
            service_health: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Update service configuration
    pub async fn update_config(&self, new_config: ServiceConfig) {
        let mut config = self.config.write().await;
        *config = new_config;
    }

    /// Get current service configuration
    pub async fn get_config(&self) -> ServiceConfig {
        self.config.read().await.clone()
    }

    /// Add a new task
    pub async fn add_task(&self, task: TaskResponse) {
        let mut tasks = self.tasks.write().await;
        tasks.insert(task.task_id, task);
    }

    /// Get task by ID
    pub async fn get_task(&self, task_id: Uuid) -> Option<TaskResponse> {
        let tasks = self.tasks.read().await;
        tasks.get(&task_id).cloned()
    }

    /// Update service health status
    pub async fn update_service_health(&self, service_name: String, health: ServiceHealth) {
        let mut health_cache = self.service_health.write().await;
        health_cache.insert(service_name, health);
    }

    /// Get service health status
    pub async fn get_service_health(&self, service_name: &str) -> Option<ServiceHealth> {
        let health_cache = self.service_health.read().await;
        health_cache.get(service_name).cloned()
    }
}

// ============================================================================
// Request/Response Types
// ============================================================================

/// Generic API response wrapper
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiResponse<T> {
    /// Response data
    pub data: T,

    /// Response metadata
    pub meta: Option<ApiMeta>,
}

/// API response metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiMeta {
    /// Response timestamp
    pub timestamp: DateTime<Utc>,

    /// Response duration in milliseconds
    pub duration_ms: u64,
}

impl<T> ApiResponse<T> {
    /// Create a new API response
    pub fn new(data: T, start_time: Instant) -> Self {
        let duration_ms = start_time.elapsed().as_millis() as u64;
        Self {
            data,
            meta: Some(ApiMeta {
                timestamp: Utc::now(),
                duration_ms,
            }),
        }
    }
}

// ============================================================================
// Handler Implementations
// ============================================================================

/// Root endpoint - API information
#[instrument(skip_all)]
pub async fn root_handler(
    State(_state): State<Arc<OrchestratorState>>,
) -> Result<Json<ApiResponse<serde_json::Value>>, OrchestratorError> {
    let start_time = Instant::now();
    info!("API root endpoint accessed");

    let response = serde_json::json!({
        "name": "ReasonKit Orchestrator API",
        "version": env!("CARGO_PKG_VERSION"),
        "description": "Central orchestration API for ReasonKit services",
        "endpoints": [
            "GET /api/v1 - API information",
            "GET /api/v1/health - Overall system health",
            "GET /api/v1/services - List all services",
            "GET /api/v1/services/{name} - Get service details",
            "POST /api/v1/services/{name} - Control service",
            "GET /api/v1/services/{name}/health - Get service health",
            "GET /api/v1/tasks - List tasks",
            "POST /api/v1/tasks - Create new task",
            "GET /api/v1/tasks/{id} - Get task details",
            "DELETE /api/v1/tasks/{id} - Cancel task",
            "GET /api/v1/metrics - Get system metrics",
            "GET /api/v1/config - Get configuration",
            "PUT /api/v1/config - Update configuration"
        ]
    });

    Ok(Json(ApiResponse::new(response, start_time)))
}

/// Overall system health endpoint
#[instrument(skip_all)]
pub async fn health_handler(
    State(state): State<Arc<OrchestratorState>>,
) -> Result<Json<ApiResponse<serde_json::Value>>, OrchestratorError> {
    let start_time = Instant::now();
    info!("System health check requested");

    // Authenticate request
    // authenticate().await?;

    // Check overall system health
    let app_health = state.app_state.health();
    let services_health = check_all_services_health(state.clone()).await;

    let response = serde_json::json!({
        "status": "healthy",
        "timestamp": Utc::now().to_rfc3339(),
        "uptime_seconds": state.app_state.uptime_seconds(),
        "application": app_health,
        "services": services_health
    });

    Ok(Json(ApiResponse::new(response, start_time)))
}

/// List all services
#[instrument(skip_all)]
pub async fn list_services_handler(
    State(state): State<Arc<OrchestratorState>>,
) -> Result<Json<ApiResponse<Vec<String>>>, OrchestratorError> {
    let start_time = Instant::now();
    info!("Listing all services");

    let config = state.get_config().await;
    let mut services = Vec::new();

    if config.listmonk.enabled {
        services.push("listmonk".to_string());
    }
    if config.postiz.enabled {
        services.push("postiz".to_string());
    }
    if config.openwebui.enabled {
        services.push("openwebui".to_string());
    }
    if config.n8n.enabled {
        services.push("n8n".to_string());
    }
    if config.metabase.enabled {
        services.push("metabase".to_string());
    }
    if config.typesense.enabled {
        services.push("typesense".to_string());
    }

    Ok(Json(ApiResponse::new(services, start_time)))
}

/// Get service details
#[instrument(skip_all, fields(service_name = %service_name))]
pub async fn get_service_handler(
    Path(service_name): Path<String>,
    State(state): State<Arc<OrchestratorState>>,
) -> Result<Json<ApiResponse<serde_json::Value>>, OrchestratorError> {
    let start_time = Instant::now();
    info!("Getting service details for: {}", service_name);

    let config = state.get_config().await;

    let service_info = match service_name.as_str() {
        "listmonk" => serde_json::to_value(&config.listmonk).unwrap_or(serde_json::Value::Null),
        "postiz" => serde_json::to_value(&config.postiz).unwrap_or(serde_json::Value::Null),
        "openwebui" => serde_json::to_value(&config.openwebui).unwrap_or(serde_json::Value::Null),
        "n8n" => serde_json::to_value(&config.n8n).unwrap_or(serde_json::Value::Null),
        "metabase" => serde_json::to_value(&config.metabase).unwrap_or(serde_json::Value::Null),
        "typesense" => serde_json::to_value(&config.typesense).unwrap_or(serde_json::Value::Null),
        _ => return Err(OrchestratorError::ServiceNotFound(service_name)),
    };

    Ok(Json(ApiResponse::new(service_info, start_time)))
}

/// Control service (start, stop, restart, etc.)
#[instrument(skip_all, fields(service_name = %service_name))]
pub async fn control_service_handler(
    Path(service_name): Path<String>,
    State(_state): State<Arc<OrchestratorState>>,
    Json(command): Json<ServiceCommand>,
) -> Result<Json<ApiResponse<serde_json::Value>>, OrchestratorError> {
    let start_time = Instant::now();
    info!(
        "Controlling service: {} with command: {:?}",
        service_name, command
    );

    // In a real implementation, this would actually control the services
    // For now, we'll simulate the behavior

    let result = match command {
        ServiceCommand::Start => format!("Service {} started", service_name),
        ServiceCommand::Stop => format!("Service {} stopped", service_name),
        ServiceCommand::Restart => format!("Service {} restarted", service_name),
        ServiceCommand::Enable => format!("Service {} enabled", service_name),
        ServiceCommand::Disable => format!("Service {} disabled", service_name),
    };

    let response = serde_json::json!({
        "message": result,
        "status": "success",
        "timestamp": Utc::now().to_rfc3339()
    });

    Ok(Json(ApiResponse::new(response, start_time)))
}

/// Get service health
#[instrument(skip_all, fields(service_name = %service_name))]
pub async fn service_health_handler(
    Path(service_name): Path<String>,
    State(state): State<Arc<OrchestratorState>>,
) -> Result<Json<ApiResponse<ServiceHealth>>, OrchestratorError> {
    let start_time = Instant::now();
    info!("Checking health for service: {}", service_name);

    // Check if we have cached health info
    if let Some(health) = state.get_service_health(&service_name).await {
        return Ok(Json(ApiResponse::new(health, start_time)));
    }

    // In a real implementation, this would actually check service health
    // For now, we'll simulate a health check

    let health = ServiceHealth {
        name: service_name.clone(),
        status: ServiceStatus::Healthy,
        last_checked: Utc::now(),
        response_time_ms: Some(rand::random::<u64>() % 100),
        details: Some(serde_json::json!({"message": "Service is healthy"})),
    };

    // Cache the health info
    state
        .update_service_health(service_name, health.clone())
        .await;

    Ok(Json(ApiResponse::new(health, start_time)))
}

/// List tasks
#[instrument(skip_all)]
pub async fn list_tasks_handler(
    Query(filter): Query<TaskFilter>,
    State(state): State<Arc<OrchestratorState>>,
) -> Result<Json<ApiResponse<Vec<TaskResponse>>>, OrchestratorError> {
    let start_time = Instant::now();
    info!("Listing tasks with filter: {:?}", filter);

    let tasks = state.tasks.read().await;
    let mut task_list: Vec<TaskResponse> = tasks.values().cloned().collect();

    // Apply filters
    if let Some(status) = filter.status {
        task_list.retain(|task| task.status == status);
    }

    if let Some(task_type) = filter.task_type {
        // In a real implementation, we would filter by task type
        // For now, we'll just log the filter
        debug!("Filtering tasks by type: {}", task_type);
    }

    // Apply pagination
    if let Some(limit) = filter.limit {
        task_list.truncate(limit as usize);
    }

    Ok(Json(ApiResponse::new(task_list, start_time)))
}

/// Create new task
#[instrument(skip_all)]
pub async fn create_task_handler(
    State(state): State<Arc<OrchestratorState>>,
    Json(task_request): Json<TaskRequest>,
) -> Result<Json<ApiResponse<TaskResponse>>, OrchestratorError> {
    let start_time = Instant::now();
    info!("Creating new task: {}", task_request.task_type);

    // Create task response
    let task_id = Uuid::new_v4();
    let task_response = TaskResponse {
        task_id,
        status: TaskStatus::Queued,
        created_at: Utc::now(),
        updated_at: Utc::now(),
        result: None,
        error: None,
    };

    // Store task
    state.add_task(task_response.clone()).await;

    // In a real implementation, we would actually execute the task
    // For now, we'll just log it
    info!("Task {} queued for execution", task_id);

    Ok(Json(ApiResponse::new(task_response, start_time)))
}

/// Get task details
#[instrument(skip_all, fields(task_id = %task_id))]
pub async fn get_task_handler(
    Path(task_id): Path<Uuid>,
    State(state): State<Arc<OrchestratorState>>,
) -> Result<Json<ApiResponse<TaskResponse>>, OrchestratorError> {
    let start_time = Instant::now();
    info!("Getting task details for: {}", task_id);

    if let Some(task) = state.get_task(task_id).await {
        Ok(Json(ApiResponse::new(task, start_time)))
    } else {
        Err(OrchestratorError::TaskNotFound(task_id))
    }
}

/// Cancel task
#[instrument(skip_all, fields(task_id = %task_id))]
pub async fn cancel_task_handler(
    Path(task_id): Path<Uuid>,
    State(state): State<Arc<OrchestratorState>>,
) -> Result<Json<ApiResponse<serde_json::Value>>, OrchestratorError> {
    let start_time = Instant::now();
    info!("Cancelling task: {}", task_id);

    let mut tasks = state.tasks.write().await;
    if let Some(task) = tasks.get_mut(&task_id) {
        task.status = TaskStatus::Cancelled;
        task.updated_at = Utc::now();
        task.error = Some("Task cancelled by user".to_string());

        let response = serde_json::json!({
            "message": format!("Task {} cancelled", task_id),
            "status": "success",
            "timestamp": Utc::now().to_rfc3339()
        });

        Ok(Json(ApiResponse::new(response, start_time)))
    } else {
        Err(OrchestratorError::TaskNotFound(task_id))
    }
}

/// Get system metrics
#[instrument(skip_all)]
pub async fn metrics_handler(
    State(_state): State<Arc<OrchestratorState>>,
) -> Result<Json<ApiResponse<SystemMetrics>>, OrchestratorError> {
    let start_time = Instant::now();
    info!("Getting system metrics");

    // In a real implementation, this would collect actual system metrics
    // For now, we'll generate sample metrics

    let metrics = SystemMetrics {
        cpu_usage_percent: rand::random::<f64>() * 100.0,
        memory_usage_bytes: rand::random::<u64>() % 8000000000,
        disk_usage_percent: rand::random::<f64>() * 100.0,
        network_throughput_bytes_sec: rand::random::<u64>() % 1000000,
        timestamp: Utc::now(),
    };

    Ok(Json(ApiResponse::new(metrics, start_time)))
}

/// Get configuration
#[instrument(skip_all)]
pub async fn get_config_handler(
    State(state): State<Arc<OrchestratorState>>,
) -> Result<Json<ApiResponse<ServiceConfig>>, OrchestratorError> {
    let start_time = Instant::now();
    info!("Getting configuration");

    let config = state.get_config().await;
    Ok(Json(ApiResponse::new(config, start_time)))
}

/// Update configuration
#[instrument(skip_all)]
pub async fn update_config_handler(
    State(state): State<Arc<OrchestratorState>>,
    Json(new_config): Json<ServiceConfig>,
) -> Result<Json<ApiResponse<serde_json::Value>>, OrchestratorError> {
    let start_time = Instant::now();
    info!("Updating configuration");

    state.update_config(new_config).await;

    let response = serde_json::json!({
        "message": "Configuration updated successfully",
        "status": "success",
        "timestamp": Utc::now().to_rfc3339()
    });

    Ok(Json(ApiResponse::new(response, start_time)))
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Check health of all services
async fn check_all_services_health(state: Arc<OrchestratorState>) -> Vec<ServiceHealth> {
    let services = vec![
        "listmonk",
        "postiz",
        "openwebui",
        "n8n",
        "metabase",
        "typesense",
    ];
    let mut health_statuses = Vec::new();

    for service_name in services {
        // Try to get cached health first
        if let Some(health) = state.get_service_health(service_name).await {
            health_statuses.push(health);
        } else {
            // Create a new health status
            let health = ServiceHealth {
                name: service_name.to_string(),
                status: ServiceStatus::Healthy, // In reality, we'd actually check
                last_checked: Utc::now(),
                response_time_ms: Some(rand::random::<u64>() % 100),
                details: Some(serde_json::json!({"message": "Service health check performed"})),
            };

            // Cache it
            state
                .update_service_health(service_name.to_string(), health.clone())
                .await;
            health_statuses.push(health);
        }
    }

    health_statuses
}

// ============================================================================
// Router Configuration
// ============================================================================

/// Create the orchestrator router with all endpoints
pub fn orchestrator_router(state: Arc<OrchestratorState>) -> Router {
    Router::new()
        .route("/api/v1", get(root_handler))
        .route("/api/v1/health", get(health_handler))
        .route("/api/v1/services", get(list_services_handler))
        .route(
            "/api/v1/services/:service_name",
            get(get_service_handler).post(control_service_handler),
        )
        .route(
            "/api/v1/services/:service_name/health",
            get(service_health_handler),
        )
        .route(
            "/api/v1/tasks",
            get(list_tasks_handler).post(create_task_handler),
        )
        .route(
            "/api/v1/tasks/:task_id",
            get(get_task_handler).delete(cancel_task_handler),
        )
        .route("/api/v1/metrics", get(metrics_handler))
        .route(
            "/api/v1/config",
            get(get_config_handler).put(update_config_handler),
        )
        .with_state(state)
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio;

    #[test]
    fn test_service_config_default() {
        let config = ServiceConfig::default();
        // All services should be disabled by default for security
        assert!(!config.listmonk.enabled);
        assert!(!config.postiz.enabled);
        assert!(!config.openwebui.enabled);
        assert!(!config.n8n.enabled);
        assert!(!config.metabase.enabled);
        assert!(!config.typesense.enabled);
    }

    #[test]
    fn test_task_status_serialization() {
        let status = TaskStatus::Running;
        let json = serde_json::to_string(&status).unwrap();
        assert_eq!(json, "\"Running\"");
    }

    #[test]
    fn test_service_status_serialization() {
        let status = ServiceStatus::Healthy;
        let json = serde_json::to_string(&status).unwrap();
        assert_eq!(json, "\"Healthy\"");
    }

    #[tokio::test]
    async fn test_orchestrator_state() {
        let app_state = Arc::new(AppState::new());
        let orchestrator_state = OrchestratorState::new(app_state);

        // Test config operations
        let config = orchestrator_state.get_config().await;
        assert_eq!(config, ServiceConfig::default());

        // Test task operations
        let task_id = Uuid::new_v4();
        let task = TaskResponse {
            task_id,
            status: TaskStatus::Queued,
            created_at: Utc::now(),
            updated_at: Utc::now(),
            result: None,
            error: None,
        };

        orchestrator_state.add_task(task.clone()).await;
        let retrieved_task = orchestrator_state.get_task(task_id).await;
        assert!(retrieved_task.is_some());
        assert_eq!(retrieved_task.unwrap().task_id, task_id);
    }

    #[test]
    fn test_api_response_serialization() {
        let start_time = Instant::now();
        let data = serde_json::json!({"test": "value"});
        let response: ApiResponse<serde_json::Value> = ApiResponse::new(data, start_time);

        assert!(response.meta.is_some());
        assert_eq!(
            response.meta.as_ref().unwrap().duration_ms,
            start_time.elapsed().as_millis() as u64
        );
    }

    #[tokio::test]
    async fn test_service_health_caching() {
        let app_state = Arc::new(AppState::new());
        let orchestrator_state = OrchestratorState::new(app_state);

        let service_name = "test-service".to_string();
        let health = ServiceHealth {
            name: service_name.clone(),
            status: ServiceStatus::Healthy,
            last_checked: Utc::now(),
            response_time_ms: Some(50),
            details: Some(serde_json::json!({"test": "details"})),
        };

        orchestrator_state
            .update_service_health(service_name.clone(), health.clone())
            .await;
        let retrieved_health = orchestrator_state.get_service_health(&service_name).await;

        assert!(retrieved_health.is_some());
        assert_eq!(retrieved_health.unwrap().name, service_name);
    }
}