//! create_story_file: write new story to CRDT/content store.

#[allow(unused_imports)]
use super::super::{
    create_section_content, next_item_number, read_story_content, replace_section_content,
    slugify_name, story_stage, write_story_content,
};

pub fn create_story_file(
    root: &std::path::Path,
    name: &str,
    user_story: Option<&str>,
    description: Option<&str>,
    acceptance_criteria: Option<&[String]>,
    depends_on: Option<&[u32]>,
    _commit: bool,
) -> Result<String, String> {
    let story_number = next_item_number(root)?;
    let slug = slugify_name(name);

    if slug.is_empty() {
        return Err("Name must contain at least one alphanumeric character.".to_string());
    }

    let story_id = format!("{story_number}");

    let mut content = String::new();
    content.push_str("---\n");
    content.push_str("type: story\n");
    content.push_str(&format!("name: \"{}\"\n", name.replace('"', "\\\"")));
    if let Some(deps) = depends_on.filter(|d| !d.is_empty()) {
        let nums: Vec<String> = deps.iter().map(|n| n.to_string()).collect();
        content.push_str(&format!("depends_on: [{}]\n", nums.join(", ")));
    }
    content.push_str("---\n\n");
    content.push_str(&format!("# Story {story_number}: {name}\n\n"));

    content.push_str("## User Story\n\n");
    if let Some(us) = user_story {
        content.push_str(us);
        content.push('\n');
    } else {
        content.push_str("As a ..., I want ..., so that ...\n");
    }
    content.push('\n');

    if let Some(desc) = description {
        content.push_str("## Description\n\n");
        content.push_str(desc);
        content.push('\n');
        content.push('\n');
    }

    content.push_str("## Acceptance Criteria\n\n");
    if let Some(criteria) = acceptance_criteria {
        for criterion in criteria {
            content.push_str(&format!("- [ ] {criterion}\n"));
        }
    } else {
        content.push_str("- [ ] TODO\n");
    }
    content.push('\n');

    content.push_str("## Out of Scope\n\n");
    content.push_str("- TBD\n");

    // Write to database content store and CRDT.
    write_story_content(root, &story_id, "1_backlog", &content);

    Ok(story_id)
}

/// Check off the Nth unchecked acceptance criterion in a story.
///
/// `criterion_index` is 0-based among unchecked (`- [ ]`) items.
#[cfg(test)]
mod tests {
    use super::*;
    use crate::io::story_metadata::parse_front_matter;
    use std::fs;

    #[allow(dead_code)]
    fn setup_git_repo(root: &std::path::Path) {
        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();
    }

    #[allow(dead_code)]
    fn story_with_criteria(n: usize) -> String {
        let mut s = "---\nname: Test Story\n---\n\n## Acceptance Criteria\n\n".to_string();
        for i in 0..n {
            s.push_str(&format!("- [ ] Criterion {i}\n"));
        }
        s
    }

    /// Helper to set up a story in the filesystem and content store for tests
    /// that use check/add criterion.
    #[allow(dead_code)]
    fn setup_story_in_fs(root: &std::path::Path, story_id: &str, content: &str) {
        let current = root.join(".huskies/work/2_current");
        fs::create_dir_all(&current).unwrap();
        fs::write(current.join(format!("{story_id}.md")), content).unwrap();
        // Also write to the global content store so read_story_content picks up this
        // content even when a previous test has left a stale entry for the same ID.
        crate::db::ensure_content_store();
        crate::db::write_content(story_id, content);
    }

    // --- create_story integration tests ---

    #[test]
    fn create_story_writes_correct_content() {
        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("36_story_existing.md"), "").unwrap();
        // Also write to content store so next_item_number sees it.
        crate::db::write_item_with_content(
            "36_story_existing",
            "1_backlog",
            "---\nname: Existing\n---\n",
        );

        let number = super::super::super::next_item_number(tmp.path()).unwrap();
        // The number must be >= 37 (at least higher than the existing "36_story_existing.md"),
        // but the global content store may have higher-numbered items from parallel tests.
        assert!(number >= 37, "expected number >= 37, got: {number}");

        let slug = super::super::super::slugify_name("My New Feature");
        assert_eq!(slug, "my_new_feature");

        let filename = format!("{number}_{slug}.md");
        let filepath = backlog.join(&filename);

        let mut content = String::new();
        content.push_str("---\n");
        content.push_str("name: \"My New Feature\"\n");
        content.push_str("---\n\n");
        content.push_str(&format!("# Story {number}: My New Feature\n\n"));
        content.push_str("## User Story\n\n");
        content.push_str("As a dev, I want this feature\n\n");
        content.push_str("## Acceptance Criteria\n\n");
        content.push_str("- [ ] It works\n");
        content.push_str("- [ ] It is tested\n\n");
        content.push_str("## Out of Scope\n\n");
        content.push_str("- TBD\n");

        fs::write(&filepath, &content).unwrap();

        let written = fs::read_to_string(&filepath).unwrap();
        assert!(written.starts_with("---\n"));
        assert!(written.contains(&format!("# Story {number}: My New Feature")));
        assert!(written.contains("- [ ] It works"));
        assert!(written.contains("- [ ] It is tested"));
        assert!(written.contains("## Out of Scope"));
    }

    #[test]
    fn create_story_with_colon_in_name_produces_valid_yaml() {
        let tmp = tempfile::tempdir().unwrap();
        let name = "Server-owned agent completion: remove report_completion dependency";
        let result = create_story_file(tmp.path(), name, None, None, None, None, false);
        assert!(result.is_ok(), "create_story_file failed: {result:?}");

        let story_id = result.unwrap();
        // Read from content store or filesystem.
        let content = crate::db::read_content(&story_id)
            .or_else(|| {
                let backlog = tmp.path().join(".huskies/work/1_backlog");
                fs::read_to_string(backlog.join(format!("{story_id}.md"))).ok()
            })
            .expect("story content should exist");

        let meta = parse_front_matter(&content).expect("front matter should be valid YAML");
        assert_eq!(meta.name.as_deref(), Some(name));
    }

    // ── check_criterion_in_file tests ─────────────────────────────────────────

    #[test]
    fn create_story_with_depends_on_writes_front_matter_array() {
        let tmp = tempfile::tempdir().unwrap();
        let story_id = create_story_file(
            tmp.path(),
            "Dependent Story",
            None,
            None,
            None,
            Some(&[489]),
            false,
        )
        .unwrap();

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

        assert!(
            contents.contains("depends_on: [489]"),
            "missing front matter: {contents}"
        );
        assert!(
            !contents.contains("- [ ] depends_on"),
            "must not appear as checkbox: {contents}"
        );

        let meta = parse_front_matter(&contents).expect("front matter should parse");
        assert_eq!(meta.depends_on, Some(vec![489]));
    }

    // ── Story 730: numeric-only story IDs ─────────────────────────────────────

    #[test]
    fn create_story_file_returns_numeric_only_id() {
        crate::db::ensure_content_store();
        let tmp = tempfile::tempdir().unwrap();
        let result = create_story_file(tmp.path(), "My Feature", None, None, None, None, false);
        assert!(
            result.is_ok(),
            "create_story_file should succeed: {result:?}"
        );
        let story_id = result.unwrap();
        assert!(
            story_id.chars().all(|c| c.is_ascii_digit()),
            "story ID must be numeric-only, got: '{story_id}'"
        );
    }

    #[test]
    fn create_story_file_writes_type_field_in_front_matter() {
        crate::db::ensure_content_store();
        let tmp = tempfile::tempdir().unwrap();
        let story_id =
            create_story_file(tmp.path(), "Type Test Story", None, None, None, None, false)
                .unwrap();
        let content = crate::db::read_content(&story_id).expect("content must exist");
        let meta = crate::io::story_metadata::parse_front_matter(&content)
            .expect("front matter should be valid");
        assert_eq!(
            meta.item_type.as_deref(),
            Some("story"),
            "front matter must contain type: story"
        );
    }

    // ── Story 504: native JSON types in front_matter ───────────────────────────
}
