const std = @import("std");

pub fn find_blocks(src: []const u8, blocks: *std.ArrayList([]const u8)) !void {
    var idx: usize = 0;
    var blk: usize = 0;

    while (idx < src.len) {
        const end = std.mem.indexOfAnyPos(u8, src, idx, "\n") orelse src.len;
        const line = src[idx..end];
        if (std.mem.indexOfNone(u8, line, " \t\r\n") == null) {
            // the line is blank; a block has ended.
            const block = src[blk..end];

            std.debug.print("BLOCK:\n{s}", .{block});

            try blocks.append(block);
            blk = end + 1;
        }
        idx = end + 1;
    }
}

pub fn convert(alloc: std.mem.Allocator, md: []const u8) ![]const u8 {
    return try alloc.dupe(u8, md);

    // _ = alloc;
    // _ = md;
    // return error.UhOh;
    // return error.NotImplemented;

    // return alloc.dupe(u8, "Hello World!");
}

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const alloc = gpa.allocator();

    defer _ = gpa.deinit();

    var args = try std.process.argsWithAllocator(alloc);
    defer args.deinit();
    std.debug.assert(args.skip());

    var blocks = std.ArrayList([]const u8).init(alloc);
    defer blocks.deinit();

    while (args.next()) |fname| {
        const src = load: {
            const file = try std.fs.cwd().openFile(fname, .{ .mode = .read_only });
            defer file.close();
            break :load try file.readToEndAlloc(alloc, std.math.maxInt(u32));
        };
        defer alloc.free(src);

        std.log.debug("arg '{s}' {d} bytes", .{ fname, src.len });

        blocks.clearRetainingCapacity();
        try find_blocks(src, &blocks);

        // try parse(alloc, src);

        // const tokens = try parse(alloc, src);
        // defer alloc.free(tokens);
    }
}
