use crate::app::AppState;
use crate::context::RequestContext;
use crate::error::WebError;
use axum::body::Body;
use axum::extract::{Extension, State};
use axum::http::{Request, StatusCode};
use axum::response::Response;
use serde_json::Value;

pub async fn next_ai_agent_run(
    State(_state): State<AppState>,
    Extension(context): Extension<RequestContext>,
    request: Request<Body>,
) -> Result<Response, WebError> {
    let (_parts, body) = request.into_parts();
    let body = axum::body::to_bytes(body, 10 * 1024 * 1024)
        .await
        .map_err(|error| WebError::internal(format!("读取 AI 请求体失败: {error}")))?;
    let payload: Value = serde_json::from_slice(&body).map_err(|error| {
        WebError::bad_request_code(
            "ai_agent_bad_request",
            format!("AI 请求体不是合法 JSON: {error}"),
        )
        .with_context(&context)
        .with_header("x-mnote-web-owner", "mnote-web")
    })?;

    let provider = explicit_agent_provider(&payload).unwrap_or("legacy");
    Err(WebError::new(
        StatusCode::GONE,
        "legacy_ai_agent_run_retired",
        format!(
            "旧 /api/ai-agent/run 页面 AI 主链已退场，provider={provider} 不再静默降级；请使用 Hermes client proxy 与 mnote Hermes plugin。"
        ),
    )
    .with_context(&context)
    .with_header("x-mnote-web-owner", "mnote-web")
    .with_header("x-mnote-ai-execution-owner", "legacy-ai-agent-run-retired"))
}

fn explicit_agent_provider(payload: &Value) -> Option<&'static str> {
    let provider = payload
        .get("options")
        .and_then(|value| value.get("ai"))
        .and_then(|value| value.get("provider"))
        .and_then(Value::as_str)?
        .trim()
        .to_ascii_lowercase();
    match provider.as_str() {
        "hermes" => Some("hermes"),
        "codex" => Some("codex"),
        "claudecode" => Some("claudecode"),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use crate::app::{build_app, AppConfig, AppState};
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use axum::response::IntoResponse;
    use tokio::net::TcpListener;
    use tower::util::ServiceExt;

    fn app() -> axum::Router {
        build_app(AppState::new(AppConfig {
            service_name: "mnote-web".into(),
            service_version: "0.1.0".into(),
            bind_addr: "127.0.0.1:0".into(),
            public_bind_addr: "127.0.0.1:3000".into(),
            legacy_next_base_url: Some("http://127.0.0.1:3100".into()),
            enable_legacy_next_compat: true,
            enable_debug_shell_routes: false,
            hermes_base_path: "/api/hermes".into(),
            compat_next_base_path: "/api/compat/next".into(),
            convex_url: None,
            convex_admin_key: None,
            allow_dev_fixtures: true,
            query_fixtures_json: Some(r#"{"sidebar:datasetList":{"active_workspace_id":"ws_demo","workspaces":[],"documents":[{"id":"page_root","workspace_id":"ws_demo","title":"工作区首页","parent_id":null,"sort_order":0,"is_starred":true,"is_template":false,"created_at":"2026-04-16T00:00:00Z","updated_at":"2026-04-16T00:00:00Z"},{"id":"page_child","workspace_id":"ws_demo","title":"子页面","parent_id":"page_root","sort_order":1,"is_starred":false,"is_template":false,"created_at":"2026-04-16T00:00:00Z","updated_at":"2026-04-16T00:00:00Z"}],"trashed_documents":[],"media_assets":[],"trashed_media_assets":[],"mindmap_assets":[],"trashed_mindmap_assets":[],"table_assets":[],"trashed_table_assets":[],"mindmap_docs":[],"mindmap_asset_children":{}},"bridgeLogs:listWorkspaceOverview":{"workspace_id":"ws_demo","command_logs":[],"domain_events":[],"next_cursor":null,"has_more":false,"filters":{"command_status":null,"event_status":null,"target_page_id":null,"target_block_id":null,"aggregate_type":null,"aggregate_id":null},"generated_at":"2026-04-16T00:00:00Z"}}"#.into()),
            mutation_fixtures_json: None,
            dev_user_id: "dev-user".into(),
            dev_user_name: "开发用户".into(),
            dev_user_email: "dev@mnote.local".into(),
        }))
    }

    #[tokio::test]
    async fn compat_next_sidebar_route_is_not_registered_by_default() {
        let response = app()
            .oneshot(
                Request::builder()
                    .uri("/api/compat/next/sidebar?workspaceId=ws_demo")
                    .body(Body::empty())
                    .expect("request"),
            )
            .await
            .expect("response");

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn direct_ai_agent_run_returns_legacy_retired_guard() {
        let response = build_app(AppState::new(AppConfig {
            service_name: "mnote-web".into(),
            service_version: "0.1.0".into(),
            bind_addr: "127.0.0.1:0".into(),
            public_bind_addr: "127.0.0.1:3000".into(),
            legacy_next_base_url: Some("http://127.0.0.1:3100".into()),
            enable_legacy_next_compat: false,
            enable_debug_shell_routes: false,
            hermes_base_path: "/api/hermes".into(),
            compat_next_base_path: "/api/compat/next".into(),
            convex_url: None,
            convex_admin_key: None,
            allow_dev_fixtures: true,
            query_fixtures_json: None,
            mutation_fixtures_json: None,
            dev_user_id: "dev-user".into(),
            dev_user_name: "开发用户".into(),
            dev_user_email: "dev@mnote.local".into(),
        }))
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/ai-agent/run")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"stream":true,"scope":"document","messages":[{"role":"user","content":"ping"}],"context":{"documentId":"doc-1"},"options":{"ai":{"provider":"online"}}}"#))
                .expect("request"),
        )
        .await
        .expect("response");

        assert_eq!(response.status(), StatusCode::GONE);
        assert_eq!(
            response
                .headers()
                .get("x-mnote-web-owner")
                .and_then(|value| value.to_str().ok()),
            Some("mnote-web")
        );
        assert_eq!(
            response
                .headers()
                .get("x-mnote-ai-execution-owner")
                .and_then(|value| value.to_str().ok()),
            Some("legacy-ai-agent-run-retired")
        );
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body");
        let text = String::from_utf8(body.to_vec()).expect("utf8");
        assert!(text.contains("legacy_ai_agent_run_retired"));
        assert!(text.contains("Hermes client proxy"));
    }

    #[tokio::test]
    async fn explicit_agent_provider_returns_legacy_retired_guard() {
        let response = build_app(AppState::new(AppConfig {
            service_name: "mnote-web".into(),
            service_version: "0.1.0".into(),
            bind_addr: "127.0.0.1:0".into(),
            public_bind_addr: "127.0.0.1:3000".into(),
            legacy_next_base_url: Some("http://127.0.0.1:9".into()),
            enable_legacy_next_compat: false,
            enable_debug_shell_routes: false,
            hermes_base_path: "/api/hermes".into(),
            compat_next_base_path: "/api/compat/next".into(),
            convex_url: None,
            convex_admin_key: None,
            allow_dev_fixtures: true,
            query_fixtures_json: None,
            mutation_fixtures_json: None,
            dev_user_id: "dev-user".into(),
            dev_user_name: "开发用户".into(),
            dev_user_email: "dev@mnote.local".into(),
        }))
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/ai-agent/run")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"stream":true,"scope":"document","messages":[{"role":"user","content":"ping"}],"context":{"documentId":"doc-1"},"options":{"ai":{"provider":"codex"}}}"#))
                .expect("request"),
        )
        .await
        .expect("response");

        assert_eq!(response.status(), StatusCode::GONE);
        assert_eq!(
            response
                .headers()
                .get("x-mnote-ai-execution-owner")
                .and_then(|value| value.to_str().ok()),
            Some("legacy-ai-agent-run-retired")
        );
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body");
        let text = String::from_utf8(body.to_vec()).expect("utf8");
        assert!(text.contains("codex"));
        assert!(text.contains("legacy_ai_agent_run_retired"));
    }

    #[tokio::test]
    async fn explicit_hermes_provider_fails_instead_of_using_legacy_next_or_direct_bridge() {
        let next_app = axum::Router::new().route(
            "/api/ai-agent/run",
            axum::routing::post(|| async move {
                (
                    [(
                        axum::http::header::CONTENT_TYPE,
                        "text/event-stream; charset=utf-8",
                    )],
                    "event: assistant_message\ndata: {\"text\":\"hello from next ai\"}\n\n",
                )
                    .into_response()
            }),
        );
        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind next");
        let addr = listener.local_addr().expect("local addr");
        let server = tokio::spawn(async move {
            axum::serve(listener, next_app).await.expect("serve next");
        });

        let response = build_app(AppState::new(AppConfig {
            service_name: "mnote-web".into(),
            service_version: "0.1.0".into(),
            bind_addr: "127.0.0.1:0".into(),
            public_bind_addr: "127.0.0.1:3000".into(),
            legacy_next_base_url: Some(format!("http://{}", addr)),
            enable_legacy_next_compat: true,
            enable_debug_shell_routes: false,
            hermes_base_path: "/api/hermes".into(),
            compat_next_base_path: "/api/compat/next".into(),
            convex_url: None,
            convex_admin_key: None,
            allow_dev_fixtures: true,
            query_fixtures_json: None,
            mutation_fixtures_json: None,
            dev_user_id: "dev-user".into(),
            dev_user_name: "开发用户".into(),
            dev_user_email: "dev@mnote.local".into(),
        }))
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/ai-agent/run")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"stream":true,"scope":"document","messages":[{"role":"user","content":"ping"}],"context":{"documentId":"doc-1"},"options":{"ai":{"provider":"hermes"}}}"#))
                .expect("request"),
        )
        .await
        .expect("response");

        assert_eq!(response.status(), StatusCode::GONE);
        assert_eq!(
            response
                .headers()
                .get("x-mnote-ai-execution-owner")
                .and_then(|value| value.to_str().ok()),
            Some("legacy-ai-agent-run-retired")
        );
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body");
        let text = String::from_utf8(body.to_vec()).expect("utf8");
        assert!(text.contains("hermes"));
        assert!(!text.contains("hello from next ai"));

        server.abort();
    }
}
