const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;

const Artificer = @import("artificer");
const Api = @import("artifacts-api");

// zig fmt: off
pub const std_options = .{
    .log_scope_levels = &[_]std.log.ScopeLevel{
        .{ .scope = .api, .level = .info },
    }
};
// zig fmt: on

fn getAPITokenFromArgs(allocator: Allocator) !?[]u8 {
    const args = try std.process.argsAlloc(allocator);
    defer std.process.argsFree(allocator, args);

    if (args.len < 2) {
        return null;
    }

    const filename = args[1];
    const cwd = std.fs.cwd();
    var token_buffer: [256]u8 = undefined;
    const token = try cwd.readFile(filename, &token_buffer);

    return try allocator.dupe(u8, std.mem.trim(u8, token, "\n\t "));
}

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

    const token = (try getAPITokenFromArgs(allocator)) orelse return error.MissingToken;
    defer allocator.free(token);

    // var artificer = try Artificer.init(allocator, token);
    // defer artificer.deinit();

    var store = try Api.Store.init(allocator);
    defer store.deinit(allocator);

    var server = try Api.Server.init(allocator, &store);
    defer server.deinit();

    try server.setToken(token);

    const resources = try server.getResources(allocator, .{});
    resources.deinit();

    // var artificer = try Artificer.init(allocator, token);
    // defer artificer.deinit();

    {
        const status: Api.Status = try server.getStatus();

        const file = try std.fs.cwd().createFile("api-store.bin", .{});
        defer file.close();
        try store.save(status.version.slice(), file.writer());
    }

    // std.log.info("Prefetching server data", .{});
    // try artificer.server.prefetchCached(cache_path);

    // if (false) {
    //     std.log.info("Starting main loop", .{});
    //     while (true) {
    //         const waitUntil = artificer.nextStepAt();
    //         const duration = waitUntil - std.time.milliTimestamp();
    //         if (duration > 0) {
    //             std.time.sleep(@intCast(duration));
    //         }
    //
    //         try artificer.step();
    //     }
    // }
}
