use crate::app::AppState;
use crate::context::RequestContext;
use crate::error::WebError;
use crate::routes::query_support::resolve_effective_workspace_id;
use crate::routes::snapshot_support::{load_projection_snapshot, ProjectionSnapshotSpec};
use axum::extract::Query;
use axum::extract::{Extension, State};
use axum::http::StatusCode;
use axum::Json;
use core_protocol::KernelProjectionKind;
use serde::Deserialize;
use serde::Serialize;
use serde_json::{json, Value};

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CompatBoundaryResponse {
    pub ok: bool,
    pub boundary: &'static str,
    pub compatibility: &'static str,
    pub request_id: String,
    pub trace_id: String,
    pub target: String,
    pub notes: Vec<&'static str>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CompatSidebarQuery {
    pub workspace_id: Option<String>,
}

pub async fn next_ai_agent_run(
    State(state): State<AppState>,
    Extension(context): Extension<RequestContext>,
) -> Json<CompatBoundaryResponse> {
    Json(CompatBoundaryResponse {
        ok: true,
        boundary: "next_route_compat",
        compatibility: "placeholder",
        request_id: context.trace.request_id,
        trace_id: context.trace.trace_id,
        target: format!("{}/bridge", state.config().hermes_base_path),
        notes: vec![
            "当前保留 Next route 兼容边界，后续用于把 /api/ai-agent/run 收口到 Rust Web 层。",
            "此占位实现不复制业务裁决，只声明桥接目标与迁移方向。",
        ],
    })
}

pub async fn next_sidebar(
    State(state): State<AppState>,
    Extension(context): Extension<RequestContext>,
    Query(query): Query<CompatSidebarQuery>,
) -> Result<(StatusCode, Json<Value>), WebError> {
    let effective_workspace_id =
        resolve_effective_workspace_id(&context, query.workspace_id.as_deref(), true)?
            .expect("workspace_required 已确保存在");

    let snapshot = load_projection_snapshot(
        state.config(),
        &context,
        &ProjectionSnapshotSpec {
            workspace_id: &effective_workspace_id,
            root_node_id: None,
            depth: None,
            projection: KernelProjectionKind::SidebarTree,
        },
    )
    .await?;

    let mut dataset_object = snapshot.dataset.as_object().cloned().ok_or_else(|| {
        WebError::bad_gateway_code("convex_bad_response", "sidebar.dataset.list 返回值不是对象")
            .with_context(&context)
            .with_header("x-error-phase", "compat_sidebar_shape")
            .with_header("x-upstream-service", "convex")
    })?;
    dataset_object.insert("kernel_sidebar_projection".into(), snapshot.projection);

    Ok((
        StatusCode::OK,
        Json(json!({
            "ok": true,
            "boundary": "next_sidebar_compat",
            "requestId": context.trace.request_id,
            "traceId": context.trace.trace_id,
            "workspaceId": effective_workspace_id,
            "result": Value::Object(dataset_object),
        })),
    ))
}

#[cfg(test)]
mod tests {
    use crate::app::{build_app, AppConfig, AppState};
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    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(),
            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_sidebar_route_returns_dataset_and_projection() {
        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::OK);
    }
}
