const std = @import("std");

fn jsonGetString(obj: std.json.ObjectMap, key: []const u8) ?[]const u8 {
    const v_opt = obj.get(key);
    if (v_opt == null) {
        return null;
    }
    const v = v_opt.?;
    if (v != .string) {
        return null;
    }
    return v.string;
}

fn jsonGetInt(obj: std.json.ObjectMap, key: []const u8) ?i64 {
    const v_opt = obj.get(key);
    if (v_opt == null) {
        return null;
    }
    const v = v_opt.?;
    if (v != .integer) {
        return null;
    }
    return v.integer;
}

pub fn formatPrewarmFromStatusRoot(allocator: std.mem.Allocator, root: std.json.ObjectMap) !?[]u8 {
    const prewarm_val_opt = root.get("prewarm");
    if (prewarm_val_opt == null) {
        return null;
    }
    const prewarm_val = prewarm_val_opt.?;
    if (prewarm_val != .array) {
        return null;
    }

    const items = prewarm_val.array.items;
    if (items.len == 0) {
        return null;
    }

    var out = std.ArrayList(u8){};
    errdefer out.deinit(allocator);

    const writer = out.writer(allocator);
    try writer.writeAll("Prewarm:\n");

    for (items) |item| {
        if (item != .object) {
            continue;
        }

        const obj = item.object;

        const worker_id = jsonGetString(obj, "worker_id") orelse "";
        const task_id = jsonGetString(obj, "task_id") orelse "";
        const phase = jsonGetString(obj, "phase") orelse "";
        const started_at = jsonGetString(obj, "started_at") orelse "";
        const dataset_count = jsonGetInt(obj, "dataset_count") orelse 0;
        const snapshot_id = jsonGetString(obj, "snapshot_id") orelse "";
        const env_image = jsonGetString(obj, "env_image") orelse "";
        const env_hit = jsonGetInt(obj, "env_hit") orelse 0;
        const env_miss = jsonGetInt(obj, "env_miss") orelse 0;
        const env_built = jsonGetInt(obj, "env_built") orelse 0;

        try writer.print(
            "  worker={s} task={s} phase={s} datasets={d} snapshot={s} env={s} env_hit={d} env_miss={d} env_built={d} started={s}\n",
            .{ worker_id, task_id, phase, dataset_count, snapshot_id, env_image, env_hit, env_miss, env_built, started_at },
        );
    }

    const owned = try out.toOwnedSlice(allocator);
    return owned;
}
