use std::fs;
use std::sync::Once;

use liwe::fs::new_for_path;
use liwe::model::config::Format;
use tempfile::TempDir;

static INIT: Once = Once::new();

fn setup() {
    INIT.call_once(|| {
        let _ = env_logger::builder().try_init();
    });
}

#[test]
fn test_gitignore_excludes_files() {
    setup();

    let temp_dir = TempDir::new().unwrap();
    let base_path = temp_dir.path().to_path_buf();

    fs::write(
        base_path.join("included.md"),
        "# Included File\n\nThis should be included.",
    )
    .unwrap();
    fs::write(
        base_path.join("excluded.md"),
        "# Excluded File\n\nThis should be excluded.",
    )
    .unwrap();
    fs::write(
        base_path.join("also_included.md"),
        "# Also Included\n\nThis should also be included.",
    )
    .unwrap();

    fs::write(base_path.join(".gitignore"), "excluded.md\n").unwrap();

    let state = new_for_path(&base_path, Format::Markdown);

    assert!(state.contains_key("included"));
    assert!(state.contains_key("also_included"));
    assert!(!state.contains_key("excluded"));

    assert_eq!(
        state.get("included").unwrap(),
        "# Included File\n\nThis should be included."
    );
    assert_eq!(
        state.get("also_included").unwrap(),
        "# Also Included\n\nThis should also be included."
    );
}

#[test]
fn test_hidden_files_and_directories_excluded() {
    setup();

    let temp_dir = TempDir::new().unwrap();
    let base_path = temp_dir.path().to_path_buf();

    fs::write(base_path.join("document.md"), "# Document").unwrap();
    fs::write(base_path.join(".hidden.md"), "# Hidden").unwrap();

    let git_dir = base_path.join(".git");
    fs::create_dir(&git_dir).unwrap();
    fs::write(git_dir.join("config.md"), "# Git Config").unwrap();

    let obsidian_dir = base_path.join(".obsidian");
    fs::create_dir(&obsidian_dir).unwrap();
    fs::write(obsidian_dir.join("workspace.md"), "# Workspace").unwrap();

    let state = new_for_path(&base_path, Format::Markdown);

    assert!(state.contains_key("document"));
    assert!(!state.contains_key(".hidden"));
    assert!(!state.contains_key(".git/config"));
    assert!(!state.contains_key(".obsidian/workspace"));
    assert_eq!(state.len(), 1);
}
