// zig build-exe ./scripts/t.zig \
//     -femit-bin=t \
//     --cache-dir ./zig-cache/local \
//     --global-cache-dir ./zig-cache/global \
//     -O ReleaseSmall \
//     -fstrip \
//     -fno-unwind-tables \
//     -fno-error-tracing \
//     -ffunction-sections \
//     -fdata-sections \
//     --gc-sections \
//     -fno-stack-protector \
//     -fno-stack-check

// zig build-exe ./scripts/t.zig \
//     -femit-bin=t \
//     --cache-dir ./zig-cache/local \
//     --global-cache-dir ./zig-cache/global \
//     -O ReleaseFast \
//     -mcpu native \
//     -fstrip \
//     -fomit-frame-pointer \
//     -fno-stack-protector \
//     -fno-stack-check \
//     -fno-error-tracing \
//     -fno-unwind-tables \
//     -fno-sanitize-c \
//     -fno-sanitize-thread \
//     -fno-fuzz


const std = @import("std");

fn toSeconds(s: []const u8) !i32 {
    var it = std.mem.splitScalar(u8, s, ':');
    const h = try std.fmt.parseInt(i32, it.next() orelse return error.BadTime, 10);
    const m = try std.fmt.parseInt(i32, it.next() orelse return error.BadTime, 10);
    const sec = try std.fmt.parseInt(i32, it.next() orelse return error.BadTime, 10);
    if (it.next() != null) return error.BadTime;
    if (h < 0 or h > 23 or m < 0 or m > 59 or sec < 0 or sec > 59) return error.BadTime;
    return h * 3600 + m * 60 + sec;
}

pub fn main(init: std.process.Init) u8 {
    const args = init.minimal.args.toSlice(init.arena.allocator()) catch return 1;

    if (args.len != 3) {
        std.debug.print("Usage: {s} START END  (e.g. {s} 07:53:39 07:58:09)\n", .{ args[0], args[0] });
        return 1;
    }

    const start = toSeconds(args[1]) catch {
        std.debug.print("Invalid time format: {s} (expected HH:MM:SS)\n", .{args[1]});
        return 1;
    };
    const end = toSeconds(args[2]) catch {
        std.debug.print("Invalid time format: {s} (expected HH:MM:SS)\n", .{args[2]});
        return 1;
    };

    var diff = end - start;
    if (diff < 0) diff += 24 * 3600;

    const h = @divTrunc(diff, 3600);
    const m = @divTrunc(@mod(diff, 3600), 60);
    const s = @mod(diff, 60);

    std.debug.print("Elapsed: {s} -> {s}\n", .{ args[1], args[2] });
    if (h > 0) {
        std.debug.print("  {} h {} min {} s  (total {} s, {} min {} s)\n", .{ h, m, s, diff, @divTrunc(diff, 60), s });
    } else {
        std.debug.print("  {} min {} s  (total {} s)\n", .{ m, s, diff });
    }
    return 0;
}
