const std = @import("std");
const vkgen = @import("vulkan-zig");

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

    const imgui_dep = b.dependency("imgui", .{});
    const cimgui_dep = b.dependency("cimgui", .{});

    const luajit = try b.findProgram(&.{"luajit"}, &.{});

    const gen = b.addSystemCommand(&.{luajit});
    gen.setCwd(cimgui_dep.path("generator/"));
    gen.addFileArg(cimgui_dep.path("generator/generator.lua"));
    gen.addArgs(&.{
        "zig cc",
        "comments internal noimstrv",
        "glfw",
        "vulkan",
    });
    _ = gen.captureStdOut(); // to quiet output

    {
        const relpath = try std.fs.path.relative(
            b.allocator,
            cimgui_dep.path("generator").getPath(b),
            imgui_dep.path("").getPath(b),
        );
        defer b.allocator.free(relpath);
        gen.setEnvironmentVariable(
            "IMGUI_PATH",
            relpath,
        );
    }

    const copy = b.addWriteFiles();
    copy.step.dependOn(&gen.step);
    _ = copy.addCopyDirectory(imgui_dep.path(""), "imgui", .{
        .include_extensions = &.{ ".h", ".cpp" },
    });
    _ = copy.addCopyFile(cimgui_dep.path("cimgui.h"), "cimgui.h");
    _ = copy.addCopyFile(cimgui_dep.path("cimgui.cpp"), "cimgui.cpp");
    _ = copy.addCopyFile(cimgui_dep.path("generator/output/cimgui_impl.h"), "cimgui_impl.h");

    const cimgui = b.addStaticLibrary(.{
        .name = "cimgui",
        .target = target,
        .optimize = optimize,
    });
    cimgui.step.dependOn(&copy.step);
    cimgui.linkLibC();
    cimgui.linkLibCpp();
    cimgui.addIncludePath(copy.getDirectory());
    cimgui.addIncludePath(copy.getDirectory().path(b, "imgui"));
    cimgui.addCSourceFiles(.{
        .root = copy.getDirectory(),
        .files = &.{
            "cimgui.cpp",
            "imgui/imgui.cpp",
            "imgui/imgui_tables.cpp",
            "imgui/imgui_widgets.cpp",
            "imgui/imgui_demo.cpp",
            "imgui/imgui_draw.cpp",
            "imgui/backends/imgui_impl_glfw.cpp",
            "imgui/backends/imgui_impl_vulkan.cpp",
        },
        .flags = &.{
            "-DIMGUI_IMPL_VULKAN_NO_PROTOTYPES",
            "-DCIMGUI_USE_GLFW",
            "-DCIMGUI_USE_VULKAN",
            "-DIMGUI_IMPL_API=extern \"C\"",
        },
    });
    cimgui.installHeader(copy.getDirectory().path(b, "cimgui.h"), "cimgui.h");
    cimgui.installHeader(copy.getDirectory().path(b, "cimgui_impl.h"), "cimgui_impl.h");

    cimgui.linkSystemLibrary2("glfw3", .{
        .needed = true,
        .preferred_link_mode = .static,
        .use_pkg_config = .force,
    });

    b.installArtifact(cimgui);

    const cimgui_mod = b.addModule("cimgui", .{
        .target = target,
        .optimize = optimize,
        .root_source_file = b.path("src/root.zig"),
    });
    cimgui_mod.linkLibrary(cimgui);
}
