aimo-cli 0.4.0

AiMo Network client CLI
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
use std::collections::HashMap;
use std::path::PathBuf;
use std::str::FromStr;

use aimo_client::types::providers::{RegisterProviderRequest, RegisterProviderResponse};
use aimo_core::utils::id::create_keypair_from_file;
use aimo_core::{
    keys::SecretKeyV1,
    transport::{Request, Response},
};
use anyhow::{Context, Result, anyhow};
use canonical_json;
use futures_util::{SinkExt, stream::StreamExt};
use reqwest::{Client, Method};
use serde::Deserialize;
use serde_json;
use solana_sdk::{pubkey::Pubkey, signature::Keypair, signer::Signer};
use tokio::sync::mpsc::{self, UnboundedSender};
use tokio_tungstenite::{
    connect_async,
    tungstenite::{self, Message},
};
use tracing::{debug, error, info, warn};
use url::Url;

use crate::config::ProxyConfig;

/// Proxy aimo node requests to standard http endpoints
///
/// 1. Connect to aimo node's websocket endpoint
/// 2. On receiving serialized `Request` messages, spawn a tokio thread to do the following:
///     a. Deserialize the `Request`, extract its payload;
///     b. Forward the request payload to the http endpoint;
///     c. Wait for response.
///     d. If the response is a normal http response, wrap the response in `Response` message,
///         send it back through websocket, and quit the thread.
///     e. If the response is a SSE stream, wrap each chunk inside the `Response` message, and
///         send back through websocket in receiving sequence.
pub async fn serve_websocket(
    node_url: String,
    secret_key: String,
    endpoint_url: String,
    api_key: Option<String>,
) -> anyhow::Result<()> {
    info!("Starting proxy service...");
    info!("Node URL: {}", node_url);
    info!("Endpoint URL: {}", endpoint_url);

    // Parse and build WebSocket URL
    let ws_url = build_websocket_url(&node_url, &secret_key)?;
    info!("Connecting to WebSocket: {}", ws_url);

    // Connect to the node's websocket endpoint
    let url = url::Url::parse(&ws_url)?;

    debug!("=== WEBSOCKET CONNECTION SETUP ===");
    debug!("Target URL: {}", ws_url);
    debug!("Host: {}", url.host_str().unwrap_or("localhost"));
    debug!(
        "Secret key prefix: {}...",
        &secret_key[..std::cmp::min(10, secret_key.len())]
    );

    let websocket_key = tungstenite::handshake::client::generate_key();
    debug!("Generated WebSocket key: {}", websocket_key);

    let request = tungstenite::http::Request::builder()
        .method("GET")
        .uri(ws_url.as_str())
        .header("Host", url.host_str().unwrap_or("localhost"))
        .header("Upgrade", "websocket")
        .header("Connection", "Upgrade")
        .header("Sec-WebSocket-Key", &websocket_key)
        .header("Sec-WebSocket-Version", "13")
        .header("Authorization", format!("Bearer {}", secret_key))
        .body(())?;

    debug!("=== WEBSOCKET REQUEST HEADERS ===");
    for (name, value) in request.headers() {
        if name == "authorization" {
            debug!(
                "{}: Bearer {}...",
                name,
                &secret_key[..std::cmp::min(10, secret_key.len())]
            );
        } else {
            debug!("{}: {:?}", name, value);
        }
    }

    debug!("Attempting WebSocket connection...");
    let connection_result = connect_async(request).await;

    match connection_result {
        Ok((ws_stream, response)) => {
            info!("WebSocket connection established successfully");
            debug!("=== WEBSOCKET RESPONSE ===");
            debug!("Status: {}", response.status());
            debug!("Response headers:");
            for (name, value) in response.headers() {
                debug!("  {}: {:?}", name, value);
            }

            let (mut ws_sender, mut ws_receiver) = ws_stream.split();
            let http_client = Client::new();

            // Create a channel for sending responses back to the websocket
            let (response_tx, mut response_rx) = mpsc::unbounded_channel::<Message>();

            // Spawn task to handle outgoing messages
            let sender_task = tokio::spawn(async move {
                while let Some(message) = response_rx.recv().await {
                    if let Err(e) = ws_sender.send(message).await {
                        error!("Failed to send message through WebSocket: {}", e);
                        break;
                    }
                }
                debug!("WebSocket sender task terminated");
            });

            // Main message loop
            loop {
                match ws_receiver.next().await {
                    Some(Ok(Message::Text(text))) => {
                        debug!("Received message: {}", text);

                        // Parse the request directly (no MessageFrame wrapper)
                        let request: Request = match serde_json::from_str::<Request>(&text) {
                            Ok(req) => {
                                info!(
                                    "Parsed request successfully - ID: {}, Method: {}, Type: {}",
                                    req.request_id, req.method, req.request_type
                                );
                                req
                            }
                            Err(e) => {
                                warn!("Failed to parse request: {}", e);
                                warn!("Raw message was: {}", text);
                                continue;
                            }
                        }; // Clone necessary data for the spawned task
                        let endpoint_url = endpoint_url.clone();
                        let api_key = api_key.clone();
                        let client = http_client.clone();
                        let response_sender = response_tx.clone();

                        // Spawn a task to handle this request
                        tokio::spawn(async move {
                            if let Err(e) = handle_request(
                                client,
                                request,
                                endpoint_url,
                                api_key,
                                response_sender,
                            )
                            .await
                            {
                                error!("Error handling request: {}", e);
                            }
                        });
                    }
                    Some(Ok(Message::Close(_))) => {
                        info!("WebSocket connection closed by server");
                        break;
                    }
                    Some(Ok(_)) => {
                        // Ignore other message types (Binary, Ping, Pong)
                        debug!("Received non-text message, ignoring");
                    }
                    Some(Err(e)) => {
                        error!("WebSocket error: {}", e);
                        break;
                    }
                    None => {
                        info!("WebSocket stream ended");
                        break;
                    }
                }
            }

            // Clean up
            sender_task.abort();
            info!("WebSocket connection terminated, proxy service stopped");

            // Return an error to indicate the connection was lost so the retry loop can handle it
            Err(anyhow!("WebSocket connection lost"))
        }
        Err(e) => {
            error!("=== WEBSOCKET CONNECTION FAILED ===");
            error!("Connection error: {}", e);

            // Try to extract more detailed error information
            match &e {
                tungstenite::Error::Http(http_response) => {
                    error!("HTTP error during WebSocket handshake:");
                    error!("Status: {}", http_response.status());
                    error!("Response headers:");
                    for (name, value) in http_response.headers() {
                        error!("  {}: {:?}", name, value);
                    }

                    // Try to read the response body if available
                    if let Some(body) = http_response.body() {
                        if !body.is_empty() {
                            error!(
                                "Response body: {:?}",
                                std::str::from_utf8(body).unwrap_or("Invalid UTF-8")
                            );
                        }
                    }
                }
                tungstenite::Error::Url(url_error) => {
                    error!("URL error: {}", url_error);
                }
                tungstenite::Error::Tls(tls_error) => {
                    error!("TLS error: {}", tls_error);
                }
                tungstenite::Error::Io(io_error) => {
                    error!("IO error: {}", io_error);
                }
                _ => {
                    error!("Other WebSocket error: {}", e);
                }
            }

            Err(anyhow!("Failed to connect to WebSocket: {}", e))
        }
    }
}

/// Build the WebSocket URL with authentication
fn build_websocket_url(node_url: &str, _secret_key: &str) -> Result<String> {
    let mut url = Url::parse(node_url)?;

    // Convert HTTP(S) to WS(S)
    match url.scheme() {
        "http" => url
            .set_scheme("ws")
            .map_err(|_| anyhow!("Invalid scheme"))?,
        "https" => url
            .set_scheme("wss")
            .map_err(|_| anyhow!("Invalid scheme"))?,
        "ws" | "wss" => {} // Already correct
        _ => return Err(anyhow!("Unsupported URL scheme: {}", url.scheme())),
    }

    // Add subscribe endpoint
    url.set_path("/api/v1/providers/subscribe");

    Ok(url.to_string())
}

/// Handle a single request by forwarding it to the HTTP endpoint
async fn handle_request(
    client: Client,
    request: Request,
    endpoint_url: String,
    api_key: Option<String>,
    response_sender: UnboundedSender<Message>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    debug!("Handling request ID: {}", request.request_id);

    // Parse the HTTP method from the new method field
    let method_str = request.method.to_uppercase();
    let method = match method_str.as_str() {
        "GET" => Method::GET,
        "POST" => Method::POST,
        "PUT" => Method::PUT,
        "DELETE" => Method::DELETE,
        "PATCH" => Method::PATCH,
        "HEAD" => Method::HEAD,
        "OPTIONS" => Method::OPTIONS,
        _ => {
            warn!("Unsupported HTTP method: {}", request.method);
            send_error_response(
                &response_sender,
                &request.request_id,
                400,
                "Unsupported HTTP method",
            )?;
            return Ok(());
        }
    };

    // Build the target URL
    let target_url = if let Some(endpoint) = &request.endpoint {
        format!(
            "{}/{}",
            endpoint_url.trim_end_matches('/'),
            endpoint.trim_start_matches('/')
        )
    } else {
        endpoint_url.clone()
    };

    debug!("=== REQUEST DETAILS ===");
    debug!("Method: {}", method_str);
    debug!("Target URL: {}", target_url);
    debug!("Original endpoint: {:?}", request.endpoint);
    debug!("Request type: {}", request.request_type);
    debug!("Request headers ({} total):", request.headers.len());
    for (key, value) in &request.headers {
        debug!("  {}: {}", key, value);
    }
    debug!("Request payload length: {} bytes", request.payload.len());
    if !request.payload.is_empty() {
        debug!("Request payload (full): {}", request.payload);

        // Try to parse as JSON for better formatting
        if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(&request.payload) {
            debug!(
                "Request payload (formatted JSON): {}",
                serde_json::to_string_pretty(&json_value)
                    .unwrap_or_else(|_| request.payload.clone())
            );
        }
    }

    // Build the HTTP request
    let mut http_request = client.request(method, &target_url);
    debug!("=== HTTP REQUEST CONSTRUCTION ===");

    // Add headers from the original request
    for (key, value) in &request.headers {
        debug!("Adding header: {}: {}", key, value);
        http_request = http_request.header(key, value);
    }

    // Add API key if provided
    if let Some(api_key) = &api_key {
        debug!(
            "Adding Authorization header with API key: Bearer {}",
            api_key.clone()
        );
        http_request = http_request.header("Authorization", format!("Bearer {}", api_key));
    }

    // Add body if present
    if !request.payload.is_empty() {
        // Try to determine content type from headers or default to JSON
        let content_type = request
            .headers
            .get("content-type")
            .or_else(|| request.headers.get("Content-Type"))
            .map(|s| s.as_str())
            .unwrap_or("application/json");

        debug!("Setting content-type to: {}", content_type);
        debug!("Setting request body: {}", request.payload);
        http_request = http_request
            .header("Content-Type", content_type)
            .body(request.payload.clone());
    }

    debug!("Sending HTTP request...");
    debug!("=== SENDING HTTP REQUEST ===");
    debug!("About to send HTTP request...");

    // Send the request
    match http_request.send().await {
        Ok(response) => {
            let status = response.status();
            debug!("=== HTTP RESPONSE RECEIVED ===");
            debug!(
                "Response status: {} {}",
                status.as_u16(),
                status.canonical_reason().unwrap_or("")
            );

            let headers: HashMap<String, String> = response
                .headers()
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
                .collect();

            debug!("Response headers ({} total):", headers.len());
            for (key, value) in &headers {
                debug!("  {}: {}", key, value);
            }

            // Log detailed error information for 4xx and 5xx status codes
            if status.is_client_error() || status.is_server_error() {
                error!("=== HTTP ERROR RESPONSE ===");
                error!(
                    "Status: {} {}",
                    status.as_u16(),
                    status.canonical_reason().unwrap_or("")
                );
                error!("Request ID: {}", request.request_id);
                error!("Target URL: {}", target_url);
                error!("Method: {}", method_str);

                // For 400 errors, log the response body for debugging
                if status.as_u16() == 400 {
                    error!("=== 400 BAD REQUEST DETAILS ===");
                    let error_body = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Failed to read error body".to_string());
                    error!("Error response body: {}", error_body);

                    // Send the error response back
                    let error_response = Response {
                        request_id: request.request_id.to_string(),
                        status_code: 400,
                        content_type: "text/plain".to_string(),
                        payload: error_body,
                        headers,
                        is_stream_chunk: false,
                        stream_done: true,
                    };

                    let message = Message::text(serde_json::to_string(&error_response)?);
                    if let Err(e) = response_sender.send(message) {
                        warn!(
                            "Failed to send error response, WebSocket connection likely closed: {}",
                            e
                        );
                    }
                    return Ok(());
                }
            }

            // Filter headers to only include essential ones
            // let filtered_headers = filter_essential_headers(&headers, ESSENTIAL_RESPONSE_HEADERS);

            let content_type = headers
                .get("content-type")
                .or_else(|| headers.get("Content-Type"))
                .unwrap_or(&"text/plain".to_string())
                .clone();

            // Check if this is a Server-Sent Events stream
            if content_type.contains("text/event-stream") || content_type.contains("text/stream") {
                debug!("Handling SSE stream for request {}", request.request_id);
                handle_sse_stream(
                    response,
                    &response_sender,
                    &request.request_id,
                    &content_type,
                    // filtered_headers,
                    headers,
                )
                .await?;
            } else {
                debug!(
                    "Handling regular HTTP response for request {}",
                    request.request_id
                );
                handle_regular_response(
                    response,
                    &response_sender,
                    &request.request_id,
                    &content_type,
                    // filtered_headers,
                    headers,
                )
                .await?;
            }
        }
        Err(e) => {
            error!("HTTP request failed: {}", e);
            error!("Error details: {:?}", e);

            // Check if it's a connection error, timeout, etc.
            if e.is_connect() {
                error!("Connection error - unable to connect to {}", target_url);
            } else if e.is_timeout() {
                error!("Request timeout");
            } else if e.is_request() {
                error!("Request construction error");
            } else {
                error!("Other HTTP error type");
            }

            send_error_response(
                &response_sender,
                &request.request_id,
                500,
                &format!("HTTP request failed: {}", e),
            )?;
        }
    }

    Ok(())
}

/// Handle a regular (non-streaming) HTTP response
async fn handle_regular_response(
    response: reqwest::Response,
    response_sender: &UnboundedSender<Message>,
    request_id: &str,
    content_type: &str,
    headers: HashMap<String, String>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let status_code = response.status().as_u16();
    let body = response.text().await.unwrap_or_else(|_| "".to_string());

    info!(
        "Endpoint response - Status: {}, Content-Type: {}",
        status_code, content_type
    );
    info!("Response body length: {} bytes", body.len());
    debug!(
        "Response body: {}",
        if body.len() > 1000 {
            format!("{}...", &body[..1000])
        } else {
            body.clone()
        }
    );

    let response = Response {
        request_id: request_id.to_string(),
        status_code,
        content_type: content_type.to_string(),
        payload: body,
        headers,
        is_stream_chunk: false,
        stream_done: true,
    };

    let message = Message::text(serde_json::to_string(&response)?);
    if let Err(e) = response_sender.send(message) {
        warn!(
            "Failed to send regular response, WebSocket connection likely closed: {}",
            e
        );
        return Err(e.into());
    }

    debug!("Sent regular response for request {}", request_id);
    Ok(())
}

/// Handle a Server-Sent Events (SSE) stream response
async fn handle_sse_stream(
    response: reqwest::Response,
    response_sender: &UnboundedSender<Message>,
    request_id: &str,
    content_type: &str,
    headers: HashMap<String, String>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let status_code = response.status().as_u16();
    info!(
        "Starting SSE stream - Status: {}, Content-Type: {}",
        status_code, content_type
    );
    let mut stream = response.bytes_stream();

    // Buffer to hold raw, potentially partial lines across chunks
    let mut line_buffer = String::new();
    // Accumulator for multi-line SSE data fields for one event
    let mut current_event_data = String::new();

    // Local structs for logging deltas
    #[derive(Deserialize, Clone)]
    struct ChunkSchema {
        choices: Vec<ChunkChoice>,
    }
    #[derive(Deserialize, Clone)]
    struct ChunkChoice {
        delta: ChunkDelta,
    }
    #[derive(Deserialize, Clone)]
    struct ChunkDelta {
        content: String,
    }

    // Helper to send a single SSE data payload as a chunked response
    let send_payload = |payload: String| -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        // Log delta for debugging
        let chunk_delta = serde_json::from_str::<ChunkSchema>(&payload)
            .ok()
            .and_then(|data| data.choices.first().cloned())
            .map(|first| first.delta.content.clone())
            .unwrap_or("[null]".to_string());
        tracing::debug!("delta: {chunk_delta}");

        let response = Response {
            request_id: request_id.to_string(),
            status_code,
            content_type: content_type.to_string(),
            payload,
            headers: headers.clone(),
            is_stream_chunk: true,
            stream_done: false,
        };

        let message = Message::text(serde_json::to_string(&response)?);
        if response_sender.send(message).is_err() {
            warn!("Failed to send stream chunk, WebSocket connection likely closed");
            // Propagate an error to abort the stream cleanly
            return Err("WebSocket connection likely closed".into());
        }
        debug!("Sent parsed stream chunk for request {}", request_id);
        Ok(())
    };

    'outer: while let Some(chunk_result) = stream.next().await {
        match chunk_result {
            Ok(chunk) => {
                // Append the new bytes to our buffer
                let chunk_data = String::from_utf8_lossy(&chunk).to_string();
                line_buffer.push_str(&chunk_data);

                // Process complete lines; keep the final partial (if any) in line_buffer
                loop {
                    if let Some(pos) = line_buffer.find('\n') {
                        // Extract one line (strip trailing CR and LF)
                        let line = line_buffer[..pos].trim_end_matches('\r').to_string();
                        // Remove the processed line (including '\n') from the buffer
                        line_buffer.drain(..=pos);

                        let trimmed = line.trim();

                        // Empty line indicates end of one SSE event
                        if trimmed.is_empty() {
                            if !current_event_data.is_empty() {
                                // Emit the accumulated event
                                let payload = current_event_data.clone();
                                current_event_data.clear();
                                if let Err(e) = send_payload(payload) {
                                    // Abort on send error
                                    return Err(e);
                                }
                            }
                            continue;
                        }

                        // Only process data: lines; ignore other SSE fields
                        if let Some(rest) = line.strip_prefix("data: ") {
                            if rest == "[DONE]" {
                                // Flush any pending event data before signaling done
                                if !current_event_data.is_empty() {
                                    let payload = current_event_data.clone();
                                    current_event_data.clear();
                                    if let Err(e) = send_payload(payload) {
                                        return Err(e);
                                    }
                                }
                                // Emit the [DONE] marker as a payload to match existing behavior
                                if let Err(e) = send_payload("[DONE]".to_string()) {
                                    return Err(e);
                                }
                                // Break out after sending final done marker
                                break 'outer;
                            } else {
                                if !current_event_data.is_empty() {
                                    current_event_data.push('\n');
                                }
                                current_event_data.push_str(rest);
                            }
                        }
                        // Any non "data:" lines are ignored per SSE spec, but do not clear state
                    } else {
                        // No full line available yet; wait for more data
                        break;
                    }
                }
            }
            Err(e) => {
                error!("Error reading stream chunk: {}", e);
                break;
            }
        }
    }

    // If the stream ended without a trailing empty line, flush any pending event data
    if !current_event_data.is_empty() {
        let payload = std::mem::take(&mut current_event_data);
        if let Err(e) = send_payload(payload) {
            return Err(e);
        }
    }

    info!("SSE stream completed for request {}", request_id);
    // Send final "stream done" message
    let final_response = Response {
        request_id: request_id.to_string(),
        status_code,
        content_type: content_type.to_string(),
        payload: "".to_string(),
        headers,
        is_stream_chunk: true,
        stream_done: true,
    };

    let message = Message::text(serde_json::to_string(&final_response)?);
    if let Err(e) = response_sender.send(message) {
        warn!(
            "Failed to send final stream response, WebSocket connection likely closed: {}",
            e
        );
        return Err(e.into());
    }

    debug!("Stream completed for request {}", request_id);
    Ok(())
}

/// Parse SSE chunk to extract JSON data content
/// Returns None if the chunk doesn't contain valid data or is a control message
///
/// # Deprecated
///
/// This function is known to have bugs and should not be used.
#[allow(dead_code)]
fn parse_sse_chunk(chunk_data: &str) -> Option<String> {
    for line in chunk_data.lines() {
        let line = line.trim();
        if line.starts_with("data: ") {
            let json_str = &line[6..]; // Remove "data: " prefix
            if json_str == "[DONE]" {
                // For [DONE] messages, return as-is without data: prefix
                return Some("[DONE]".to_string());
            }
            // For JSON data, return the raw JSON
            if !json_str.is_empty() {
                return Some(json_str.to_string());
            }
        }
    }
    None
}

/// Send an error response back through the WebSocket
fn send_error_response(
    response_sender: &UnboundedSender<Message>,
    request_id: &str,
    status_code: u16,
    error_message: &str,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let response = Response {
        request_id: request_id.to_string(),
        status_code,
        content_type: "text/plain".to_string(),
        payload: error_message.to_string(),
        headers: HashMap::new(),
        is_stream_chunk: false,
        stream_done: true,
    };

    let message = Message::text(serde_json::to_string(&response)?);

    // Handle the case where the WebSocket connection might be closed
    if let Err(e) = response_sender.send(message) {
        warn!(
            "Failed to send error response, WebSocket connection likely closed: {}",
            e
        );
    }

    Ok(())
}

/// New entry point that loads config file and calls the original serve_websocket with auto-registration
pub async fn serve_websocket_with_config(config_path: PathBuf, id: Option<PathBuf>) -> Result<()> {
    info!(
        "Loading proxy configuration from: {}",
        config_path.display()
    );

    let config = ProxyConfig::from_file(&config_path)?;
    let keypair = create_keypair_from_file(id)?;

    info!("Registering provider before starting websocket proxy");
    register_provider(&config, &keypair).await?;

    info!("Provider registered successfully, starting websocket proxy with retry logic");

    let mut retry_count = 0;

    // Retry loop: attempt to connect every 1 second forever
    loop {
        retry_count += 1;

        if retry_count > 1 {
            info!("Reconnection attempt #{}", retry_count - 1);
        }

        match serve_websocket(
            format!("{}/api/v1/providers/subscribe", config.node_url()),
            config.secret_key().to_string(),
            config.endpoint_url().to_string(),
            Some(config.endpoint_api_key().to_string()),
        )
        .await
        {
            Ok(_) => {
                info!("WebSocket connection closed normally, reconnecting in 1 second...");
            }
            Err(e) => {
                error!(
                    "WebSocket connection failed: {}, reconnecting in 1 second...",
                    e
                );
            }
        }

        // Wait 1 second before retrying
        tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;

        info!("Attempting to reconnect to WebSocket...");
    }
}

/// Register the provider with the AIMO node before starting the proxy
async fn register_provider(config: &ProxyConfig, keypair: &Keypair) -> Result<()> {
    debug!("=== PROVIDER REGISTRATION DEBUG ===");

    // First, let's verify our secret key is valid
    debug!("Verifying secret key validity...");
    let (_scope, secret_key_v1) =
        SecretKeyV1::decode(config.secret_key()).context("Failed to decode secret key")?;

    match secret_key_v1.verify_signature() {
        Ok(_) => debug!("Secret key signature is VALID"),
        Err(e) => {
            error!("Secret key signature is INVALID: {}", e);
            return Err(anyhow!("Secret key has invalid signature: {}", e));
        }
    }

    // Extract the signer pubkey (this is the provider ID)
    let signer_pubkey =
        Pubkey::from_str(&secret_key_v1.signer).context("Failed to parse signer pubkey")?;

    debug!("Secret key signer pubkey: {}", signer_pubkey);
    debug!("Keypair pubkey: {}", keypair.pubkey());
    debug!(
        "Keypair matches secret key: {}",
        keypair.pubkey() == signer_pubkey
    );

    // Serialize metadata to canonical JSON for signing
    let metadata_json =
        serde_json::to_value(&config.metadata).context("Failed to serialize provider metadata")?;
    debug!(
        "Metadata JSON: {}",
        serde_json::to_string_pretty(&metadata_json)?
    );

    let canonical_metadata =
        canonical_json::to_string(&metadata_json).context("Failed to create canonical JSON")?;
    debug!("Canonical metadata string: {}", canonical_metadata);
    debug!(
        "Canonical metadata bytes: {:?}",
        canonical_metadata.as_bytes()
    );

    // Sign the canonical metadata
    let signature = keypair.sign_message(canonical_metadata.as_bytes());
    debug!("Generated signature: {}", signature.to_string());

    // Create the registration request
    let request = RegisterProviderRequest {
        metadata: config.metadata.clone(),
        signature: signature.to_string(),
    };

    debug!(
        "Registration request: {}",
        serde_json::to_string_pretty(&request)?
    );

    // Extract the base URL from router URL (use HTTP version for API calls)
    let base_url = config.router.url.clone();
    let register_url = format!("{}/api/v1/providers/register", base_url);

    debug!("Registration URL: {}", register_url);
    debug!(
        "Authorization header: Bearer {}...",
        &config.secret_key()[..std::cmp::min(10, config.secret_key().len())]
    );

    // Make the HTTP request
    let client = reqwest::Client::new();
    let response = client
        .post(&register_url)
        .header("Authorization", format!("Bearer {}", config.secret_key()))
        .header("Content-Type", "application/json")
        .json(&request)
        .send()
        .await
        .context("Failed to send registration request")?;

    debug!(
        "Received registration response with status: {}",
        response.status()
    );
    debug!("Response headers:");
    for (name, value) in response.headers() {
        debug!("  {}: {:?}", name, value);
    }

    if response.status().is_success() {
        let result: RegisterProviderResponse = response
            .json()
            .await
            .context("Failed to parse registration response")?;
        info!("Provider registration: {}", result.message);
        Ok(())
    } else {
        let status = response.status();
        let error_text = response
            .text()
            .await
            .unwrap_or_else(|_| "Failed to read error response".to_string());

        error!("=== REGISTRATION FAILED ===");
        error!("Status: {}", status);
        error!("Error response body: {}", error_text);

        Err(anyhow!(
            "Provider registration failed with status {}: {}",
            status,
            error_text
        ))
    }
}