use std::fs;
use std::path::PathBuf;

use snippets::engine::Engine;

fn write(path: &PathBuf, contents: &str) {
    if let Some(p) = path.parent() { fs::create_dir_all(p).unwrap(); }
    fs::write(path, contents).unwrap();
}

fn setup_temp_root(name: &str) -> PathBuf {
    let root = std::env::var_os("CARGO_TARGET_TMPDIR").map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("target/test-tmp"));
    if !root.exists() { let _ = fs::create_dir_all(&root); }
    let dir = root.join(format!("snippets-{}-{}", name, std::process::id()));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();
    dir
}

#[test]
fn pointer_dep_from_text_segment_namespaced() {
    let root = setup_temp_root("text-ns");
    let src_dir = root.join("src");
    let out_dir = root.join("dist");
    let snippets_dir = root.join("snippets");
    let content_dir = root.join("content");
    let static_dir = root.join("static");

    write(&src_dir.join("page.htmlt"), "Hello {{foo/bar}}\n");
    write(&content_dir.join("foo.toml"), "bar = 'X'\n");

    let mut engine = Engine::new(
        src_dir.clone(),
        out_dir,
        snippets_dir,
        content_dir.clone(),
        static_dir,
        true,
    ).unwrap();

    engine.full_build().unwrap();

    // expect pointer key recorded
    let key = "foo.toml::path=bar";
    let templates = engine.depgraph.templates_by_content_ptr(key);
    assert!(templates.iter().any(|t| t == "page.htmlt"));

    // ensure the file key grouping works
    let ptrs = engine.depgraph.pointer_keys_for_content_file("foo.toml");
    assert!(ptrs.iter().any(|k| k == key));
}

#[test]
fn pointer_dep_from_list_snippet_content_pointer() {
    let root = setup_temp_root("list-cp");
    let src_dir = root.join("src");
    let out_dir = root.join("dist");
    let snippets_dir = root.join("snippets");
    let content_dir = root.join("content");
    let static_dir = root.join("static");

    write(&src_dir.join("page.htmlt"), "<!-- @snippet name=\"it\" is=\"list\" content=\"list\" -->\n");
    write(&snippets_dir.join("it.htmls"), "<li>{{name}}</li>\n");
    write(&content_dir.join("list.toml"), "items = [ { name = 'a' } ]\n");

    let mut engine = Engine::new(
        src_dir.clone(),
        out_dir,
        snippets_dir.clone(),
        content_dir.clone(),
        static_dir,
        true,
    ).unwrap();

    engine.full_build().unwrap();

    // expect pointer key for implicit items path
    let key = "list.toml::path=items";
    let templates = engine.depgraph.templates_by_content_ptr(key);
    assert!(templates.iter().any(|t| t == "page.htmlt"));
}
