use crate::product::app_server_protocol::JSONRPCResponse;
use crate::product::app_server_protocol::RequestId;
use crate::product::app_server_protocol::ServerRequest;
use crate::product::app_server_protocol::ThreadStartParams;
use crate::product::app_server_protocol::ThreadStartResponse;
use crate::product::app_server_protocol::TurnStartParams;
use crate::product::app_server_protocol::TurnStartResponse;
use crate::product::app_server_protocol::UserInput as V2UserInput;
use crate::product::protocol::config_types::Identity;
use crate::product::protocol::config_types::IdentityKind;
use crate::product::protocol::config_types::Settings;
use crate::product::protocol::openai_models::ReasoningEffort;
use crate::test_support::app_server::McpProcess;
use crate::test_support::app_server::create_final_assistant_message_sse_response;
use crate::test_support::app_server::create_mock_responses_server_sequence;
use crate::test_support::app_server::create_request_user_input_sse_response;
use crate::test_support::app_server::to_response;
use anyhow::Result;
use tokio::time::timeout;

const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn request_user_input_round_trip() -> Result<()> {
    let lha_home = tempfile::TempDir::new()?;
    let responses = vec![
        create_request_user_input_sse_response("call1")?,
        create_final_assistant_message_sse_response("done")?,
    ];
    let server = create_mock_responses_server_sequence(responses).await;
    create_config_toml(lha_home.path(), &server.uri())?;

    let mut mcp = McpProcess::new(lha_home.path()).await?;
    timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;

    let thread_start_id = mcp
        .send_thread_start_request(ThreadStartParams {
            model: Some("mock-model".to_string()),
            ..Default::default()
        })
        .await?;
    let thread_start_resp: JSONRPCResponse = timeout(
        DEFAULT_READ_TIMEOUT,
        mcp.read_stream_until_response_message(RequestId::Integer(thread_start_id)),
    )
    .await??;
    let ThreadStartResponse { thread, .. } = to_response(thread_start_resp)?;

    let turn_start_id = mcp
        .send_turn_start_request(TurnStartParams {
            thread_id: thread.id.clone(),
            input: vec![V2UserInput::Text {
                text: "ask something".to_string(),
                text_elements: Vec::new(),
            }],
            model: Some("mock-model".to_string()),
            effort: Some(ReasoningEffort::Medium),
            identity: Some(Identity {
                kind: IdentityKind::Planner,
                settings: Settings {
                    model: "mock-model".to_string(),
                    reasoning_effort: Some(ReasoningEffort::Medium),
                    developer_instructions: None,
                },
            }),
            ..Default::default()
        })
        .await?;
    let turn_start_resp: JSONRPCResponse = timeout(
        DEFAULT_READ_TIMEOUT,
        mcp.read_stream_until_response_message(RequestId::Integer(turn_start_id)),
    )
    .await??;
    let TurnStartResponse { turn, .. } = to_response(turn_start_resp)?;

    let server_req = timeout(
        DEFAULT_READ_TIMEOUT,
        mcp.read_stream_until_request_message(),
    )
    .await??;
    let ServerRequest::ToolRequestUserInput { request_id, params } = server_req else {
        panic!("expected ToolRequestUserInput request, got: {server_req:?}");
    };

    assert_eq!(params.thread_id, thread.id);
    assert_eq!(params.turn_id, turn.id);
    assert_eq!(params.item_id, "call1");
    assert_eq!(params.questions.len(), 1);

    mcp.send_response(
        request_id,
        serde_json::json!({
            "answers": {
                "confirm_path": { "answers": ["yes"] }
            }
        }),
    )
    .await?;

    timeout(
        DEFAULT_READ_TIMEOUT,
        mcp.read_stream_until_notification_message("lha/event/task_complete"),
    )
    .await??;
    timeout(
        DEFAULT_READ_TIMEOUT,
        mcp.read_stream_until_notification_message("turn/completed"),
    )
    .await??;

    Ok(())
}

fn create_config_toml(lha_home: &std::path::Path, server_uri: &str) -> std::io::Result<()> {
    let features = std::collections::BTreeMap::from([(
        crate::product::agent::features::Feature::Identities,
        true,
    )]);
    crate::test_support::app_server::write_mock_responses_config_toml_with_options(
        lha_home,
        server_uri,
        &features,
        20_000,
        Some(false),
        "mock_provider",
        crate::test_support::app_server::MockResponsesConfigTomlOptions {
            model: "mock-model",
            compact_prompt: "",
            approval_policy: "untrusted",
            sandbox_mode: "read-only",
        },
    )
}
