//! Tests for bug, spike, and refactor pipeline-item operations.

use super::bug::{create_bug_file, extract_bug_name_from_content, list_bug_files};
use super::refactor::{create_refactor_file, list_refactor_files};
use super::spike::create_spike_file;
use std::fs;

fn setup_git_repo(root: &std::path::Path) {
    crate::db::ensure_content_store();
    std::process::Command::new("git")
        .args(["init"])
        .current_dir(root)
        .output()
        .unwrap();
    std::process::Command::new("git")
        .args(["config", "user.email", "test@test.com"])
        .current_dir(root)
        .output()
        .unwrap();
    std::process::Command::new("git")
        .args(["config", "user.name", "Test"])
        .current_dir(root)
        .output()
        .unwrap();
    std::process::Command::new("git")
        .args(["commit", "--allow-empty", "-m", "init"])
        .current_dir(root)
        .output()
        .unwrap();
}

// ── Bug file helper tests ──────────────────────────────────────────────────

#[test]
fn next_item_number_starts_at_1_when_empty_bugs() {
    let tmp = tempfile::tempdir().unwrap();
    assert!(super::super::next_item_number(tmp.path()).unwrap() >= 1);
}

#[test]
fn next_item_number_increments_from_existing_bugs() {
    crate::db::ensure_content_store();
    let tmp = tempfile::tempdir().unwrap();
    let backlog = tmp.path().join(".huskies/work/1_backlog");
    fs::create_dir_all(&backlog).unwrap();
    fs::write(backlog.join("1_bug_crash.md"), "").unwrap();
    fs::write(backlog.join("3_bug_another.md"), "").unwrap();
    // Also write to content store so next_item_number sees them.
    crate::db::write_item_with_content(
        "1_bug_crash",
        "1_backlog",
        "---\nname: Crash\n---\n",
        crate::db::ItemMeta::named("Crash"),
    );
    crate::db::write_item_with_content(
        "3_bug_another",
        "1_backlog",
        "---\nname: Another\n---\n",
        crate::db::ItemMeta::named("Another"),
    );
    assert!(super::super::next_item_number(tmp.path()).unwrap() >= 4);
}

#[test]
fn next_item_number_scans_archived_too() {
    crate::db::ensure_content_store();
    let tmp = tempfile::tempdir().unwrap();
    let backlog = tmp.path().join(".huskies/work/1_backlog");
    let archived = tmp.path().join(".huskies/work/5_done");
    fs::create_dir_all(&backlog).unwrap();
    fs::create_dir_all(&archived).unwrap();
    fs::write(archived.join("5_bug_old.md"), "").unwrap();
    // Also write to content store so next_item_number sees it.
    crate::db::write_item_with_content(
        "5_bug_old",
        "5_done",
        "---\nname: Old Bug\n---\n",
        crate::db::ItemMeta::named("Old Bug"),
    );
    assert!(super::super::next_item_number(tmp.path()).unwrap() >= 6);
}

#[test]
fn list_bug_files_no_crash_on_missing_dir() {
    // list_bug_files now reads from the global CRDT, not the filesystem.
    // Verify it does not panic when called with a non-existent project root.
    let tmp = tempfile::tempdir().unwrap();
    let result = list_bug_files(tmp.path());
    assert!(result.is_ok());
}

#[test]
fn list_bug_files_excludes_archive_subdir() {
    let tmp = tempfile::tempdir().unwrap();
    crate::db::ensure_content_store();
    // Bug in backlog (should appear).
    crate::db::write_item_with_content(
        "7001_bug_open",
        "1_backlog",
        "---\nname: Open Bug\n---\n# Bug 7001: Open Bug\n",
        crate::db::ItemMeta::named("Open Bug"),
    );
    // Bug in done (should NOT appear — list_bug_files only returns Backlog).
    crate::db::write_item_with_content(
        "7002_bug_closed",
        "5_done",
        "---\nname: Closed Bug\n---\n# Bug 7002: Closed Bug\n",
        crate::db::ItemMeta::named("Closed Bug"),
    );

    let result = list_bug_files(tmp.path()).unwrap();
    assert!(
        result
            .iter()
            .any(|(id, name)| id == "7001_bug_open" && name == "Open Bug")
    );
    assert!(!result.iter().any(|(id, _)| id == "7002_bug_closed"));
}

#[test]
fn list_bug_files_sorted_by_id() {
    let tmp = tempfile::tempdir().unwrap();
    crate::db::ensure_content_store();
    crate::db::write_item_with_content(
        "7013_bug_third",
        "1_backlog",
        "---\nname: Third\n---\n# Bug 7013: Third\n",
        crate::db::ItemMeta::named("Third"),
    );
    crate::db::write_item_with_content(
        "7011_bug_first",
        "1_backlog",
        "---\nname: First\n---\n# Bug 7011: First\n",
        crate::db::ItemMeta::named("First"),
    );
    crate::db::write_item_with_content(
        "7012_bug_second",
        "1_backlog",
        "---\nname: Second\n---\n# Bug 7012: Second\n",
        crate::db::ItemMeta::named("Second"),
    );

    let result = list_bug_files(tmp.path()).unwrap();
    // Find positions of our three bugs in the sorted result.
    let pos_first = result
        .iter()
        .position(|(id, _)| id == "7011_bug_first")
        .unwrap();
    let pos_second = result
        .iter()
        .position(|(id, _)| id == "7012_bug_second")
        .unwrap();
    let pos_third = result
        .iter()
        .position(|(id, _)| id == "7013_bug_third")
        .unwrap();
    assert!(pos_first < pos_second);
    assert!(pos_second < pos_third);
}

#[test]
fn extract_bug_name_from_content_parses_heading() {
    let content = "# Bug 1: Login page crashes\n\n## Description\n";
    let name = extract_bug_name_from_content(content).unwrap();
    assert_eq!(name, "Login page crashes");
}

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

    let bug_id = create_bug_file(
        tmp.path(),
        "Login Crash",
        "The login page crashes on submit.",
        "1. Go to /login\n2. Click submit",
        "Page crashes with 500 error",
        "Login succeeds",
        &["Login form submits without error".to_string()],
        None,
    )
    .unwrap();

    assert!(
        bug_id.chars().all(|c| c.is_ascii_digit()),
        "bug ID must be numeric-only, got: {bug_id}"
    );

    // Check content exists (either in DB or filesystem).
    let contents = crate::db::read_content(crate::db::ContentKey::Story(&bug_id))
        .or_else(|| {
            let filepath = tmp
                .path()
                .join(format!(".huskies/work/1_backlog/{bug_id}.md"));
            fs::read_to_string(filepath).ok()
        })
        .expect("bug content should exist");

    assert!(
        contents.starts_with("---\ntype: bug\nname: \"Login Crash\"\n---"),
        "bug file must start with YAML front matter including type field"
    );
    assert!(
        contents.contains("Login Crash"),
        "content should mention bug name"
    );
    assert!(contents.contains("## Description"));
    assert!(contents.contains("The login page crashes on submit."));
    assert!(contents.contains("## How to Reproduce"));
    assert!(contents.contains("1. Go to /login"));
    assert!(contents.contains("## Actual Result"));
    assert!(contents.contains("Page crashes with 500 error"));
    assert!(contents.contains("## Expected Result"));
    assert!(contents.contains("Login succeeds"));
    assert!(contents.contains("## Acceptance Criteria"));
    assert!(contents.contains("- [ ] Login form submits without error"));
}

#[test]
fn create_bug_file_rejects_empty_name() {
    let tmp = tempfile::tempdir().unwrap();
    let result = create_bug_file(
        tmp.path(),
        "!!!",
        "desc",
        "steps",
        "actual",
        "expected",
        &[],
        None,
    );
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("alphanumeric"));
}

#[test]
fn create_bug_file_rejects_empty_acceptance_criteria() {
    let tmp = tempfile::tempdir().unwrap();
    let err = create_bug_file(
        tmp.path(),
        "Some Bug",
        "desc",
        "steps",
        "actual",
        "expected",
        &[],
        None,
    )
    .unwrap_err();
    assert!(
        err.contains("acceptance criterion"),
        "error should mention acceptance criterion, got: {err}"
    );
}

// ── create_spike_file tests ────────────────────────────────────────────────

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

    let spike_id = create_spike_file(
        tmp.path(),
        "Filesystem Watcher Architecture",
        None,
        &["Architecture documented".to_string()],
        None,
    )
    .unwrap();

    assert!(
        spike_id.chars().all(|c| c.is_ascii_digit()),
        "spike ID must be numeric-only, got: {spike_id}"
    );

    let contents = crate::db::read_content(crate::db::ContentKey::Story(&spike_id))
        .expect("spike content should exist");

    assert!(
        contents.starts_with("---\ntype: spike\nname: \"Filesystem Watcher Architecture\"\n---"),
        "spike file must start with YAML front matter including type field"
    );
    assert!(
        contents.contains("Filesystem Watcher Architecture"),
        "content should mention spike name"
    );
    assert!(contents.contains("## Question"));
    assert!(contents.contains("## Hypothesis"));
    assert!(contents.contains("## Timebox"));
    assert!(contents.contains("## Investigation Plan"));
    assert!(contents.contains("## Findings"));
    assert!(contents.contains("## Recommendation"));
}

#[test]
fn create_spike_file_uses_description_when_provided() {
    crate::db::ensure_content_store();
    let tmp = tempfile::tempdir().unwrap();
    let description = "What is the best approach for watching filesystem events?";

    let spike_id = create_spike_file(
        tmp.path(),
        "FS Watcher Spike",
        Some(description),
        &["Findings documented".to_string()],
        None,
    )
    .unwrap();

    let contents = crate::db::read_content(crate::db::ContentKey::Story(&spike_id))
        .or_else(|| {
            let filepath = tmp
                .path()
                .join(format!(".huskies/work/1_backlog/{spike_id}.md"));
            fs::read_to_string(filepath).ok()
        })
        .expect("spike content should exist");
    assert!(contents.contains(description));
}

#[test]
fn create_spike_file_uses_placeholder_when_no_description() {
    crate::db::ensure_content_store();
    let tmp = tempfile::tempdir().unwrap();
    let spike_id = create_spike_file(
        tmp.path(),
        "My Spike",
        None,
        &["Findings documented".to_string()],
        None,
    )
    .unwrap();

    let contents = crate::db::read_content(crate::db::ContentKey::Story(&spike_id))
        .or_else(|| {
            let filepath = tmp
                .path()
                .join(format!(".huskies/work/1_backlog/{spike_id}.md"));
            fs::read_to_string(filepath).ok()
        })
        .expect("spike content should exist");
    assert!(contents.contains("## Question\n\n- TBD\n"));
}

#[test]
fn create_spike_file_rejects_empty_name() {
    let tmp = tempfile::tempdir().unwrap();
    // Name "!!!" has no alphanumeric chars — fails before AC check.
    let err = create_spike_file(tmp.path(), "!!!", None, &["AC".to_string()], None).unwrap_err();
    assert!(err.contains("alphanumeric"), "got: {err}");
}

#[test]
fn create_spike_file_with_special_chars_in_name_produces_valid_yaml() {
    crate::db::ensure_content_store();
    let tmp = tempfile::tempdir().unwrap();
    let name = "Spike: compare \"fast\" vs slow encoders";
    let result = create_spike_file(
        tmp.path(),
        name,
        None,
        &["Findings documented".to_string()],
        None,
    );
    assert!(result.is_ok(), "create_spike_file failed: {result:?}");

    let spike_id = result.unwrap();
    let view = crate::crdt_state::read_item(&spike_id).expect("CRDT entry should exist");
    assert_eq!(view.name(), name);
}

#[test]
fn create_spike_file_increments_from_existing_items() {
    let tmp = tempfile::tempdir().unwrap();
    crate::db::ensure_content_store();
    // Seed a high-numbered item into the CRDT so next_item_number goes beyond it.
    crate::db::write_item_with_content(
        "7050_story_existing",
        "1_backlog",
        "---\nname: Existing\n---\n",
        crate::db::ItemMeta::named("Existing"),
    );

    let spike_id = create_spike_file(
        tmp.path(),
        "My Spike",
        None,
        &["Findings documented".to_string()],
        None,
    )
    .unwrap();
    assert!(
        spike_id.chars().all(|c| c.is_ascii_digit()),
        "spike ID must be numeric-only, got: {spike_id}"
    );
    let num: u32 = spike_id.parse().unwrap();
    assert!(
        num >= 7051,
        "expected spike number >= 7051, got: {spike_id}"
    );
}

// ── Bug 640: create_bug_file / create_refactor_file depends_on tests ────────

#[test]
fn create_bug_file_with_depends_on_persists_to_crdt() {
    crate::crdt_state::init_for_test();
    let tmp = tempfile::tempdir().unwrap();
    setup_git_repo(tmp.path());

    let bug_id = create_bug_file(
        tmp.path(),
        "Dep Bug",
        "desc",
        "steps",
        "actual",
        "expected",
        &["Bug fixed".to_string()],
        Some(&[42, 43]),
    )
    .unwrap();

    let view = crate::crdt_state::read_item(&bug_id).expect("CRDT entry should exist");
    assert_eq!(view.depends_on(), &[42, 43]);
}

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

    let bug_id = create_bug_file(
        tmp.path(),
        "No Dep Bug",
        "desc",
        "steps",
        "actual",
        "expected",
        &["Bug fixed".to_string()],
        None,
    )
    .unwrap();

    let contents = crate::db::read_content(crate::db::ContentKey::Story(&bug_id))
        .or_else(|| {
            let filepath = tmp
                .path()
                .join(format!(".huskies/work/1_backlog/{bug_id}.md"));
            fs::read_to_string(filepath).ok()
        })
        .expect("bug content should exist");

    assert!(
        !contents.contains("depends_on"),
        "front matter must not contain depends_on when not provided: {contents}"
    );
}

#[test]
fn create_refactor_file_with_depends_on_persists_to_crdt() {
    crate::crdt_state::init_for_test();
    let tmp = tempfile::tempdir().unwrap();
    setup_git_repo(tmp.path());

    let refactor_id = create_refactor_file(
        tmp.path(),
        "Dep Refactor",
        None,
        &["Refactoring complete".to_string()],
        Some(&[99]),
    )
    .unwrap();

    let view = crate::crdt_state::read_item(&refactor_id).expect("CRDT entry should exist");
    assert_eq!(view.depends_on(), &[99]);
}

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

    let refactor_id = create_refactor_file(
        tmp.path(),
        "No Dep Refactor",
        None,
        &["Refactoring complete".to_string()],
        None,
    )
    .unwrap();

    let contents = crate::db::read_content(crate::db::ContentKey::Story(&refactor_id))
        .or_else(|| {
            let filepath = tmp
                .path()
                .join(format!(".huskies/work/1_backlog/{refactor_id}.md"));
            fs::read_to_string(filepath).ok()
        })
        .expect("refactor content should exist");

    assert!(
        !contents.contains("depends_on"),
        "front matter must not contain depends_on when not provided: {contents}"
    );
}

#[test]
fn list_refactor_files_returns_ok() {
    let tmp = tempfile::tempdir().unwrap();
    let result = list_refactor_files(tmp.path());
    assert!(result.is_ok());
}

/// Regression for bug 1001: 8 rapid sequential `create_refactor` calls with
/// `depends_on` chains must all land cleanly in BOTH the content store AND
/// the CRDT.  Before the fix, the allocator could return a tombstoned ID on
/// a tight loop, producing a half-written item invisible to `list_refactors`
/// and `update_story`.
#[test]
fn rapid_sequential_creates_all_land_in_crdt() {
    crate::crdt_state::init_for_test();
    crate::db::ensure_content_store();
    let tmp = tempfile::tempdir().unwrap();

    let mut ids: Vec<String> = Vec::new();

    for i in 0..8u32 {
        // Build a depends_on chain: item i depends on item i-1.
        let depends_on: Option<Vec<u32>> = if ids.is_empty() {
            None
        } else {
            let last_num: u32 = ids.last().unwrap().parse().unwrap_or(0);
            Some(vec![last_num])
        };

        let id = create_refactor_file(
            tmp.path(),
            &format!("Rapid Refactor {i}"),
            None,
            &[format!("AC for rapid refactor {i}")],
            depends_on.as_deref(),
        )
        .unwrap_or_else(|e| panic!("create_refactor_file {i} failed: {e}"));

        // Immediately verify it landed in CRDT (the core transactional guarantee).
        assert!(
            crate::crdt_state::read_item(&id).is_some(),
            "refactor {i} (id={id}) must be in CRDT immediately after create"
        );

        ids.push(id);
    }

    assert_eq!(ids.len(), 8, "all 8 creates must succeed");
    assert_eq!(
        ids.iter().collect::<std::collections::HashSet<_>>().len(),
        8,
        "all 8 IDs must be distinct"
    );

    // list_refactor_files must return all 8 (reads from CRDT).
    let listed = list_refactor_files(tmp.path()).expect("list_refactor_files must succeed");
    let listed_ids: std::collections::HashSet<&str> =
        listed.iter().map(|(id, _)| id.as_str()).collect();
    for id in &ids {
        assert!(
            listed_ids.contains(id.as_str()),
            "refactor '{id}' must appear in list_refactor_files: {listed_ids:?}"
        );
    }

    // set_name (the update_story --name path) must succeed for all 8.
    for (i, id) in ids.iter().enumerate() {
        let new_name = format!("Renamed Rapid Refactor {i}");
        let success = crate::crdt_state::set_name(id, Some(&new_name));
        assert!(success, "set_name for refactor {i} (id={id}) must succeed");
        let view = crate::crdt_state::read_item(id)
            .unwrap_or_else(|| panic!("item {i} (id={id}) must still be in CRDT after rename"));
        assert_eq!(
            view.name(),
            new_name,
            "CRDT must reflect the new name for refactor {i}"
        );
    }
}
