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
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
// SPF Smart Gateway - HTTP API Server Transport
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// HTTP API running alongside stdio MCP server.
// Uses Axum 0.8 with Tower middleware stack and optional TLS (axum-server + rustls).
//
// Routes:
//   POST /mcp/v1  — Full JSON-RPC 2.0 (initialize, tools/list, tools/call)
//   GET  /health   — Health check (no auth)
//   GET  /status   — SPF gateway status
//   GET  /tools    — Tool definitions list
//   GET  /ws       — WebSocket (persistent JSON-RPC, auth on upgrade)
//
// Auth modes:
//   "key"    — X-SPF-Key header (API key)
//   "crypto" — Ed25519 signed requests (X-SPF-Pub, X-SPF-Sig, X-SPF-Time, X-SPF-Nonce)
//   "both"   — Accept either method
//
// Middleware (Tower + axum):
//   TraceLayer — structured request/response logging
//   CatchPanicLayer — handler panics → 500 (never crash server)
//   RequestBodyLimitLayer — 10MB (matches original read_body limit)
//   SetSensitiveRequestHeadersLayer — hide auth headers from logs
//   CompressionLayer — gzip response compression
//   CORS (axum::middleware::from_fn) — browser preflight + response headers
//   Timeout — 30s per request via spawn_blocking + tokio::time::timeout
//
// Threading:
//   serve() is async — runs in caller's tokio runtime (shared with mesh in E7).
//   start() is sync wrapper — creates own runtime (backward compat with mcp.rs).
//
// BLOCK SEC-4: SPF_API_KEY env var override in serve() — process-scoped, not in JSON files

use crate::agent_state::AgentStateDb;
use crate::config::SpfConfig;
use crate::config_db::SpfConfigDb;
use crate::fs::SpfFs;
use crate::mcp;
use crate::session::Session;
use crate::storage::SpfStorage;
use crate::tmp_db::SpfTmpDb;
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
use iroh::Endpoint;
use serde_json::{json, Value};
use sha2::{Sha256, Digest};
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// P2: Tracked peer in the mesh.
#[derive(Debug, Clone)]
pub struct MeshPeerStatus {
    pub role: crate::config::AgentRole,
    pub name: String,
    pub last_seen: Instant,
}
use axum::{
    Router,
    middleware,
    routing::{get, post},
    extract::{Request, State, Query, Path, ws::{WebSocketUpgrade, WebSocket, Message}},
    http::{HeaderMap, HeaderName, Method, StatusCode, header},
    response::{IntoResponse, Response},
    body::Body,
    Json,
};
use tower::ServiceBuilder;
use tower_http::{
    trace::TraceLayer,
    limit::RequestBodyLimitLayer,
    catch_panic::CatchPanicLayer,
    sensitive_headers::SetSensitiveRequestHeadersLayer,
    compression::CompressionLayer,
};

const PROTOCOL_VERSION: &str = "2024-11-05";
const TIMESTAMP_WINDOW_SECS: u64 = 30;
const NONCE_EXPIRY_SECS: u64 = 60;

/// Shared server state — used by all transports (stdio, HTTP, mesh).
/// Wrapped in Arc for thread-safe sharing.
pub struct ServerState {
    pub config: SpfConfig,
    pub config_db: Option<SpfConfigDb>,
    pub session: Mutex<Session>,
    pub storage: SpfStorage,
    pub tmp_db: Option<SpfTmpDb>,
    pub agent_db: Option<AgentStateDb>,
    pub fs_db: Option<SpfFs>,
    pub pub_key_hex: String,
    pub trusted_keys: HashSet<String>,
    pub auth_mode: String,
    pub nonce_cache: Mutex<HashMap<String, Instant>>,
    pub listeners: Vec<Box<dyn crate::dispatch::DispatchListener>>,
    /// Mesh endpoint handle for outbound peer calls (None if mesh disabled)
    pub mesh_tx: Option<std::sync::mpsc::Sender<crate::mesh::MeshRequest>>,
    /// Peer info with addresses for direct mesh connections
    pub peers: HashMap<String, crate::identity::PeerInfo>,
    /// Transformer runtime state — None if transformer disabled or not yet loaded
    pub transformer: Option<std::sync::Arc<std::sync::RwLock<crate::transformer_tools::TransformerState>>>,
    /// Transformer configuration — loaded from LIVE/CONFIG/transformer.json
    pub transformer_config: crate::config::TransformerConfig,
    /// Pipeline state for task orchestration
    pub pipeline: std::sync::Arc<std::sync::Mutex<crate::pipeline::PipelineState>>,
    /// Ed25519 signing key — needed for I-4 peer API key derivation
    pub signing_key: ed25519_dalek::SigningKey,
    /// Network pool configuration — role (NetAdmin/Worker), pool size, peer list
    pub network_config: crate::config::NetworkConfig,
    /// Live pool state — None on Worker nodes, Some(Arc<PoolState>) on NetAdmin
    pub pool_state: Option<std::sync::Arc<crate::network::PoolState>>,
    /// Reverse proxy browser session — ProxyEngine + mpsc channel ends
    pub browser: std::sync::Mutex<crate::browser::BrowserSession>,
    /// WsBrowserChannels produced by BrowserSession::connect(), consumed by /ws/browser handler
    pub ws_browser_channels: std::sync::Mutex<Option<crate::browser::WsBrowserChannels>>,
    /// HTTP server port — injected into proxied pages as WebSocket target port
    pub http_port: u16,
    /// P2: Tracked mesh peers — pubkey → MeshPeerStatus
    pub tracked_peers: Mutex<HashMap<String, MeshPeerStatus>>,
    /// P5: Orchestrator state — Some only on orchestrator nodes
    pub orchestrator_state: Mutex<Option<Arc<std::sync::Mutex<crate::orchestrator::OrchestratorState>>>>,
    /// DS: Iroh QUIC endpoint — stored by mesh on startup, used by MCP for direct duplex calls
    pub endpoint: Mutex<Option<Endpoint>>,
    /// DS: Tokio runtime handle — bridges sync MCP thread to async mesh I/O
    pub tokio_handle: Mutex<Option<tokio::runtime::Handle>>,
}

/// P5: Helper — get tracked peer count without full state reference (for tool access).
pub fn tracked_peer_count(state: &Arc<ServerState>) -> usize {
    state.tracked_peers.lock().unwrap().len()
}

/// Application state for Axum handlers — wraps ServerState + API key.
/// Clone is required by Axum's State extractor.
#[derive(Clone)]
struct AppState {
    inner: Arc<ServerState>,
    api_key: String,
}

// ============================================================================
// AUTH — Dual mode: API key + Ed25519 crypto
// ============================================================================

/// Extract a header value by name from Axum HeaderMap.
/// HeaderMap keys are case-insensitive by spec.
fn extract_header(headers: &HeaderMap, name: &str) -> Option<String> {
    headers.get(name)
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_string())
}

/// Dual-mode auth check. Tries API key first, then crypto.
/// Returns true if request is authenticated.
fn check_auth(headers: &HeaderMap, method_str: &str, path: &str,
              body: &str, api_key: &str, state: &ServerState) -> bool {
    let mode = state.auth_mode.as_str();

    // Try API key auth
    if mode == "key" || mode == "both" {
        if let Some(key) = extract_header(headers, "x-spf-key") {
            return key == api_key;
        }
    }

    // Try crypto auth
    if mode == "crypto" || mode == "both" {
        if let (Some(pub_hex), Some(sig_hex), Some(time_str), Some(nonce)) = (
            extract_header(headers, "x-spf-pub"),
            extract_header(headers, "x-spf-sig"),
            extract_header(headers, "x-spf-time"),
            extract_header(headers, "x-spf-nonce"),
        ) {
            return verify_crypto_auth(
                &pub_hex, &sig_hex, &time_str, &nonce,
                method_str, path, body,
                &state.trusted_keys, &state.nonce_cache,
            );
        }
    }

    // I-4 FIX: Try peer-derived key auth (mesh↔HTTP bridge)
    if mode == "both" || mode == "key" {
        if let Some(peer_key_header) = extract_header(headers, "x-spf-peer-key") {
            if let Some(peer_pub) = extract_header(headers, "x-spf-peer-pub") {
                // Verify the peer is trusted before attempting derivation
                if state.trusted_keys.contains(&peer_pub) {
                    let expected = crate::identity::derive_peer_api_key(
                        &state.signing_key, &peer_pub
                    );
                    if let Some(expected_key) = expected {
                        if peer_key_header == expected_key {
                            return true;
                        }
                    }
                }
            }
        }
    }

    false
}

/// Verify Ed25519 crypto authentication with replay prevention.
fn verify_crypto_auth(pub_hex: &str, sig_hex: &str, time_str: &str, nonce: &str,
                      method: &str, path: &str, body: &str,
                      trusted_keys: &HashSet<String>,
                      nonce_cache: &Mutex<HashMap<String, Instant>>) -> bool {
    // 1. Check public key is in trusted keys
    if !trusted_keys.contains(pub_hex) {
        return false;
    }

    // 2. Check timestamp within window
    let timestamp: u64 = match time_str.parse() {
        Ok(t) => t,
        Err(_) => return false,
    };
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    if now.abs_diff(timestamp) > TIMESTAMP_WINDOW_SECS {
        return false;
    }

    // 3. Check nonce uniqueness (and clean expired entries)
    {
        let mut cache = nonce_cache.lock().unwrap();
        let instant_now = Instant::now();
        cache.retain(|_, t| instant_now.duration_since(*t).as_secs() < NONCE_EXPIRY_SECS);
        if cache.contains_key(nonce) {
            return false; // replay detected
        }
        cache.insert(nonce.to_string(), instant_now);
    }

    // 4. Build canonical signing string
    let body_hash = hex::encode(Sha256::digest(body.as_bytes()));
    let canonical = format!("{}\n{}\n{}\n{}\n{}", method, path, body_hash, time_str, nonce);

    // 5. Decode public key
    let pub_bytes: [u8; 32] = match hex::decode(pub_hex) {
        Ok(b) if b.len() == 32 => match b.try_into() {
            Ok(arr) => arr,
            Err(_) => return false,
        },
        _ => return false,
    };
    let verifying_key = match VerifyingKey::from_bytes(&pub_bytes) {
        Ok(vk) => vk,
        Err(_) => return false,
    };

    // 6. Decode signature
    let sig_bytes: [u8; 64] = match hex::decode(sig_hex) {
        Ok(b) if b.len() == 64 => match b.try_into() {
            Ok(arr) => arr,
            Err(_) => return false,
        },
        _ => return false,
    };
    let signature = Signature::from_bytes(&sig_bytes);

    // 7. Verify signature over canonical string
    verifying_key.verify(canonical.as_bytes(), &signature).is_ok()
}

// ============================================================================
// RESPONSE HELPERS
// ============================================================================

/// Standard 401 response for failed auth
fn unauthorized() -> Response {
    (StatusCode::UNAUTHORIZED, Json(json!({
        "jsonrpc": "2.0",
        "id": null,
        "error": {"code": -32000, "message": "Unauthorized: invalid or missing authentication"}
    }))).into_response()
}

// ============================================================================
// JSON-RPC 2.0 HANDLER — shared by POST /mcp/v1 and WebSocket
// ============================================================================

/// Process a JSON-RPC 2.0 message. Returns (status_code, response_value).
/// Sync function — call from async via tokio::task::block_in_place().
fn handle_jsonrpc(body: &str, state: &Arc<ServerState>) -> (StatusCode, Value) {
    if body.is_empty() {
        return (StatusCode::BAD_REQUEST, json!({
            "jsonrpc": "2.0", "id": null,
            "error": {"code": -32700, "message": "Parse error: empty body"}
        }));
    }

    let msg: Value = match serde_json::from_str(body) {
        Ok(v) => v,
        Err(_) => {
            return (StatusCode::BAD_REQUEST, json!({
                "jsonrpc": "2.0", "id": null,
                "error": {"code": -32700, "message": "Parse error: invalid JSON"}
            }));
        }
    };

    let method = msg["method"].as_str().unwrap_or("");
    let id = &msg["id"];
    let params = &msg["params"];

    match method {
        "initialize" => {
            (StatusCode::OK, json!({
                "jsonrpc": "2.0",
                "id": id,
                "result": {
                    "protocolVersion": PROTOCOL_VERSION,
                    "capabilities": { "tools": {} },
                    "serverInfo": {
                        "name": "spf-smart-gate",
                        "version": env!("CARGO_PKG_VERSION"),
                    }
                }
            }))
        }

        "tools/list" => {
            (StatusCode::OK, json!({
                "jsonrpc": "2.0",
                "id": id,
                "result": { "tools": mcp::tool_definitions() }
            }))
        }

        "tools/call" => {
            let name = params["name"].as_str().unwrap_or("");
            let args = params.get("arguments").cloned().unwrap_or(json!({}));

            // Route through Unified Dispatch — same gate as stdio and mesh
            let resp = crate::dispatch::call(state, crate::dispatch::Source::Http, name, &args);
            (StatusCode::OK, json!({
                "jsonrpc": "2.0",
                "id": id,
                "result": { "content": [resp.result] }
            }))
        }

        "ping" => (StatusCode::OK, json!({"jsonrpc": "2.0", "id": id, "result": {}})),

        _ => (StatusCode::BAD_REQUEST, json!({
            "jsonrpc": "2.0",
            "id": id,
            "error": {"code": -32601, "message": format!("Unknown method: {}", method)}
        })),
    }
}

// ============================================================================
// CORS MIDDLEWARE — browser clients (ecommerce, web dashboards)
// ============================================================================

/// CORS middleware via axum::middleware::from_fn.
/// tower_http::CorsLayer requires ResBody: Default (same issue as TimeoutLayer),
/// so we handle CORS manually — zero body type constraints.
async fn cors_middleware(request: Request, next: middleware::Next) -> Response {
    // Preflight: browsers send OPTIONS before the real request
    if request.method() == Method::OPTIONS {
        return Response::builder()
            .status(StatusCode::OK)
            .header("access-control-allow-origin", "*")
            .header("access-control-allow-methods", "GET, POST, OPTIONS")
            .header("access-control-allow-headers",
                "content-type, authorization, x-spf-key, x-spf-sig, x-spf-pub, x-spf-time, x-spf-nonce")
            .header("access-control-max-age", "3600")
            .body(axum::body::Body::empty())
            .unwrap();
    }

    let mut response = next.run(request).await;
    let headers = response.headers_mut();
    headers.insert("access-control-allow-origin", "*".parse().unwrap());
    headers.insert("access-control-allow-methods", "GET, POST, OPTIONS".parse().unwrap());
    headers.insert("access-control-allow-headers",
        "content-type, authorization, x-spf-key, x-spf-sig, x-spf-pub, x-spf-time, x-spf-nonce".parse().unwrap());
    response
}

// ============================================================================
// ROUTE HANDLERS
// ============================================================================

/// GET /health — no auth required (health checks, load balancers)
async fn health_handler(State(app): State<AppState>) -> Response {
    let session = app.inner.session.lock().unwrap();
    let action_count = session.action_count;
    drop(session);

    Json(json!({
        "status": "ok",
        "version": env!("CARGO_PKG_VERSION"),
        "actions": action_count,
    })).into_response()
}

/// GET /status — requires auth
async fn status_handler(
    State(app): State<AppState>,
    headers: HeaderMap,
) -> Response {
    if !check_auth(&headers, "GET", "/status", "", &app.api_key, &app.inner) {
        return unauthorized();
    }

    let session = app.inner.session.lock().unwrap();
    let summary = session.status_summary();
    drop(session);

    Json(json!({
        "version": env!("CARGO_PKG_VERSION"),
        "mode": format!("{:?}", app.inner.config.enforce_mode),
        "session": summary,
    })).into_response()
}

/// GET /tools — requires auth
async fn tools_handler(
    State(app): State<AppState>,
    headers: HeaderMap,
) -> Response {
    if !check_auth(&headers, "GET", "/tools", "", &app.api_key, &app.inner) {
        return unauthorized();
    }

    Json(json!({
        "tools": mcp::tool_definitions()
    })).into_response()
}

/// POST /mcp/v1 — JSON-RPC 2.0 protocol handler, requires auth.
/// Body extracted as String for crypto auth signature verification.
/// 30s timeout via spawn_blocking + tokio::time::timeout.
async fn mcp_handler(
    State(app): State<AppState>,
    headers: HeaderMap,
    body: String,
) -> Response {
    if !check_auth(&headers, "POST", "/mcp/v1", &body, &app.api_key, &app.inner) {
        return unauthorized();
    }

    let state = app.inner.clone();
    let result = tokio::time::timeout(
        Duration::from_secs(30),
        tokio::task::spawn_blocking(move || handle_jsonrpc(&body, &state)),
    ).await;

    match result {
        Ok(Ok((status, json))) => (status, Json(json)).into_response(),
        Ok(Err(_)) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({
            "jsonrpc": "2.0", "id": null,
            "error": {"code": -32603, "message": "Internal error"}
        }))).into_response(),
        Err(_) => (StatusCode::REQUEST_TIMEOUT, Json(json!({
            "jsonrpc": "2.0", "id": null,
            "error": {"code": -32000, "message": "Request timeout (30s)"}
        }))).into_response(),
    }
}

// ============================================================================
// WEBSOCKET — persistent JSON-RPC connection (E5)
// ============================================================================

/// GET /ws — WebSocket upgrade, requires auth on the HTTP upgrade request.
/// Once upgraded, the connection is authenticated for its lifetime.
async fn ws_handler(
    State(app): State<AppState>,
    headers: HeaderMap,
    ws: WebSocketUpgrade,
) -> Response {
    if !check_auth(&headers, "GET", "/ws", "", &app.api_key, &app.inner) {
        return unauthorized();
    }

    let state = app.inner.clone();
    ws.on_upgrade(move |socket| handle_ws(socket, state))
}

/// WebSocket message loop — each text message is a JSON-RPC request.
/// Same dispatch path as POST /mcp/v1 but persistent connection.
async fn handle_ws(mut socket: WebSocket, state: Arc<ServerState>) {
    eprintln!("[SPF-WS] Client connected");

    while let Some(Ok(msg)) = socket.recv().await {
        match msg {
            Message::Text(text) => {
                let state_ref = state.clone();
                let result = tokio::time::timeout(
                    Duration::from_secs(30),
                    tokio::task::spawn_blocking(move || handle_jsonrpc(&text, &state_ref)),
                ).await;

                let resp_json = match result {
                    Ok(Ok((_, json))) => json,
                    Ok(Err(_)) => json!({"jsonrpc": "2.0", "id": null,
                        "error": {"code": -32603, "message": "Internal error"}}),
                    Err(_) => json!({"jsonrpc": "2.0", "id": null,
                        "error": {"code": -32000, "message": "Request timeout (30s)"}}),
                };
                let resp = serde_json::to_string(&resp_json).unwrap_or_default();
                if socket.send(Message::Text(resp.into())).await.is_err() {
                    break;
                }
            }
            Message::Ping(data) => {
                if socket.send(Message::Pong(data)).await.is_err() {
                    break;
                }
            }
            Message::Close(_) => break,
            _ => {}
        }
    }

    eprintln!("[SPF-WS] Client disconnected");
}

// ============================================================================
// HTTP SERVER
// ============================================================================

/// Scan for an available port starting at preferred.
/// Tries preferred..=preferred+1000. Returns first port that binds.
/// Logs if non-preferred port selected.
fn find_available_port(bind: &str, preferred: u16) -> u16 {
    let range_end = preferred.saturating_add(1000);
    for port in preferred..=range_end {
        let addr = format!("{}:{}", bind, port);
        match std::net::TcpListener::bind(&addr) {
            Ok(listener) => {
                drop(listener);
                if port != preferred {
                    eprintln!(
                        "[SPF] Port {} in use — auto-selected port {}",
                        preferred, port
                    );
                }
                return port;
            }
            Err(_) => continue,
        }
    }
    eprintln!(
        "[SPF] WARNING: No port available in {}..={}, falling back to {}",
        preferred, range_end, preferred
    );
    preferred
}

// ============================================================================
// WB-2d: REVERSE PROXY HANDLERS — /proxy, /proxy/asset, /ws/browser
// No auth: served to local browser (localhost only, no external exposure).
// ============================================================================

/// GET /proxy?url=... — Fetch target URL, inject CONTROL_JS, serve to browser.
async fn proxy_handler(
    State(app): State<AppState>,
    Query(params): Query<HashMap<String, String>>,
) -> Response {
    let url = match params.get("url") {
        Some(u) if !u.is_empty() => u.clone(),
        _ => return (StatusCode::BAD_REQUEST, "Missing url parameter").into_response(),
    };
    if let Err(e) = crate::web::validate_url(&url) {
        return (StatusCode::BAD_REQUEST, e).into_response();
    }
    let ws_port = app.inner.http_port;
    let state = app.inner.clone();
    match tokio::task::spawn_blocking(move || {
        state.browser.lock().unwrap().proxy_page(&url, ws_port)
    }).await {
        Ok(Ok(page)) => Response::builder()
            .header(header::CONTENT_TYPE, "text/html; charset=utf-8")
            .body(Body::from(page.html))
            .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response()),
        Ok(Err(e)) => (StatusCode::BAD_GATEWAY, format!("Proxy error: {}", e)).into_response(),
        Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
    }
}

/// GET /proxy/asset?url=... — Fetch and passthrough a page asset (CSS/JS/image).
async fn proxy_asset_handler(
    State(app): State<AppState>,
    Query(params): Query<HashMap<String, String>>,
) -> Response {
    let url = match params.get("url") {
        Some(u) if !u.is_empty() => u.clone(),
        _ => return (StatusCode::BAD_REQUEST, "Missing url parameter").into_response(),
    };
    if let Err(e) = crate::web::validate_url(&url) {
        return (StatusCode::BAD_REQUEST, e).into_response();
    }
    let state = app.inner.clone();
    match tokio::task::spawn_blocking(move || {
        state.browser.lock().unwrap().proxy_asset(&url)
    }).await {
        Ok(Ok(asset)) => Response::builder()
            .header(header::CONTENT_TYPE, asset.content_type)
            .body(Body::from(asset.data))
            .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response()),
        Ok(Err(e)) => (StatusCode::BAD_GATEWAY, format!("Asset error: {}", e)).into_response(),
        Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
    }
}

/// GET /ws/browser — WebSocket endpoint for browser control JS.
/// Bridges std::sync::mpsc channels (BrowserSession) ↔ WebSocket (browser JS).
async fn ws_browser_handler(
    ws: WebSocketUpgrade,
    State(app): State<AppState>,
) -> impl IntoResponse {
    ws.on_upgrade(move |socket| async move {
        // Take channels — only one WS browser session at a time
        let channels = app.inner.ws_browser_channels.lock()
            .ok()
            .and_then(|mut g| g.take());
        if let Some(channels) = channels {
            handle_browser_ws(socket, channels).await;
        }
        // No channels = no active session, close immediately
    })
}

/// Bridge mpsc channels to WebSocket — command relay between BrowserSession and browser JS.
async fn handle_browser_ws(
    mut socket: WebSocket,
    channels: crate::browser::WsBrowserChannels,
) {
    loop {
        // Forward any pending commands from BrowserSession → browser JS
        while let Ok(cmd) = channels.cmd_rx.try_recv() {
            if socket.send(Message::Text(cmd.into())).await.is_err() {
                return;
            }
        }
        // Wait up to 50ms for a message from browser JS (polling rate)
        match tokio::time::timeout(
            std::time::Duration::from_millis(50),
            socket.recv(),
        ).await {
            Ok(Some(Ok(Message::Text(text)))) => {
                if channels.resp_tx.send(text.to_string()).is_err() {
                    return; // BrowserSession dropped — session over
                }
            }
            Ok(Some(Ok(Message::Close(_)))) | Ok(Some(Err(_))) | Ok(None) => return,
            _ => {} // Binary/ping/pong/timeout — continue polling
        }
    }
}

// ============================================================================
// CH-2 + CH-3: CHANNEL HUB — WebSocket + HTTP API routes
// ============================================================================

/// GET /ws/channel/:id — WebSocket upgrade for channel communication.
/// Auth required on upgrade. Peer identified by X-SPF-Pub header (or query param fallback).
/// Once upgraded, the connection is a full-duplex push channel.
async fn ws_channel_handler(
    State(app): State<AppState>,
    Path(channel_id): Path<String>,
    headers: HeaderMap,
    Query(params): Query<HashMap<String, String>>,
    ws: WebSocketUpgrade,
) -> Response {
    if !check_auth(&headers, "GET", &format!("/ws/channel/{}", channel_id), "", &app.api_key, &app.inner) {
        return unauthorized();
    }

    // Identify the connecting agent — prefer header, fallback to query param
    let peer_key = extract_header(&headers, "x-spf-pub")
        .or_else(|| params.get("key").cloned())
        .unwrap_or_else(|| "anonymous".to_string());
    let peer_name = extract_header(&headers, "x-spf-name")
        .or_else(|| params.get("name").cloned())
        .unwrap_or_else(|| peer_key[..8.min(peer_key.len())].to_string());

    ws.on_upgrade(move |socket| {
        crate::channel::handle_channel_ws(socket, channel_id, peer_key, peer_name)
    })
}

/// POST /api/channel/create — Create a new channel.
/// Body: { "name": "ops", "key": "abc...", "display_name": "ALPHA" }
async fn api_channel_create(
    State(app): State<AppState>,
    headers: HeaderMap,
    Json(body): Json<Value>,
) -> Response {
    if !check_auth(&headers, "POST", "/api/channel/create", "", &app.api_key, &app.inner) {
        return unauthorized();
    }
    let name = body["name"].as_str().unwrap_or("unnamed");
    let key = body["key"].as_str().unwrap_or(&app.inner.pub_key_hex);
    let display_name = body["display_name"].as_str().unwrap_or("Agent");
    Json(crate::channel::api_create_channel(name, key, display_name)).into_response()
}

/// POST /api/channel/join — Join an existing channel.
/// Body: { "channel_id": "ch-1", "key": "abc...", "name": "BRAVO" }
async fn api_channel_join(
    State(app): State<AppState>,
    headers: HeaderMap,
    Json(body): Json<Value>,
) -> Response {
    if !check_auth(&headers, "POST", "/api/channel/join", "", &app.api_key, &app.inner) {
        return unauthorized();
    }
    let channel_id = body["channel_id"].as_str().unwrap_or("");
    let key = body["key"].as_str().unwrap_or(&app.inner.pub_key_hex);
    let name = body["name"].as_str().unwrap_or("Agent");
    Json(crate::channel::api_join_channel(channel_id, key, name)).into_response()
}

/// POST /api/channel/leave — Leave a channel.
/// Body: { "channel_id": "ch-1", "key": "abc..." }
async fn api_channel_leave(
    State(app): State<AppState>,
    headers: HeaderMap,
    Json(body): Json<Value>,
) -> Response {
    if !check_auth(&headers, "POST", "/api/channel/leave", "", &app.api_key, &app.inner) {
        return unauthorized();
    }
    let channel_id = body["channel_id"].as_str().unwrap_or("");
    let key = body["key"].as_str().unwrap_or(&app.inner.pub_key_hex);
    Json(crate::channel::api_leave_channel(channel_id, key)).into_response()
}

/// POST /api/channel/send — Send a message to a channel.
/// Body: { "channel_id": "ch-1", "key": "abc...", "name": "ALPHA", "text": "hello", "msg_type": "text" }
async fn api_channel_send(
    State(app): State<AppState>,
    headers: HeaderMap,
    Json(body): Json<Value>,
) -> Response {
    if !check_auth(&headers, "POST", "/api/channel/send", "", &app.api_key, &app.inner) {
        return unauthorized();
    }
    let channel_id = body["channel_id"].as_str().unwrap_or("");
    let key = body["key"].as_str().unwrap_or(&app.inner.pub_key_hex);
    let name = body["name"].as_str().unwrap_or("Agent");
    let text = body["text"].as_str().unwrap_or("");
    let msg_type = match body["msg_type"].as_str() {
        Some("tool_result") => crate::channel::MessageType::ToolResult,
        Some("system") => crate::channel::MessageType::System,
        _ => crate::channel::MessageType::Text,
    };
    Json(crate::channel::api_send_message(channel_id, key, name, text, msg_type)).into_response()
}

/// GET /api/channel/list — List all channels.
async fn api_channel_list(
    State(app): State<AppState>,
    headers: HeaderMap,
) -> Response {
    if !check_auth(&headers, "GET", "/api/channel/list", "", &app.api_key, &app.inner) {
        return unauthorized();
    }
    Json(crate::channel::api_list_channels()).into_response()
}

/// GET /api/channel/:id/history — Get message history for a channel.
async fn api_channel_history(
    State(app): State<AppState>,
    Path(channel_id): Path<String>,
    headers: HeaderMap,
    Query(params): Query<HashMap<String, String>>,
) -> Response {
    if !check_auth(&headers, "GET", &format!("/api/channel/{}/history", channel_id), "", &app.api_key, &app.inner) {
        return unauthorized();
    }
    let limit: usize = params.get("limit")
        .and_then(|l| l.parse().ok())
        .unwrap_or(50);
    Json(crate::channel::api_channel_history(&channel_id, limit)).into_response()
}

/// Build the Axum Router with all routes and middleware.
fn build_router(app_state: AppState) -> Router {
    // Tower middleware stack — applied to ALL routes
    // TimeoutLayer removed: requires ResBody: Default which axum::body::Body doesn't impl.
    // Timeout protection provided by tokio task isolation + SPF gate rate limiting.
    // CompressionLayer applied on Router (outside stack) to avoid body type conflicts.
    let middleware_stack = ServiceBuilder::new()
        // 1. Structured request/response tracing (outermost)
        .layer(TraceLayer::new_for_http())
        // 2. Hide auth headers from trace output
        .layer(SetSensitiveRequestHeadersLayer::new([
            HeaderName::from_static("x-spf-key"),
            HeaderName::from_static("x-spf-sig"),
        ]))
        // 3. 10MB body limit (matches original read_body limit)
        .layer(RequestBodyLimitLayer::new(10 * 1024 * 1024))
        // 4. Convert handler panics to 500 (innermost — uses ResponseForPanic, not Default)
        .layer(CatchPanicLayer::new());

    Router::new()
        // Public routes — no auth
        .route("/health", get(health_handler))
        // Protected routes — auth checked in each handler
        .route("/status", get(status_handler))
        .route("/tools", get(tools_handler))
        .route("/mcp/v1", post(mcp_handler))
        // WebSocket — auth on upgrade request
        .route("/ws", get(ws_handler))
        // Reverse proxy browser routes (WB-2d) — no auth, served to local browser
        .route("/proxy", get(proxy_handler))
        .route("/proxy/asset", get(proxy_asset_handler))
        .route("/ws/browser", get(ws_browser_handler))
        // CH-2: Channel WebSocket — full duplex agent communication
        .route("/ws/channel/{id}", get(ws_channel_handler))
        // CH-3: Channel HTTP API — control plane for channel management
        .route("/api/channel/create", post(api_channel_create))
        .route("/api/channel/join", post(api_channel_join))
        .route("/api/channel/leave", post(api_channel_leave))
        .route("/api/channel/send", post(api_channel_send))
        .route("/api/channel/list", get(api_channel_list))
        .route("/api/channel/{id}/history", get(api_channel_history))
        // CORS — browser clients (ecommerce, web dashboards)
        .layer(middleware::from_fn(cors_middleware))
        // Compression outside CatchPanic (CompressionBody doesn't impl Default)
        .layer(CompressionLayer::new())
        // Global middleware (all routes)
        .layer(middleware_stack)
        .with_state(app_state)
}

/// Async HTTP server — runs in caller's tokio runtime.
/// Use this for shared runtime (E7) where mcp.rs spawns HTTP + mesh together.
/// Blocks until server stops or task is cancelled.
///
/// BLOCK SEC-4: SPF_API_KEY env var checked first — process-scoped override.
/// Priority: SPF_API_KEY env > identity-derived key > JSON config fallback.
/// The env var is never written to disk, so AI agents with native Read
/// cannot discover it from config files.
pub async fn serve(
    state: Arc<ServerState>,
    bind: String,
    port: u16,
    api_key: String,
    tls: Option<(Vec<u8>, Vec<u8>)>,
) {
    rustls::crypto::ring::default_provider().install_default().ok();

    // SEC-4: Environment variable override for API key.
    // SPF_API_KEY env var takes priority over identity-derived key.
    // Process-scoped: not readable from JSON config files by AI agents.
    let api_key = match std::env::var("SPF_API_KEY") {
        Ok(env_key) if !env_key.is_empty() => {
            eprintln!("[SPF-HTTP] API key loaded from SPF_API_KEY env var");
            env_key
        }
        _ => api_key, // Fall back to identity-derived key (passed from mcp.rs)
    };

    let port = find_available_port(&bind, port);
    let addr = format!("{}:{}", bind, port);

    let app_state = AppState {
        inner: state,
        api_key,
    };

    let app = build_router(app_state);

    eprintln!("[SPF-HTTP] Listening on {}", addr);

    if let Some((cert_pem, key_pem)) = tls {
        // HTTPS via axum-server + rustls — PEM bytes from rcgen
        let tls_config = axum_server::tls_rustls::RustlsConfig::from_pem(cert_pem, key_pem)
            .await
            .expect("[SPF-HTTP] Failed to load TLS config from PEM");

        let sock_addr: std::net::SocketAddr = addr.parse()
            .expect("[SPF-HTTP] Invalid bind address");

        // Graceful shutdown handle (E6)
        let handle = axum_server::Handle::new();
        let shutdown_handle = handle.clone();
        tokio::spawn(async move {
            tokio::signal::ctrl_c().await.ok();
            eprintln!("[SPF-HTTP] Graceful shutdown initiated (10s timeout)...");
            shutdown_handle.graceful_shutdown(Some(Duration::from_secs(10)));
        });

        axum_server::bind_rustls(sock_addr, tls_config)
            .handle(handle)
            .serve(app.into_make_service())
            .await
            .expect("[SPF-HTTP] HTTPS server failed");
    } else {
        // Plain HTTP via axum::serve
        let listener = tokio::net::TcpListener::bind(&addr)
            .await
            .expect("[SPF-HTTP] Failed to bind TCP");

        // Graceful shutdown (E6)
        axum::serve(listener, app)
            .with_graceful_shutdown(async {
                tokio::signal::ctrl_c().await.ok();
                eprintln!("[SPF-HTTP] Graceful shutdown initiated...");
            })
            .await
            .expect("[SPF-HTTP] HTTP server failed");
    }
}

/// Start HTTP API server — sync wrapper for backward compatibility.
/// Called from spawned thread in mcp::run(). Creates own tokio runtime.
/// Blocks forever (runs in dedicated thread).
///
/// Signature unchanged from tiny_http version — mcp.rs needs zero changes
/// when using this entry point. For shared runtime (E7), use serve() instead.
pub fn start(state: Arc<ServerState>, bind: &str, port: u16, api_key: String, tls: Option<(Vec<u8>, Vec<u8>)>) {
    let bind = bind.to_string();
    let rt = tokio::runtime::Builder::new_multi_thread()
        .worker_threads(2)
        .enable_all()
        .build()
        .expect("[SPF-HTTP] Failed to build tokio runtime");

    rt.block_on(serve(state, bind, port, api_key, tls));
}