opencrates 3.0.1

Enterprise-grade AI-powered Rust development companion with comprehensive automation, monitoring, and deployment capabilities
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
//! `OpenCrates` server module

use anyhow::Result;
use axum::{
    extract::{DefaultBodyLimit, Path, Query, State},
    http::{HeaderMap, Method, StatusCode},
    middleware::{self, Next},
    response::{Html, IntoResponse, Json, Response},
    routing::{delete, get, post, put},
    Router,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::net::TcpListener;
use tower::ServiceBuilder;
use tower_http::{
    compression::CompressionLayer,
    cors::{Any, CorsLayer},
    limit::RequestBodyLimitLayer,
    request_id::{MakeRequestId, PropagateRequestIdLayer, RequestId},
    sensitive_headers::SetSensitiveRequestHeadersLayer,
    timeout::TimeoutLayer,
    trace::TraceLayer,
};
use tracing::{error, info};
use utoipa::{OpenApi, ToSchema};
use utoipa_redoc::{Redoc, Servable};
use utoipa_swagger_ui::SwaggerUi;
use uuid::Uuid;

use crate::core::AnalysisResult;
use crate::core::{AppState, OpenCrates};
use crate::providers::{CodexProvider, GenerationResponse, LLMProvider};
use crate::utils::{
    cache::CacheManager,
    config::{CodexConfig, OpenCratesConfig},
    health::HealthManager,
    metrics::MetricRegistry,
    templates::{CrateSpec, CrateType},
};

/// Request payload for code generation
#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)]
pub struct CodeGenerationRequest {
    /// The instruction or prompt for code generation
    pub instruction: String,
    /// Optional context to provide for the generation
    pub context: Option<String>,
    /// Programming language for the generated code
    pub language: Option<String>,
    /// Whether to include tests in the generated code
    pub include_tests: Option<bool>,
}

/// Response for code generation
#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)]
pub struct CodeGenerationResponse {
    /// The generated code
    pub code: String,
    /// Additional metadata about the generation
    pub metadata: GenerationMetadata,
}

/// Metadata about the code generation
#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)]
pub struct GenerationMetadata {
    /// Model used for generation
    pub model: String,
    /// Number of tokens used
    pub tokens_used: usize,
    /// Generation timestamp
    pub timestamp: String,
}

/// Request for applying a patch to a file
#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)]
pub struct PatchApplicationRequest {
    /// The file path to apply the patch to
    pub file_path: String,
    /// The patch content
    pub patch_content: String,
}

/// Response for patch application
#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)]
pub struct PatchApplicationResponse {
    /// Whether the patch was successfully applied
    pub success: bool,
    /// Any error message if the patch failed
    pub message: String,
    /// The file path that was modified
    pub file_path: String,
}

/// Request for generating a Rust crate
#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)]
pub struct GenerateRequest {
    /// Name of the crate to generate
    pub name: String,
    /// Description of the crate
    pub description: String,
    /// Features to include
    pub features: Vec<String>,
    /// Optional context for generation
    pub context: Option<String>,
    /// AI provider to use
    pub provider: Option<String>,
}

/// Response for crate generation
#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)]
pub struct GenerateResponse {
    /// Request ID
    pub request_id: String,
    /// Generated crate specification
    pub crate_spec: CrateSpec,
    /// Generation metrics
    pub metrics: GenerationMetrics,
    /// Success message
    pub message: String,
}

/// Generation metrics
#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)]
pub struct GenerationMetrics {
    /// Time taken for generation in milliseconds
    pub generation_time_ms: u64,
    /// Number of tokens used
    pub tokens_used: Option<u64>,
    /// Estimated cost
    pub cost_estimate: Option<f64>,
    /// Provider used
    pub provider: String,
}

/// Request for analyzing a project
#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)]
pub struct AnalyzeRequest {
    /// Path to the project to analyze
    pub path: std::path::PathBuf,
}

/// Health status response
#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)]
pub struct HealthStatus {
    /// Health status
    pub status: String,
    /// Timestamp
    pub timestamp: String,
    /// Version
    pub version: String,
}

/// API error response
#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)]
pub struct ApiError {
    /// Error message
    pub message: String,
    /// Error code
    pub code: String,
}

#[derive(OpenApi)]
#[openapi(
    paths(
        health_handler,
        ready_handler,
        metrics_handler,
        generate_handler,
        codex_generate_handler,
        codex_apply_patch_handler,
        codex_health_handler,
        codex_models_handler,
        generate_crate,
        analyze_project,
        health_check,
        system_status,
        metrics_endpoint,
        list_templates,
        list_providers,
    ),
    components(
        schemas(CodeGenerationRequest, CodeGenerationResponse, GenerationMetadata, PatchApplicationRequest, PatchApplicationResponse)
    ),
    tags(
        (name = "OpenCrates", description = "OpenCrates API"),
        (name = "generation", description = "Crate generation endpoints"),
        (name = "analysis", description = "Project analysis endpoints"),
        (name = "system", description = "System monitoring endpoints"),
        (name = "templates", description = "Template management endpoints"),
        (name = "providers", description = "AI provider endpoints"),
    ),
    info(
        title = "OpenCrates API",
        version = "3.0.0",
        description = "Enterprise-grade AI-powered Rust development companion",
        contact(
            name = "OpenCrates Team",
            email = "support@opencrates.dev",
        ),
        license(
            name = "MIT OR Apache-2.0",
            url = "https://opensource.org/licenses/MIT",
        ),
    ),
    servers(
        (url = "http://localhost:8080", description = "Local development server"),
        (url = "https://api.opencrates.dev", description = "Production server"),
    ),
)]
struct ApiDoc;

/// Creates and configures the main application, including the router and documentation endpoints.
pub async fn create_app(config: OpenCratesConfig) -> Result<Router> {
    info!("Creating OpenCrates server application");
    let core = Arc::new(OpenCrates::new_with_config(config.clone()).await?);
    let metrics = Arc::new(MetricRegistry::new());
    let health_manager = Arc::new(HealthManager::new().await?);
    let cache_manager = Arc::new(CacheManager::new());

    let app_state = AppState {
        core,
        metrics,
        health: health_manager,
        cache: cache_manager,
        start_time: std::time::Instant::now(),
    };

    let router = Router::new()
        .route("/health", get(health_handler))
        .route("/ready", get(ready_handler))
        .route("/metrics", get(metrics_handler))
        .route("/api/v1/generate", post(generate_handler))
        .route("/api/v1/codex/generate", post(codex_generate_handler))
        .route("/api/v1/codex/apply-patch", post(codex_apply_patch_handler))
        .route("/api/v1/codex/health", get(codex_health_handler))
        .route("/api/v1/codex/models", get(codex_models_handler))
        .route("/generate", post(generate_crate))
        .route("/analyze", post(analyze_project))
        .route("/templates", get(list_templates))
        .route("/providers", get(list_providers))
        .route("/providers/:provider/models", get(list_provider_models))
        .route("/system/health", get(health_check))
        .route("/system/status", get(system_status))
        .route("/system/metrics", get(metrics_endpoint))
        .route("/version", get(version_info))
        .route("/admin/stats", get(admin_stats))
        .route("/admin/config", get(get_config))
        .route("/admin/config", put(update_config))
        .route("/admin/cache/clear", post(clear_cache))
        .with_state(app_state);

    let swagger_ui = SwaggerUi::new("/swagger-ui").url("/api-docs/openapi.json", ApiDoc::openapi());
    let redoc = Redoc::with_url("/redoc", ApiDoc::openapi());

    let app = router.merge(swagger_ui).merge(redoc);

    Ok(app)
}

/// Health check endpoint
#[utoipa::path(
    get,
    path = "/health",
    responses(
        (status = 200, description = "Service is healthy")
    )
)]
async fn health_handler() -> Result<Json<Value>, StatusCode> {
    Ok(Json(serde_json::json!({
        "status": "healthy",
        "service": "opencrates",
        "timestamp": chrono::Utc::now().to_rfc3339(),
        "version": env!("CARGO_PKG_VERSION")
    })))
}

/// Readiness check endpoint
#[utoipa::path(
    get,
    path = "/ready",
    responses(
        (status = 200, description = "Service is ready to accept traffic")
    )
)]
async fn ready_handler() -> Result<Json<Value>, StatusCode> {
    Ok(Json(serde_json::json!({
        "status": "ready",
        "timestamp": chrono::Utc::now().to_rfc3339()
    })))
}

/// Metrics endpoint
#[utoipa::path(
    get,
    path = "/metrics",
    responses(
        (status = 200, description = "Prometheus metrics")
    )
)]
async fn metrics_handler() -> Result<String, StatusCode> {
    Ok("# OpenCrates metrics placeholder\n".to_string())
}

/// Generate crate endpoint
#[utoipa::path(
    post,
    path = "/api/v1/generate",
    responses(
        (status = 200, description = "Crate generation placeholder")
    )
)]
async fn generate_handler(
    State(_app_state): State<AppState>,
    Json(_payload): Json<Value>,
) -> Result<Json<Value>, StatusCode> {
    // TODO: This is a general purpose handler, `codex_generate_handler` is the one to use for now
    Err(StatusCode::NOT_IMPLEMENTED)
}

/// Codex code generation endpoint
#[utoipa::path(
    post,
    path = "/api/v1/codex/generate",
    request_body = CodeGenerationRequest,
    responses(
        (status = 200, description = "Code generated successfully", body = CodeGenerationResponse)
    )
)]
async fn codex_generate_handler(
    State(app_state): State<AppState>,
    Json(request): Json<CodeGenerationRequest>,
) -> Result<Json<CodeGenerationResponse>, StatusCode> {
    info!("Handling codex code generation request");
    let provider = app_state
        .core
        .providers
        .get_provider("codex")
        .ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;

    let gen_request = crate::providers::GenerationRequest {
        spec: CrateSpec::default(), // Not really used for this kind of generation
        prompt: Some(request.instruction),
        max_tokens: Some(4096),
        model: None,
        temperature: None,
        context: request.context,
    };

    let response = provider.generate(&gen_request).await.map_err(|e| {
        error!("Codex generation failed: {}", e);
        StatusCode::INTERNAL_SERVER_ERROR
    })?;

    let response = CodeGenerationResponse {
        code: response.preview,
        metadata: GenerationMetadata {
            model: "codex".to_string(), // This should be dynamic
            tokens_used: response.metrics.total_tokens,
            timestamp: Utc::now().to_rfc3339(),
        },
    };

    Ok(Json(response))
}

/// Codex patch application endpoint
#[utoipa::path(
    post,
    path = "/api/v1/codex/apply-patch",
    request_body = PatchApplicationRequest,
    responses(
        (status = 200, description = "Patch applied successfully", body = PatchApplicationResponse)
    )
)]
async fn codex_apply_patch_handler(
    State(app_state): State<AppState>,
    Json(request): Json<PatchApplicationRequest>,
) -> Result<Json<PatchApplicationResponse>, StatusCode> {
    info!("Handling codex patch application request");
    let provider = app_state
        .core
        .providers
        .get_provider("codex")
        .ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;
    let codex_provider = provider
        .as_any()
        .downcast_ref::<CodexProvider>()
        .ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;

    let file_path = std::path::PathBuf::from(&request.file_path);
    codex_provider
        .apply_patch(&file_path, &request.patch_content)
        .map_err(|e| {
            error!("Failed to apply patch: {}", e);
            StatusCode::INTERNAL_SERVER_ERROR
        })?;

    let response = PatchApplicationResponse {
        success: true,
        message: "Patch applied successfully".to_string(),
        file_path: request.file_path,
    };

    Ok(Json(response))
}

/// Codex health check endpoint
#[utoipa::path(
    get,
    path = "/api/v1/codex/health",
    responses(
        (status = 200, description = "Codex provider is healthy")
    )
)]
async fn codex_health_handler(
    State(app_state): State<AppState>,
) -> Result<Json<Value>, StatusCode> {
    info!("Handling codex health request");
    let provider = app_state
        .core
        .providers
        .get_provider("codex")
        .ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;
    let health = provider.health_check().await.map_err(|e| {
        error!("Codex health check failed: {}", e);
        StatusCode::INTERNAL_SERVER_ERROR
    })?;
    let status = if health { "ok" } else { "error" };
    Ok(Json(serde_json::json!({ "status": status })))
}

/// Codex available models endpoint
#[utoipa::path(
    get,
    path = "/api/v1/codex/models",
    responses(
        (status = 200, description = "List of available models")
    )
)]
async fn codex_models_handler(
    State(_app_state): State<AppState>,
) -> Result<Json<Value>, StatusCode> {
    info!("Handling codex models request");
    // Codex provider does not have a concept of models in the same way as OpenAI
    let models = vec!["davinci-codex"];
    Ok(Json(serde_json::json!({ "models": models })))
}

/// For integration tests: build a test server router
pub async fn create_test_server() -> Result<Router> {
    let config = OpenCratesConfig::default();
    create_app(config).await
}

/// Runs the main `OpenCrates` server.
pub async fn run_server(config: OpenCratesConfig) -> Result<()> {
    info!("Starting OpenCrates server v{}", env!("CARGO_PKG_VERSION"));
    let app = create_app(config).await?;

    let host = "127.0.0.1";
    let port = 8080;
    info!("Server listening on http://{}:{}", host, port);

    let addr = SocketAddr::new(host.parse().unwrap(), port);
    let listener = TcpListener::bind(addr).await?;
    axum::serve(listener, app).await?;

    Ok(())
}

pub use crate::utils::fastapi_integration::create_router as build_router;

async fn request_id_middleware(
    mut request: axum::http::Request<axum::body::Body>,
    next: Next,
) -> Result<Response, StatusCode> {
    if !request.headers().contains_key("x-request-id") {
        let request_id = Uuid::new_v4().to_string();
        request.headers_mut().insert(
            "x-request-id",
            request_id
                .parse()
                .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
        );
    }
    Ok(next.run(request).await)
}

async fn rate_limit_middleware(
    request: axum::http::Request<axum::body::Body>,
    next: Next,
) -> Result<Response, StatusCode> {
    // Rate limiting logic would go here
    // For now, just pass through
    Ok(next.run(request).await)
}

async fn auth_middleware(
    request: axum::http::Request<axum::body::Body>,
    next: Next,
) -> Result<Response, StatusCode> {
    // Authentication logic would go here
    // Check for API key or JWT token
    if let Some(_auth_header) = request.headers().get("authorization") {
        // Validate token
    }
    Ok(next.run(request).await)
}

/// Generate a new Rust crate using AI
#[utoipa::path(
    post,
    path = "/api/v1/generate",
    request_body = GenerateRequest,
    responses(
        (status = 200, description = "Crate generated successfully", body = GenerateResponse),
        (status = 400, description = "Invalid request", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError),
    ),
    tag = "generation"
)]
async fn generate_crate(
    State(state): State<AppState>,
    headers: HeaderMap,
    Json(request): Json<GenerateRequest>,
) -> Result<Json<GenerateResponse>, StatusCode> {
    let request_id = headers
        .get("x-request-id")
        .and_then(|h| h.to_str().ok())
        .unwrap_or("unknown")
        .to_string();

    let start_time = std::time::Instant::now();

    // Create generation context
    let provider = request.provider.unwrap_or_else(|| "openai".to_string());

    match state
        .core
        .generate_crate(
            &request.name,
            &request.description,
            request.features.clone(),
            "./output".into(),
        )
        .await
    {
        Ok(()) => {
            // Create a CrateSpec from the request since generate_crate returns ()
            let crate_spec = CrateSpec {
                name: request.name.clone(),
                description: request.description.clone(),
                version: "0.1.0".to_string(),
                authors: vec!["OpenCrates".to_string()],
                license: Some("MIT".to_string()),
                crate_type: CrateType::Library,
                dependencies: std::collections::HashMap::new(),
                dev_dependencies: std::collections::HashMap::new(),
                features: request.features,
                keywords: vec![],
                categories: vec![],
                repository: None,
                homepage: None,
                documentation: None,
                readme: None,
                rust_version: None,
                edition: "2021".to_string(),
                publish: true,
                author: None,
                template: None,
            };
            let generation_time = start_time.elapsed();

            let response = GenerateResponse {
                request_id,
                crate_spec,
                metrics: GenerationMetrics {
                    generation_time_ms: generation_time.as_millis() as u64,
                    tokens_used: None, // Would be populated by AI provider
                    cost_estimate: None,
                    provider,
                },
                message: "Crate generated successfully".to_string(),
            };

            Ok(Json(response))
        }
        Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
    }
}

/// Analyze an existing Rust project
#[utoipa::path(
    post,
    path = "/api/v1/analyze",
    request_body = AnalyzeRequest,
    responses(
        (status = 200, description = "Analysis completed successfully", body = AnalysisResult),
        (status = 400, description = "Invalid request", body = ApiError),
        (status = 500, description = "Internal server error", body = ApiError),
    ),
    tag = "analysis"
)]
async fn analyze_project(
    State(state): State<AppState>,
    Json(request): Json<AnalyzeRequest>,
) -> Result<Json<AnalysisResult>, StatusCode> {
    let analysis = state.core.analyze_crate(&request.path).await.map_err(|e| {
        error!("Failed to analyze project: {}", e);
        StatusCode::INTERNAL_SERVER_ERROR
    })?;

    Ok(Json(analysis))
}

/// Get system health status
#[utoipa::path(
    get,
    path = "/system/health",
    responses(
        (status = 200, description = "System is healthy", body = HealthStatus),
        (status = 503, description = "System is unhealthy", body = HealthStatus),
    ),
    tag = "system"
)]
async fn health_check(State(state): State<AppState>) -> impl IntoResponse {
    let health = state.health.get_health_info().await;
    Json(health)
}

async fn detailed_health_check(State(state): State<AppState>) -> impl IntoResponse {
    let health = state.health.get_health_info().await;
    Json(health)
}

/// Get system status information
#[utoipa::path(
    get,
    path = "/system/status",
    responses(
        (status = 200, description = "System status retrieved successfully"),
    ),
    tag = "system"
)]
async fn system_status(State(state): State<AppState>) -> Json<serde_json::Value> {
    let status = state.core.get_system_status().await.unwrap();
    Json(serde_json::json!(status))
}

/// Get Prometheus metrics
#[utoipa::path(
    get,
    path = "/system/metrics",
    responses(
        (status = 200, description = "Metrics retrieved successfully"),
    ),
    tag = "system"
)]
async fn metrics_endpoint(State(state): State<AppState>) -> impl IntoResponse {
    match state.metrics.export_prometheus().await {
        Ok(metrics) => (StatusCode::OK, metrics).into_response(),
        Err(e) => {
            error!("Failed to export metrics: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

/// List available templates
#[utoipa::path(
    get,
    path = "/api/v1/templates",
    responses(
        (status = 200, description = "Templates retrieved successfully"),
    ),
    tag = "templates"
)]
async fn list_templates(State(state): State<AppState>) -> Json<Vec<String>> {
    let templates = state.core.template_manager.templates();
    let template_names: Vec<String> = templates.keys().cloned().collect();
    Json(template_names)
}

/// List available AI providers
#[utoipa::path(
    get,
    path = "/api/v1/providers",
    responses(
        (status = 200, description = "Providers retrieved successfully"),
    ),
    tag = "providers"
)]
async fn list_providers(State(_state): State<AppState>) -> Json<Vec<String>> {
    let providers = vec!["openai".to_string(), "codex".to_string()]; // TODO: Replace with actual provider names from registry
    Json(providers)
}

/// List available models for a given provider
#[utoipa::path(
    get,
    path = "/providers/:provider/models",
    responses(
        (status = 200, description = "List of available models")
    ),
    tag = "providers"
)]
async fn list_provider_models(
    State(state): State<AppState>,
    Path(provider): Path<String>,
) -> Json<Vec<String>> {
    let models = state
        .core
        .providers()
        .get_provider(&provider)
        .map(|_p| {
            serde_json::json!({
                "name": "default_model",
                "provider": "openai"
            })
        })
        .map(|_info| vec!["default_model".to_string()])
        .unwrap_or_default();
    Json(models)
}

/// Get server version information
#[utoipa::path(
    get,
    path = "/version",
    responses(
        (status = 200, description = "Server version information")
    ),
    tag = "system"
)]
async fn version_info() -> Json<serde_json::Value> {
    Json(serde_json::json!({
        "version": env!("CARGO_PKG_VERSION"),
        "build_timestamp": std::env::var("VERGEN_BUILD_TIMESTAMP").unwrap_or_else(|_| "unknown".to_string()),
        "git_sha": std::env::var("VERGEN_GIT_SHA").unwrap_or_else(|_| "unknown".to_string())
    }))
}

/// Get admin statistics
#[utoipa::path(
    get,
    path = "/admin/stats",
    responses(
        (status = 200, description = "Server statistics")
    ),
    tag = "admin"
)]
async fn admin_stats(State(app_state): State<AppState>) -> Json<serde_json::Value> {
    let statistics = serde_json::json!({
        "uptime_seconds": app_state.start_time.elapsed().as_secs(),
        "core_stats": "Not implemented"
    });
    Json(statistics)
}

/// Get current server configuration
#[utoipa::path(
    get,
    path = "/admin/config",
    responses(
        (status = 200, description = "Current server configuration")
    ),
    tag = "admin"
)]
async fn get_config(State(state): State<AppState>) -> Json<OpenCratesConfig> {
    Json(state.core.config.as_ref().clone())
}

/// Update server configuration
#[utoipa::path(
    put,
    path = "/admin/config",
    request_body = OpenCratesConfig,
    responses(
        (status = 200, description = "Server configuration updated successfully")
    ),
    tag = "admin"
)]
async fn update_config(
    State(_state): State<AppState>,
    Json(_new_config): Json<OpenCratesConfig>,
) -> StatusCode {
    // TODO: Implement update_config method in ConfigManager
    if false {
        // Placeholder for actual config update
        let e = "update not implemented";
        error!("Failed to update config: {}", e);
        return StatusCode::INTERNAL_SERVER_ERROR;
    }
    StatusCode::OK
}

/// Clear server cache
#[utoipa::path(
    post,
    path = "/admin/cache/clear",
    responses(
        (status = 200, description = "Server cache cleared")
    ),
    tag = "admin"
)]
async fn clear_cache(State(_state): State<AppState>) -> StatusCode {
    // TODO: Implement clear method for cache
    info!("Cache clear requested");
    StatusCode::OK
}

async fn root_handler() -> Html<&'static str> {
    Html(
        r#"
    <!DOCTYPE html>
    <html>
    <head>
        <title>OpenCrates API</title>
        <style>
            body { font-family: Arial, sans-serif; margin: 40px; }
            h1 { color: #ff6b35; }
            a { color: #007acc; text-decoration: none; }
            a:hover { text-decoration: underline; }
            .links { margin: 20px 0; }
            .links a { display: inline-block; margin-right: 20px; padding: 10px 15px; 
                      background: #f0f0f0; border-radius: 5px; }
        </style>
    </head>
    <body>
        <h1> OpenCrates API Server</h1>
        <p>Enterprise-grade AI-powered Rust development companion</p>
        <div class="links">
            <a href="/docs"> Swagger UI</a>
            <a href="/redoc"> ReDoc</a>
                            <a href="/system/health">Health Check</a>
                <a href="/system/status">System Status</a>
                <a href="/system/metrics">Metrics</a>
        </div>
        <p>Version: 3.0.0 | Status: Running</p>
    </body>
    </html>
    "#,
    )
}