const std = @import("std");

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

    // SQLite compile flags for optimal embedded use
    const sqlite_flags: []const []const u8 = &.{
        "-DSQLITE_DQS=0", // Disable double-quoted strings as identifiers
        "-DSQLITE_THREADSAFE=0", // Single-threaded for speed
        "-DSQLITE_DEFAULT_MEMSTATUS=0", // Disable memory usage tracking
        "-DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1", // Normal WAL sync
        "-DSQLITE_LIKE_DOESNT_MATCH_BLOBS", // LIKE doesn't match BLOBs
        "-DSQLITE_OMIT_DEPRECATED", // Remove deprecated APIs
        "-DSQLITE_OMIT_SHARED_CACHE", // No shared cache
        "-DSQLITE_ENABLE_FTS5", // Full-text search v5
        "-DSQLITE_ENABLE_JSON1", // JSON functions
        "-DSQLITE_ENABLE_RTREE", // R-Tree for geospatial
        "-DSQLITE_OMIT_LOAD_EXTENSION", // No dynamic extensions
    };

    // zsqlite module - includes SQLite C compilation
    const zsqlite_mod = b.createModule(.{
        .root_source_file = b.path("src/root.zig"),
        .target = target,
        .optimize = optimize,
        .link_libc = true,
    });
    zsqlite_mod.addIncludePath(b.path("vendor"));
    zsqlite_mod.addCSourceFile(.{
        .file = b.path("vendor/sqlite3.c"),
        .flags = sqlite_flags,
    });

    // Tests
    const unit_tests = b.addTest(.{
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/root.zig"),
            .target = target,
            .optimize = optimize,
            .link_libc = true,
        }),
    });
    unit_tests.root_module.addIncludePath(b.path("vendor"));
    unit_tests.root_module.addCSourceFile(.{
        .file = b.path("vendor/sqlite3.c"),
        .flags = sqlite_flags,
    });

    const run_unit_tests = b.addRunArtifact(unit_tests);
    const test_step = b.step("test", "Run unit tests");
    test_step.dependOn(&run_unit_tests.step);

    // Example: basic
    const basic_exe = b.addExecutable(.{
        .name = "basic",
        .root_module = b.createModule(.{
            .root_source_file = b.path("examples/basic.zig"),
            .target = target,
            .optimize = optimize,
            .imports = &.{
                .{ .name = "zsqlite", .module = zsqlite_mod },
            },
        }),
    });
    b.installArtifact(basic_exe);

    const run_basic = b.addRunArtifact(basic_exe);
    run_basic.step.dependOn(b.getInstallStep());
    const basic_step = b.step("basic", "Run basic example");
    basic_step.dependOn(&run_basic.step);
}
