/*
 * File: assets_campaign.h
 * Campaign loading, connectivity checks and packed level/briefing output.
 * Implementation include; compiled only through assets.c.
 */

#ifndef ASSETS_CAMPAIGN_H
#define ASSETS_CAMPAIGN_H

static void load_campaign(void)
{
    char paths[MAPS][4096];
    Node *campaign = read_json("maps/campaign.json");
    int i, j;
    for (i = 0; i < MAPS; ++i) {
        Node *entry = element(campaign, i, MAPS), *story;
        const char *name = string(member(entry, "name"));
        const char *file = string(member(entry, "file"));
        size_t length = strlen(file);
        uint8_t check[16];
        if (!*name) fail("empty mission name");
        screen_bytes(check, name, 16);
        if (length < 5 || length >= sizeof(levels[i].file) || strchr(file, '/')
            || strchr(file, '\\') || strchr(file, ':') || strcmp(file + length - 4, ".tmx"))
            fail("campaign requires local TMX filenames");
        for (j = 0; j < i; ++j)
            if (!strcmp(file, levels[j].file)) fail("duplicate campaign map: %s", file);
        strcpy(levels[i].name, name);
        strcpy(levels[i].file, file);
        story = member(entry, "story");
        for (j = 0; j < 2; ++j) {
            const char *line = string(element(story, j, 2)), *nonblank = line;
            while (*nonblank == ' ') ++nonblank;
            if (!*nonblank) fail("mission story cannot be blank");
            screen_bytes(levels[i].story + j * 32, line, 32);
        }
        {
            char maps_dir[4096];
            path_join(maps_dir, root_dir, "maps");
            path_join(paths[i], maps_dir, file);
        }
    }
    free_nodes();
    for (i = 0; i < MAPS; ++i) {
        Level decoded;
        int reached[CELLS] = {0}, queue[CELLS], head = 0, tail = 0, start = 0;
        load_map(paths[i], &decoded);
        memcpy(levels[i].terrain, decoded.terrain, CELLS);
        memcpy(levels[i].units, decoded.units, sizeof(decoded.units));
        levels[i].count = decoded.count; levels[i].cash = decoded.cash;
        for (j = 0; j < CELLS; ++j)
            if (decoded.terrain[j] == 7) start = j;
        queue[tail++] = start; reached[start] = 1;
        while (head < tail) {
            int pos = queue[head++], offsets[4] = {-16,1,16,-1}, d;
            for (d = 0; d < 4; ++d) {
                int next = pos + offsets[d];
                if (next < 0 || next >= CELLS || (d == 1 && pos % 16 == 15)
                    || (d == 3 && pos % 16 == 0) || reached[next]
                    || move_cost[decoded.terrain[next]] == 255) continue;
                reached[next] = 1; queue[tail++] = next;
            }
        }
        for (j = 0; j < CELLS; ++j)
            if (decoded.terrain[j] == 8 && !reached[j]) fail("%s: HQs are disconnected", paths[i]);
        for (j = 0; j < decoded.count; ++j)
            if (decoded.units[2][j] != 4 && !reached[decoded.units[1][j] * 16 + decoded.units[0][j]])
                fail("%s: ground unit is disconnected", paths[i]);
    }
}

static size_t pack_level(const uint8_t *raw, size_t size, uint8_t out[389])
{
    uint8_t packed[387];
    size_t length;
    if (size != 386 || raw[0] < 2 || raw[0] > 16 || raw[385] > 99)
        fail("level needs unit count 2..16, 384 payload bytes and starting cash 0..99");
    length = pack_bits(raw + 1, 384, packed);
    out[0] = (uint8_t)(raw[0] | (length < 384 ? 128 : 0)); out[1] = raw[385];
    if (length < 384) memcpy(out + 2, packed, length);
    else { length = 384; memcpy(out + 2, raw + 1, length); }
    return length + 2;
}

static void write_campaign(void)
{
    uint8_t stories[MAPS * 64];
    FILE *f = output("generated/levels.i", "w");
    int i, j, k;
    size_t total = 0;
    fprintf(f, "MAP_COUNT = %d\n\nlevelLow\n\t.byte\t", MAPS);
    for (i = 0; i < MAPS; ++i) fprintf(f, "%s<level%d", i ? "," : "", i);
    fputs("\n\nlevelHigh\n\t.byte\t", f);
    for (i = 0; i < MAPS; ++i) fprintf(f, "%s>level%d", i ? "," : "", i);
    fputs("\n\nlevelNames\n", f);
    {
        uint8_t names[MAPS * 16];
        for (i = 0; i < MAPS; ++i) screen_bytes(names + i * 16, levels[i].name, 16);
        byte_table(f, names, sizeof(names));
    }
    for (i = 0; i < MAPS; ++i) {
        uint8_t raw[386], packed[389];
        char name[128];
        size_t size;
        terrain_graphics(&levels[i]);
        raw[0] = (uint8_t)levels[i].count;
        memcpy(raw + 1, levels[i].terrain, CELLS); memcpy(raw + 161, levels[i].display, CELLS);
        for (j = 0; j < 4; ++j)
            for (k = 0; k < 16; ++k) raw[321 + j * 16 + k] = levels[i].units[j][k];
        raw[385] = (uint8_t)levels[i].cash;
        size = pack_level(raw, sizeof(raw), packed); total += size;
        snprintf(name, sizeof(name), "generated/level%02d.rle", i + 1);
        write_bytes(name, packed, size);
        fprintf(f, "level%d ins\t\"%s\"\n\n", i, name);
        memcpy(stories + i * 64, levels[i].story, 64);
    }
    close_file(f);
    write_bytes("generated/briefings-main.bin", stories, 7 * 64);
    write_bytes("generated/briefings-extra.bin", stories + 7 * 64, 5 * 64);
    f = output("generated/briefings.i", "w");
    for (j = 0; j < 2; ++j) {
        fprintf(f, "briefing%s\n\t.byte\t", j ? "High" : "Low");
        for (i = 0; i < MAPS; ++i)
            fprintf(f, "%s%c(briefing%s+%d)", i ? "," : "", j ? '>' : '<',
                    i < 7 ? "Main" : "Extra", (i < 7 ? i : i - 7) * 64);
        fputs("\n\n", f);
    }
    fputs("briefingExtra ins\t\"generated/briefings-extra.bin\"\n\n"
          "briefingLabels ins\t\"generated/briefing-labels.bin\"\n\n", f);
    close_file(f);
    printf("Compiled %d campaign maps: %zu/%d map bytes\n", MAPS, total, MAPS * 386);
}

#endif
