const std = @import("std");
const builtin = @import("builtin");
const raylib_src = @import("raylib");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{
        .default_target = if (builtin.target.os.tag == .windows)
            .{ .os_tag = .windows, .abi = .msvc }
        else
            .{},
    });

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

    const assets = b.addInstallDirectory(.{
        .source_dir = b.path("assets"),
        .install_dir = .bin,
        .install_subdir = "assets",
    });

    const shared = b.addModule("shared", .{
        .root_source_file = b.path("src/shared/shared.zig"),
        .target = target,
    });

    const client = b.addExecutable(.{
        .name = "client",
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/client/main.zig"),
            .target = target,
            .optimize = optimize,
            .imports = &.{
                .{
                    .name = "shared",
                    .module = shared,
                },
            },
        }),
        .use_llvm = true,
    });

    const server = b.addExecutable(.{
        .name = "server",
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/server/main.zig"),
            .target = target,
            .optimize = optimize,
            .imports = &.{
                .{
                    .name = "shared",
                    .module = shared,
                },
            },
        }),
        .use_llvm = true,
    });

    // tracy
    {
        const tracy = b.dependency(
            "tracy",
            .{
                .target = target,
                .optimize = optimize,
                .enable_tracy = true,
                .enable_fibers = false,
                .on_demand = false,
            },
        );
        client.root_module.addImport("tracy", tracy.module("tracy"));
    }

    // freetype
    {
        const freetype = b.dependency(
            "freetype",
            .{
                .target = target,
                .optimize = optimize,
            }
        );
        client.root_module.addImport("freetype", freetype.module("freetype"));
    }

    // kb_text_shape
    {
        client.root_module.addCSourceFile(.{
            .file = b.path("vendor/kb_text_shape/kb_text_shape.h"),
            .language = .c,
            .flags = &.{
                "-DKB_TEXT_SHAPE_IMPLEMENTATION",
                "-O3",                 // Maximum optimization
                // "-ffast-math",         // Allows algebraic reorganizations (risky for precision, great for speed)
                // "-fno-plt",            // Reduces overhead for library calls
                // "-march=native",       // Use every instruction your CPU has
                // "-flto",               // Enable LTO for the C side specifically
            },
        });
        const kb_text_shape = b.addTranslateC(.{
            .root_source_file = b.path("vendor/kb_text_shape/kb_text_shape.h"),
            .target = target,
            .optimize = optimize,
        });
        client.root_module.addImport("kb", kb_text_shape.createModule());
    }

    // stb_rect_pack
    {
        client.root_module.addCSourceFile(.{ .file = b.path("vendor/stb/stb_rect_pack.h"), .language = .c, .flags = &.{} });
        const stb_rect_pack = b.addTranslateC(.{
            .root_source_file = b.path("vendor/stb/stb_rect_pack.h"),
            .target = target,
            .optimize = optimize,
        });
        client.root_module.addImport("stb_rect_pack", stb_rect_pack.createModule());
    }

    // zmath
    {
        const zmath = b.dependency(
            "zmath",
            .{
                .target = target,
                .optimize = optimize,
            }
        );
        client.root_module.addImport("zmath", zmath.module("root"));
        server.root_module.addImport("zmath", zmath.module("root"));
        shared.addImport("zmath", zmath.module("root"));
    }


    // ENet
    {
        const enet = b.dependency("enet", .{
            .target = target,
            .optimize = optimize,
        });

        // shared.linkLibrary(enet.artifact("enet"));
        client.root_module.linkLibrary(enet.artifact("enet"));
        server.root_module.linkLibrary(enet.artifact("enet"));
    }

    // // Bufzilla
    // {
    //     const bufzilla = b.dependency(
    //     "bufzilla",
    //     .{
    //         .target = target,
    //         .optimize = optimize,
    //     });
    //     shared.addImport("bufzilla", bufzilla.module("bufzilla"));
    //     client.root_module.addImport("bufzilla", bufzilla.module("bufzilla"));
    //     server.root_module.addImport("bufzilla", bufzilla.module("bufzilla"));
    // }

    // Raylib
    {
        const raylib_dep = b.dependency("raylib", .{ .target = target, .optimize = optimize });

        const raylib_lib = raylib_dep.artifact("raylib");
        raylib_lib.root_module.addCMacro("SUPPORT_CUSTOM_FRAME_CONTROL", "");

        client.root_module.linkLibrary(raylib_lib);

        if (target.result.os.tag == .windows)
            client.root_module.linkSystemLibrary("shell32", .{ .needed = true });
    }

    client.root_module.link_libc = true;
    server.root_module.link_libc = true;

    b.installArtifact(client);
    b.installArtifact(server);

    b.getInstallStep().dependOn(&assets.step);

    const run_client_step = b.step("run-client", "Run the client");
    const run_server_step = b.step("run-server", "Run the server");

    const run_cmd_client = b.addRunArtifact(client);
    const run_cmd_server = b.addRunArtifact(server);
    run_client_step.dependOn(&run_cmd_client.step);
    run_server_step.dependOn(&run_cmd_server.step);

    run_cmd_client.step.dependOn(b.getInstallStep());
    run_cmd_server.step.dependOn(b.getInstallStep());

    if (b.args) |args| {
        run_cmd_client.addArgs(args);
        run_cmd_server.addArgs(args);
    }

    // Creates an executable that will run `test` blocks from the provided module.
    // Here `mod` needs to define a target, which is why earlier we made sure to
    // set the releative field.
    const shared_tests = b.addTest(.{
        .root_module = shared,
        .use_llvm = true,
    });

    // A run step that will run the test executable.
    const run_shared_tests = b.addRunArtifact(shared_tests);

    // Creates an executable that will run `test` blocks from the executable's
    // root module. Note that test executables only test one module at a time,
    // hence why we have to create two separate ones.
    // const exe_tests = b.addTest(.{
    //     .root_module = exe.root_module,
    // });

    // A run step that will run the second test executable.
    // const run_exe_tests = b.addRunArtifact(exe_tests);

    // A top level step for running all tests. dependOn can be called multiple
    // times and since the two run steps do not depend on one another, this will
    // make the two of them run in parallel.
    const test_step = b.step("test", "Run tests");
    test_step.dependOn(&run_shared_tests.step);
    // test_step.dependOn(&run_exe_tests.step);

    // Just like flags, top level steps are also listed in the `--help` menu.
    //
    // The Zig build system is entirely implemented in userland, which means
    // that it cannot hook into private compiler APIs. All compilation work
    // orchestrated by the build system will result in other Zig compiler
    // subcommands being invoked with the right flags defined. You can observe
    // these invocations when one fails (or you pass a flag to increase
    // verbosity) to validate assumptions and diagnose problems.
    //
    // Lastly, the Zig build system is relatively simple and self-contained,
    // and reading its source code will allow you to master it.
}

fn getRaylib(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, options: raylib_src.Options) *std.Build.Step.Compile {
    const raylib_dep = b.dependency("raylib", .{
        .target = target,
        .optimize = optimize,
        .raudio = options.raudio,
        .rmodels = options.rmodels,
        .rshapes = options.rshapes,
        .rtext = options.rtext,
        .rtextures = options.rtextures,
        .platform = options.platform,
        .linkage = options.linkage,
        .linux_display_backend = options.linux_display_backend,
        .opengl_version = options.opengl_version,
        .android_api_version = options.android_api_version,
        .android_ndk = options.android_ndk,
    });

    const raylib = raylib_dep.artifact("raylib");

    b.installArtifact(raylib);
    return raylib;
}

fn getModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module {
    if (b.modules.contains("raylib")) {
        return b.modules.get("raylib").?;
    }
    return b.addModule("raylib", .{
        .root_source_file = b.path("lib/raylib.zig"),
        .target = target,
        .optimize = optimize,
    });
}
