use std::path::Path;
use std::process::Command;

fn main()
{
    compile_ink_stories();

    let wesl = wesl::Wesl::new("src/shaders");
    wesl.build_artifact(&"package::main".parse().unwrap(), "main");
    wesl.build_artifact(&"package::shadow".parse().unwrap(), "shadow");
}

fn compile_ink_stories()
{
    let dialogs_dir = Path::new("assets/dialogs");

    if !dialogs_dir.exists()
    {
        return;
    }

    let inklecate = Path::new("tools/inklecate.dll");

    if !inklecate.exists()
    {
        eprintln!("cargo:warning=tools/inklecate.dll not found — ink stories will not be compiled");
        return;
    }

    let entries = match std::fs::read_dir(dialogs_dir)
    {
        Ok(e) => e,
        Err(_) => return,
    };

    for entry in entries.flatten()
    {
        let path = entry.path();

        if path.extension().and_then(|e| e.to_str()) != Some("ink")
        {
            continue;
        }

        let ink_path = path.to_str().unwrap();
        let json_path = format!("{}.json", ink_path);

        println!("cargo:rerun-if-changed={ink_path}");

        let ink_modified = std::fs::metadata(ink_path).and_then(|m| m.modified()).ok();
        let json_modified = std::fs::metadata(&json_path)
            .and_then(|m| m.modified())
            .ok();

        let needs_compile = match (ink_modified, json_modified)
        {
            (Some(ink_time), Some(json_time)) => ink_time > json_time,
            _ => true,
        };

        if !needs_compile
        {
            continue;
        }

        println!("cargo:warning=Compiling {ink_path}");

        let status = Command::new("dotnet")
            .args([inklecate.to_str().unwrap(), "-o", &json_path, ink_path])
            .status();

        match status
        {
            Ok(s) if s.success() =>
            {
                println!("cargo:warning=Compiled {ink_path} → {json_path}");
            }
            Ok(s) =>
            {
                println!("cargo:warning=inklecate exited with {s} for {ink_path}");
            }
            Err(e) =>
            {
                println!("cargo:warning=Failed to run dotnet inklecate: {e}");
            }
        }
    }
}
