use crate::file::{collect_all_hashes, CitrineFile};
use crate::hash::generate_hash;
use crate::task::{Line, Status, Task};
use anyhow::Result;
use std::path::Path;

pub fn run(dir: &Path, description: &str, local: bool) -> Result<()> {
    let citrine_path = dir.join(".citrine");
    if !citrine_path.exists() {
        anyhow::bail!("Not initialized. Run 'citrine init' first");
    }

    let existing = collect_all_hashes(dir);
    let hash = generate_hash(&existing)?;

    let target = if local {
        dir.join(".citrine.local")
    } else {
        citrine_path
    };

    let mut file = CitrineFile::read_or_empty(&target);
    let task = Task {
        hash: hash.clone(),
        status: Status::Todo,
        description: description.to_string(),
        metadata: String::new(),
    };
    file.lines.push(Line::Task(task));
    file.write(&target)?;

    let suffix = if local { " (local)" } else { "" };
    println!("Added task [{}]: {}{}", hash, description, suffix);
    Ok(())
}
