use arc_swap::ArcSwap;
use axum::body::Bytes;
use crate::proxy::{RewriteConfig, sse::split_upstream};
#[must_use]
pub fn rewrite_passthrough_urls(config: &ArcSwap<RewriteConfig>, body: Bytes) -> Bytes {
let cfg = config.load();
let (upstream_base, _) = split_upstream(&cfg.mcp_upstream);
let upstream_base = upstream_base.trim_end_matches('/');
let proxy_url = cfg.proxy_url.trim_end_matches('/');
if !contains_slice(&body, upstream_base.as_bytes()) {
return body;
}
let body_str = String::from_utf8_lossy(&body);
Bytes::from(body_str.replace(upstream_base, proxy_url).into_bytes())
}
fn contains_slice(haystack: &[u8], needle: &[u8]) -> bool {
if needle.is_empty() || haystack.len() < needle.len() {
return needle.is_empty();
}
haystack.windows(needle.len()).any(|win| win == needle)
}