/*
 * File: assets.c
 * AtariWars C asset-generator entry point and shared file/text helpers.
 * Parser, graphics, campaign, preview and UI implementations live in
 * dedicated includes below; no external libraries are required.
 *
 * Usage: assets [--root PROJECT] | --pack-level INPUT OUTPUT
 */

#ifndef _WIN32
#define _XOPEN_SOURCE 700
#endif
#define _CRT_SECURE_NO_WARNINGS
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#ifdef _WIN32
#include <direct.h>
#define mkdir_one(path) _mkdir(path)
#define full_path(out, path) _fullpath(out, path, 4096)
#define path_compare _stricmp
#else
#include <unistd.h>
#define mkdir_one(path) mkdir(path, 0777)
#define full_path(out, path) realpath(path, out)
#define path_compare strcmp
#endif
#include "../../Assembler/gen/gfxPack.h"
#include "../../Assembler/gen/packBits.h"

enum { MAPS = 12, CELLS = 160, ART = 23, TILES = 55 };
typedef uint8_t Tile[16][8];
typedef struct {
    uint8_t terrain[CELLS], display[CELLS], units[4][16];
    int count, cash;
    char name[17], file[128];
    uint8_t story[64];
} Level;

static char root_dir[4096] = ".";
static Tile pixels[ART], graphics[TILES];
static uint8_t opacity[ART][16][8], lights[6][16];
static uint8_t palette[4][3], raster_rgb[4][4][3], light_rgb[3];
static uint8_t atari[4], orange[4], blue[4], title_colors[16], light_color, cursor_color;
static const int unit_art[2][6] = {{10,11,12,16,18,19}, {13,14,15,17,20,21}};
static const int move_cost[11] = {1,1,255,1,2,255,1,1,1,1,1};
static Level levels[MAPS], test_level;

_Noreturn static void fail(const char *format, ...)
{
    va_list args;
    fputs("assets: ", stderr);
    va_start(args, format);
    vfprintf(stderr, format, args);
    va_end(args);
    fputc('\n', stderr);
    exit(EXIT_FAILURE);
}

static void *allocate(size_t size)
{
    void *p = calloc(size ? size : 1, 1);
    if (!p) fail("out of memory");
    return p;
}

static char *slice(const char *p, size_t length)
{
    char *out = allocate(length + 1);
    memcpy(out, p, length);
    return out;
}

static void path_join(char out[4096], const char *base, const char *name)
{
    if (snprintf(out, 4096, "%s/%s", base, name) >= 4096)
        fail("path too long: %s", name);
}

static FILE *open_file(const char *path, const char *mode)
{
    FILE *f = fopen(path, mode);
    if (!f) fail("%s: %s", path, strerror(errno));
    return f;
}

static void close_file(FILE *f)
{
    if (ferror(f)) fail("file I/O failed");
    if (fclose(f)) fail("closing file failed: %s", strerror(errno));
}

static char *read_file(const char *path, size_t *size)
{
    FILE *f = open_file(path, "rb");
    long length;
    char *out;
    if (fseek(f, 0, SEEK_END) || (length = ftell(f)) < 0 || length > 4 * 1024 * 1024)
        fail("%s: input too large or not seekable", path);
    rewind(f);
    out = allocate((size_t)length + 1);
    if (fread(out, 1, (size_t)length, f) != (size_t)length)
        fail("%s: incomplete read", path);
    close_file(f);
    *size = (size_t)length;
    return out;
}

static FILE *output(const char *name, const char *mode)
{
    char path[4096];
    FILE *f;
    path_join(path, root_dir, name);
    f = open_file(path, mode);
    if (strlen(name) > 2 && !strcmp(name + strlen(name) - 2, ".i")) {
        const char *base = strrchr(name, '/');
        fprintf(f, "; AtariWars - generated %s; do not edit.\n\n", base ? base + 1 : name);
    }
    return f;
}

static void write_bytes(const char *name, const void *data, size_t size)
{
    FILE *f = output(name, "wb");
    if (fwrite(data, 1, size, f) != size) fail("%s: incomplete write", name);
    close_file(f);
}

static int art_kind(int index, int *team)
{
    int t, k;
    for (t = 0; t < 2; ++t)
        for (k = 0; k < 6; ++k)
            if (unit_art[t][k] == index) {
                *team = t;
                return k;
            }
    return -1;
}

static void screen_bytes(uint8_t *out, const char *text, int width)
{
    size_t len = strlen(text);
    int i;
    if (len > (size_t)width) fail("screen text exceeds %d columns: %s", width, text);
    for (i = 0; i < width; ++i) {
        unsigned char c = i < (int)len ? (unsigned char)text[i] : ' ';
        if (c < 32 || c > 95) fail("screen text requires uppercase ASCII: %s", text);
        out[i] = (uint8_t)(c - 32);
    }
}

static void byte_table(FILE *f, const uint8_t *data, int count)
{
    int i;
    fputs("\t.byte\t", f);
    for (i = 0; i < count; ++i) fprintf(f, "%s%u", i ? "," : "", data[i]);
    fputs("\n\n", f);
}

/* Include order follows the parser and writer dependencies. */
#include "assets_parser.h"
#include "assets_json.h"
#include "assets_tmx.h"
#include "assets_graphics.h"
#include "assets_campaign.h"
#include "assets_preview.h"
#include "assets_ui.h"

int main(int argc, char **argv)
{
    char path[4096];
    int i;
    if (argc == 4 && !strcmp(argv[1], "--pack-level")) {
        size_t size, length;
        char *raw = read_file(argv[2], &size);
        uint8_t packed[389];
        FILE *f;
        length = pack_level((const uint8_t *)raw, size, packed);
        f = open_file(argv[3], "wb");
        if (fwrite(packed, 1, length, f) != length) fail("incomplete packed-level write");
        close_file(f); free(raw);
        return 0;
    }
    for (i = 1; i < argc; ++i) {
        if (!strcmp(argv[i], "--root") && i + 1 < argc) {
            if (!full_path(root_dir, argv[++i])) fail("invalid project root: %s", argv[i]);
        } else fail("usage: assets [--root PROJECT] | --pack-level INPUT OUTPUT");
    }
    path_join(path, root_dir, "generated");
    if (mkdir_one(path) && errno != EEXIST) fail("%s: %s", path, strerror(errno));
    load_art();
    load_campaign();
    path_join(path, root_dir, "maps/testlevel.tmx");
    load_map(path, &test_level);
    write_graphics();
    write_ui();
    write_campaign();
    write_title();
    write_previews();
    puts("Compiled 55 tiles, 16x10 terrain; C asset pipeline");
    return 0;
}
