use std::{ffi::OsStr, path::PathBuf};

use typser::files_to_rust;
use walkdir::WalkDir;

const DOCS_SOURCE: &str = "docs";

// TODO: avoid re-building docs every time
fn main() {
    println!("cargo:rerun-if-changed=docs");
    println!("cargo:rerun-if-changed=crates/typser");

    // Recursively find all .typ (typst) files within `docs/`
    let typst_files = WalkDir::new(DOCS_SOURCE)
        .into_iter()
        // Remove inaccessible directories
        .filter_map(|possible_entry| possible_entry.ok())
        // Only find files
        .filter(|entry| entry.path().is_file())
        // Only find typst (.typ) files
        .filter(|entry| entry.path().extension() == Some(OsStr::new("typ")));

    // Set up the output directory
    let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());
    std::fs::create_dir_all(&out_dir).unwrap();

    // Keep track of all the filenames to later construct modules
    // Each folder is a module, each file is a function
    // For example: docs/test/hello.typ is docs::test::hello()
    let filenames: Vec<String> = typst_files
        .map(|entry| entry.path().to_string_lossy().to_string())
        .collect();

    // Store everything inside one large autogenerated Rust file
    let output_path = out_dir.join("docs.rs");

    let rust_code = files_to_rust(filenames);
    std::fs::write(&output_path, rust_code).unwrap();
}