//! Spike item MCP tools.

#![allow(unused_imports, dead_code)]
#[allow(unused_imports)]
use crate::agents::{
    close_bug_to_archive, feature_branch_has_unmerged_changes, move_story_to_done,
};
use crate::http::context::AppContext;
use crate::http::workflow::{
    add_criterion_to_file, check_criterion_in_file, create_bug_file, create_refactor_file,
    create_spike_file, create_story_file, edit_criterion_in_file, list_bug_files,
    list_refactor_files, load_pipeline_state, load_upcoming_stories, remove_criterion_from_file,
    update_story_in_file, validate_story_dirs,
};
use crate::io::story_metadata::parse_unchecked_todos;
use crate::service::story::parse_test_cases;
use crate::slog_warn;
#[allow(unused_imports)]
use crate::workflow::{TestCaseResult, TestStatus, evaluate_acceptance_with_coverage};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::fs;

pub(crate) fn tool_create_spike(args: &Value, ctx: &AppContext) -> Result<String, String> {
    let req = crate::validation::CreateSpikeRequest::from_json(args)?;
    let acs = req.acceptance_criteria_strings();
    let description = req.description.as_ref().map(|d| d.as_str());
    let depends_on = req.depends_on_ids();

    // Bug 1102: resolve and validate origin BEFORE creating the spike file so
    // a missing-attribution call leaves no half-state behind.
    let (origin, origin_label) = super::build_origin(args)?;

    let root = ctx.state.get_project_root()?;
    let spike_id = create_spike_file(
        &root,
        req.name.as_ref(),
        description,
        &acs,
        depends_on.as_deref(),
    )?;

    crate::crdt_state::set_origin(&spike_id, &origin);

    let _ = ctx
        .watcher_tx
        .send(crate::io::watcher::WatcherEvent::NewItemCreated {
            item_id: spike_id.clone(),
            item_type: "spike".to_string(),
            name: req.name.as_ref().to_string(),
            origin: origin_label,
        });

    Ok(format!("Created spike: {spike_id}"))
}

#[cfg(test)]
mod tests {
    use super::super::super::tools_list::handle_tools_list;
    use super::*;
    use crate::http::test_helpers::test_ctx;
    use serde_json::Value;

    #[test]
    fn create_spike_in_tools_list() {
        use super::super::super::tools_list::handle_tools_list;
        let resp = handle_tools_list(Some(json!(1)));
        let tools = resp.result.unwrap()["tools"].as_array().unwrap().clone();
        let tool = tools.iter().find(|t| t["name"] == "create_spike");
        assert!(tool.is_some(), "create_spike missing from tools list");
        let t = tool.unwrap();
        assert!(t["description"].is_string());
        let required = t["inputSchema"]["required"].as_array().unwrap();
        let req_names: Vec<&str> = required.iter().map(|v| v.as_str().unwrap()).collect();
        assert!(req_names.contains(&"name"));
        // description is optional
        assert!(!req_names.contains(&"description"));
    }

    #[test]
    fn tool_create_spike_missing_name() {
        let tmp = tempfile::tempdir().unwrap();
        let ctx = test_ctx(tmp.path());
        let result = tool_create_spike(&json!({}), &ctx);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("name"));
    }

    #[test]
    fn tool_create_spike_rejects_empty_name() {
        let tmp = tempfile::tempdir().unwrap();
        let ctx = test_ctx(tmp.path());
        let result = tool_create_spike(
            &json!({
                "name": "!!!",
                "acceptance_criteria": ["AC"],
                "origin": {"kind": "test", "id": "test-suite"}
            }),
            &ctx,
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("alphanumeric"));
    }

    #[test]
    fn tool_create_spike_rejects_whitespace_only_name() {
        let tmp = tempfile::tempdir().unwrap();
        let ctx = test_ctx(tmp.path());
        let err = tool_create_spike(
            &json!({"name": "   ", "acceptance_criteria": ["Findings documented"]}),
            &ctx,
        )
        .unwrap_err();
        assert!(
            err.contains("EmptyAfterTrim"),
            "error should mention EmptyAfterTrim, got: {err}"
        );
    }

    #[test]
    fn tool_create_spike_creates_file() {
        crate::db::ensure_content_store();
        let tmp = tempfile::tempdir().unwrap();
        let ctx = test_ctx(tmp.path());

        let result = tool_create_spike(
            &json!({
                "name": "Compare Encoders",
                "description": "Which encoder is fastest?",
                "acceptance_criteria": ["Encoder comparison is documented"],
                "origin": {"kind": "test", "id": "test-suite"}
            }),
            &ctx,
        )
        .unwrap();

        assert!(
            result.starts_with("Created spike: "),
            "result should be a 'Created spike: <id>' message: {result}"
        );
        // Extract the actual spike ID from the result message (format: "Created spike: <id>").
        let spike_id = result.trim_start_matches("Created spike: ").trim();
        // Spike content should exist in the CRDT content store.
        let contents = crate::db::read_content(crate::db::ContentKey::Story(spike_id))
            .expect("expected spike content in CRDT");
        assert!(contents.starts_with("---\ntype: spike\nname: \"Compare Encoders\"\n---"));
        assert!(contents.contains("Which encoder is fastest?"));
    }

    #[test]
    fn tool_create_spike_creates_file_without_description() {
        crate::db::ensure_content_store();
        let tmp = tempfile::tempdir().unwrap();
        let ctx = test_ctx(tmp.path());

        let result = tool_create_spike(
            &json!({
                "name": "My Spike",
                "acceptance_criteria": ["Spike findings documented"],
                "origin": {"kind": "test", "id": "test-suite"}
            }),
            &ctx,
        )
        .unwrap();
        assert!(
            result.starts_with("Created spike: "),
            "result should be a 'Created spike: <id>' message: {result}"
        );
        // Extract the actual spike ID from the result message (format: "Created spike: <id>").
        let spike_id = result.trim_start_matches("Created spike: ").trim();

        // Spike content should exist in the CRDT content store.
        let contents = crate::db::read_content(crate::db::ContentKey::Story(spike_id))
            .expect("expected spike content in CRDT");
        assert!(contents.starts_with("---\ntype: spike\nname: \"My Spike\"\n---"));
        assert!(contents.contains("## Question\n\n- TBD\n"));
    }

    #[test]
    fn tool_create_spike_rejects_missing_acceptance_criteria() {
        let tmp = tempfile::tempdir().unwrap();
        let ctx = test_ctx(tmp.path());
        let result = tool_create_spike(&json!({"name": "My Spike"}), &ctx);
        assert!(result.is_err());
        assert!(
            result.unwrap_err().contains("acceptance_criteria"),
            "error should mention acceptance_criteria"
        );
    }

    #[test]
    fn tool_create_spike_rejects_empty_acceptance_criteria() {
        let tmp = tempfile::tempdir().unwrap();
        let ctx = test_ctx(tmp.path());
        let result = tool_create_spike(
            &json!({"name": "My Spike", "acceptance_criteria": []}),
            &ctx,
        );
        assert!(result.is_err());
        assert!(
            result.unwrap_err().contains("acceptance_criteria"),
            "error should mention acceptance_criteria"
        );
    }

    #[test]
    fn tool_create_spike_accepts_single_criterion() {
        crate::db::ensure_content_store();
        let tmp = tempfile::tempdir().unwrap();
        let ctx = test_ctx(tmp.path());
        let result = tool_create_spike(
            &json!({
                "name": "Single Criterion Spike",
                "acceptance_criteria": ["Findings documented"],
                "origin": {"kind": "test", "id": "test-suite"}
            }),
            &ctx,
        );
        assert!(result.is_ok(), "expected ok: {result:?}");
        assert!(result.unwrap().contains("Created spike:"));
    }

    #[test]
    fn tool_create_spike_rejects_all_junk_acceptance_criteria() {
        let tmp = tempfile::tempdir().unwrap();
        let ctx = test_ctx(tmp.path());
        let result = tool_create_spike(
            &json!({"name": "Junk Spike", "acceptance_criteria": ["TODO", "TBD"]}),
            &ctx,
        );
        assert!(result.is_err());
        assert!(
            result.unwrap_err().contains("TooFewItems"),
            "error should contain TooFewItems"
        );
    }

    #[test]
    fn tool_create_spike_accepts_mixed_junk_and_real_acceptance_criteria() {
        crate::db::ensure_content_store();
        let tmp = tempfile::tempdir().unwrap();
        let ctx = test_ctx(tmp.path());
        let result = tool_create_spike(
            &json!({
                "name": "Mixed Spike",
                "acceptance_criteria": ["TODO", "Real AC"],
                "origin": {"kind": "test", "id": "test-suite"}
            }),
            &ctx,
        );
        assert!(result.is_ok(), "expected ok for mixed AC: {result:?}");
        assert!(result.unwrap().contains("Created spike:"));
    }
}
