const std = @import("std");
const sdl = @import("sdl");
const vkgen = @import("vulkan");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});

    const optimize = b.standardOptimizeOption(.{});

    const exe = b.addExecutable(.{
        .name = "vulkan-test",
        .root_source_file = b.path("src/main.zig"),
        .target = target,
        .optimize = optimize,
        .link_libc = true,
    });

    // --- Dependencies ---

    // Vulkan
    const vkzig_dep = b.dependency("vulkan", .{
        .registry = @as([]const u8, b.pathFromRoot("./vk.xml")),
    });
    const vkzig_bindings = vkzig_dep.module("vulkan-zig");
    exe.root_module.addImport("vulkan", vkzig_bindings);

    // Shaders
    compileShader(b, exe, "shader_frag", "shader.frag");
    compileShader(b, exe, "shader_vert", "shader.vert");
    compileShader(b, exe, "second_frag", "second.frag");
    compileShader(b, exe, "second_vert", "second.vert");

    // SDL2
    const sdl_sdk = sdl.init(b, .{});
    sdl_sdk.link(exe, .dynamic, sdl.Library.SDL2);
    exe.root_module.addImport("sdl", sdl_sdk.getWrapperModuleVulkan(vkzig_bindings));

    // zmath
    const zmath = b.dependency("zmath", .{});
    exe.root_module.addImport("zmath", zmath.module("root"));

    // zstbi
    const zstbi = b.dependency("zstbi", .{});
    exe.root_module.addImport("zstbi", zstbi.module("root"));
    exe.linkLibrary(zstbi.artifact("zstbi"));

    // Assimp
    exe.linkSystemLibrary("assimp");

    // ---

    b.installArtifact(exe);

    const exe_check = b.addExecutable(.{
        .name = "vulkan-test",
        .root_source_file = b.path("src/main.zig"),
        .target = target,
        .optimize = optimize,
    });

    const check = b.step("check", "Check if vulkan-test compiles");
    check.dependOn(&exe_check.step);

    const run_cmd = b.addRunArtifact(exe);

    run_cmd.step.dependOn(b.getInstallStep());

    if (b.args) |args| {
        run_cmd.addArgs(args);
    }

    const run_step = b.step("run", "Run the app");
    run_step.dependOn(&run_cmd.step);

    const exe_unit_tests = b.addTest(.{
        .root_source_file = b.path("src/main.zig"),
        .target = target,
        .optimize = optimize,
    });

    const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);

    const test_step = b.step("test", "Run unit tests");
    test_step.dependOn(&run_exe_unit_tests.step);
}

fn compileShader(
    b: *std.Build,
    exe: *std.Build.Step.Compile,
    comptime name: []const u8,
    comptime file_name: []const u8,
) void {
    const cmd = b.addSystemCommand(&.{ "glslc", "--target-env=vulkan1.3", "-o" });

    const spv = cmd.addOutputFileArg(name ++ ".spv");
    cmd.addFileArg(b.path("src/shaders/" ++ file_name));
    exe.root_module.addAnonymousImport(name, .{ .root_source_file = spv });
}
