use anyhow::Result;
use std::fs;
use std::path::Path;

pub fn run(dir: &Path) -> Result<()> {
    let citrine_path = dir.join(".citrine");
    if !citrine_path.exists() {
        fs::write(&citrine_path, "")?;
    }
    println!("Initialized citrine in {}", dir.display());

    let gitignore_path = dir.join(".gitignore");
    let entry = ".citrine.local";

    if gitignore_path.exists() {
        let content = fs::read_to_string(&gitignore_path)?;
        if !content.lines().any(|l| l.trim() == entry) {
            let separator = if content.ends_with('\n') || content.is_empty() { "" } else { "\n" };
            fs::write(&gitignore_path, format!("{}{}{}\n", content, separator, entry))?;
            println!("Added {} to .gitignore", entry);
        }
    } else {
        fs::write(&gitignore_path, format!("{}\n", entry))?;
        println!("Added {} to .gitignore", entry);
    }

    Ok(())
}
