// The tools Qwen can call, run by the RV32 CPU compiled into Qwenputer's weights.
//
// Each run (GO, after </tool_call>) reads the call Qwen wrote from the text buffer (its i-th token's
// bytes at 0x8000 + 16 i, at most 80 tokens), runs the function it names and prints the tool
// response in upstream's framing, then parks (exit ecall) until the next call:
//   \n<tool_response>\nRESULT\n</tool_response>\n<think>\n\n</think>\n   (+ the HALT echo \n)
// calc is upstream's calc.c (github.com/divagr18/qwenputer, MIT), unchanged. RAM survives between
// calls, so the Life grid stays where the last call left it.
#define main calc_main
#include "calc.c"
#undef main

#include <string.h>

#define CALL_TEXT ((const volatile unsigned char *)0x8000)
#define CALL_ROWS 80
#define SIZE 32  // the Life grid: SIZE rows of one 32-bit word, a torus
#define MAX_GENERATIONS 60

enum { TOOL_RESPONSE = 256, TOOL_RESPONSE_END, THINK, THINK_END };

static char call[16 * CALL_ROWS + 1];
uint32_t screen[SIZE];  // the grid, a named symbol so the front panel can draw it
static uint32_t next[SIZE], left[SIZE], right[SIZE];

static const char *const DAYS[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
                                   "Friday", "Saturday"};

static const struct pattern {
    const char *name;
    int height;
    const char *rows[13];
} PATTERNS[] = {
    {"glider", 3, {".O.", "..O", "OOO"}},
    {"lwss", 4, {".O..O", "O....", "O...O", "OOOO."}},
    {"rpentomino", 3, {".OO", "OO.", ".O."}},
    {"acorn", 3, {".O.....", "...O...", "OO..OOO"}},
    {"diehard", 3, {"......O.", "OO......", ".O...OOO"}},
    {"pulsar", 13, {"..OOO...OOO..", ".............", "O....O.O....O", "O....O.O....O",
                    "O....O.O....O", "..OOO...OOO..", ".............", "..OOO...OOO..",
                    "O....O.O....O", "O....O.O....O", "O....O.O....O", ".............",
                    "..OOO...OOO.."}},
};

static void emit(int c) { rv_ecall2(1, c, 0, 0); }

static void say(const char *s) {
    while (*s) emit(*s++);
}

static void say_int(int v) {
    char digits[12];
    int n = 0;
    unsigned u = v < 0 ? -(unsigned)v : (unsigned)v;
    if (v < 0) emit('-');
    do digits[n++] = '0' + u % 10; while (u /= 10);
    while (n) emit(digits[--n]);
}

// The call's text: every captured token's bytes, in order.
static void read_call(void) {
    int n = 0;
    for (int i = 1; i <= CALL_ROWS && CALL_TEXT[16 * i]; i++)
        for (int k = 0; k < 16 && CALL_TEXT[16 * i + k]; k++) call[n++] = CALL_TEXT[16 * i + k];
    call[n] = 0;
}

// The text between `open` and `close`, without the newlines Qwen puts around it; -1 if missing.
static int between(const char *open, const char *close, char *out, int cap) {
    const char *p = strstr(call, open), *e;
    if (!p) return -1;
    p += strlen(open);
    if (*p == '\n') p++;
    if (!(e = strstr(p, close))) return -1;
    if (e > p && e[-1] == '\n') e--;
    int n = e - p < cap - 1 ? e - p : cap - 1;
    memcpy(out, p, n);
    out[n] = 0;
    return n;
}

static int param(const char *name, char *out, int cap) {
    char open[40] = "<parameter=";
    strcat(strcat(open, name), ">");
    return between(open, "</parameter>", out, cap);
}

// --- letters ---------------------------------------------------------------------------------
// The text spelled out, then how often each letter a-z occurs (any case), most frequent first.
static void letters(const char *s) {
    int count[26] = {0}, total = 0, most = 0;
    for (const char *p = s; *p; p++) {
        if (p != s && ((unsigned char)*p & 0xC0) != 0x80) emit(' ');  // not inside a UTF-8 char
        emit(*p == ' ' ? '_' : *p);
        int c = *p | 0x20;
        if (c >= 'a' && c <= 'z') {
            total++;
            if (++count[c - 'a'] > most) most = count[c - 'a'];
        }
    }
    emit('\n');
    say_int(total);
    say(total == 1 ? " letter" : " letters");
    for (int k = most, first = 1; k > 0; k--)
        for (int c = 0; c < 26; c++)
            if (count[c] == k) {
                say(first ? ": " : ", ");
                emit('a' + c);
                emit(' ');
                say_int(k);
                first = 0;
            }
    emit('\n');
}

// --- dates -----------------------------------------------------------------------------------
// YYYY-MM-DD (proleptic Gregorian, years 1-9999) as days since 1970-01-01; 0 if it isn't a date.
static int parse_date(const char *s, int *days) {
    int part[3] = {0}, k = 0, digits = 0;
    for (; *s && k < 3; s++) {
        if (*s >= '0' && *s <= '9') {
            part[k] = part[k] * 10 + *s - '0';
            if (++digits > 4) return 0;
        } else if (*s == '-' && digits && k < 2) {
            k++;
            digits = 0;
        } else {
            return 0;
        }
    }
    int y = part[0], m = part[1], d = part[2];
    int leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
    int month_days = m == 2 ? 28 + leap : 30 + ((m + (m > 7)) & 1);
    if (k != 2 || !digits || y < 1 || m < 1 || m > 12 || d < 1 || d > month_days) return 0;
    y -= m <= 2;  // days_from_civil (H. Hinnant): years start in March
    int era = y / 400, yoe = y - era * 400;
    int doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
    *days = era * 146097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719468;
    return 1;
}

static void weekday(const char *date) {
    int days;
    if (!parse_date(date, &days)) {
        say("error: give the date as YYYY-MM-DD\n");
        return;
    }
    say(DAYS[((days % 7) + 11) % 7]);  // 1970-01-01 was a Thursday
    emit('\n');
}

static void days_between(const char *start, const char *end) {
    int a, b;
    if (!parse_date(start, &a) || !parse_date(end, &b)) {
        say("error: give the dates as YYYY-MM-DD\n");
        return;
    }
    say_int(b - a);
    say(" days\n");
}

// --- life ------------------------------------------------------------------------------------
static int same_name(const char *a, const char *b) {  // ignoring case, spaces, '-' and '_'
    for (;; a++, b++) {
        while (*a == ' ' || *a == '-' || *a == '_') a++;
        while (*b == ' ' || *b == '-' || *b == '_') b++;
        if ((*a | 0x20) != (*b | 0x20)) return 0;
        if (!*a) return 1;
    }
}

static uint32_t rotl(uint32_t x) { return x << 1 | x >> 31; }
static uint32_t rotr(uint32_t x) { return x >> 1 | x << 31; }

// One generation, 32 cells per word: the 8 neighbours of every cell are added with bitwise full
// adders into ones (o0) and twos (u1 + w1 + m1 + k1), and a cell lives on with exactly one two
// (2 or 3 neighbours) and either a one (3) or a live cell (2).
static void step(void) {
    for (int y = 0; y < SIZE; y++) {
        left[y] = rotl(screen[y]);
        right[y] = rotr(screen[y]);
    }
    for (int y = 0; y < SIZE; y++) {
        int up = (y + SIZE - 1) % SIZE, down = (y + 1) % SIZE;
        uint32_t t = left[up] ^ screen[up];
        uint32_t u0 = t ^ right[up], u1 = (left[up] & screen[up]) | (right[up] & t);
        t = left[down] ^ screen[down];
        uint32_t w0 = t ^ right[down], w1 = (left[down] & screen[down]) | (right[down] & t);
        uint32_t m0 = left[y] ^ right[y], m1 = left[y] & right[y];
        t = u0 ^ w0;
        uint32_t o0 = t ^ m0, k1 = (u0 & w0) | (m0 & t);
        uint32_t one_two = (u1 ^ w1 ^ m1 ^ k1) & ~(u1 & w1) & ~(m1 & k1);
        next[y] = one_two & (o0 | screen[y]);
    }
    for (int y = 0; y < SIZE; y++) screen[y] = next[y];
}

static void life(const char *name, const char *generations) {
    const struct pattern *p = 0;
    for (unsigned i = 0; i < sizeof PATTERNS / sizeof *PATTERNS; i++)
        if (same_name(name, PATTERNS[i].name)) p = &PATTERNS[i];
    if (!p) {
        say("error: pattern is one of glider, lwss, r-pentomino, acorn, diehard, pulsar\n");
        return;
    }
    int n = 0;
    for (const char *s = generations; *s; s++) {
        if (*s < '0' || *s > '9' || (n = n * 10 + *s - '0') > MAX_GENERATIONS) {
            say("error: generations is a whole number from 0 to 60\n");
            return;
        }
    }
    int width = strlen(p->rows[0]), top = (SIZE - p->height) / 2, col = (SIZE - width) / 2;
    for (int y = 0; y < SIZE; y++) screen[y] = 0;
    for (int y = 0; y < p->height; y++)
        for (int x = 0; x < width; x++)
            if (p->rows[y][x] == 'O') screen[top + y] |= 1u << (31 - col - x);
    for (int g = 0; g < n; g++) step();
    int alive = 0;
    for (int y = 0; y < SIZE; y++)
        for (uint32_t w = screen[y]; w; w &= w - 1) alive++;
    say_int(alive);
    say(" cells alive after ");
    say_int(n);
    say(n == 1 ? " generation\n" : " generations\n");
}

// --- the bridge ------------------------------------------------------------------------------
static void dispatch(void) {
    char tool[24], a[128], b[128];
    if (!strstr(call, "</function>")) {
        say("error (too long: split it)\n");
        return;
    }
    if (between("<function=", ">", tool, sizeof tool) < 0) {
        say("error: no function\n");
        return;
    }
    if (!strcmp(tool, "calc") && param("expression", calc_in, sizeof calc_in) >= 0) {
        calc_eval();
    } else if (!strcmp(tool, "letters") && param("text", a, sizeof a) >= 0) {
        letters(a);
    } else if (!strcmp(tool, "weekday") && param("date", a, sizeof a) >= 0) {
        weekday(a);
    } else if (!strcmp(tool, "days_between") && param("start", a, sizeof a) >= 0
               && param("end", b, sizeof b) >= 0) {
        days_between(a, b);
    } else if (!strcmp(tool, "life") && param("pattern", a, sizeof a) >= 0
               && param("generations", b, sizeof b) >= 0) {
        life(a, b);
    } else {
        say("error: unknown tool or missing parameter\n");
    }
}

int main(void) {
    for (;;) {
        rv_ecall2(93, 0, 0, 0);  // park: HALT; the next GO resumes here
        read_call();
        emit('\n');
        emit(TOOL_RESPONSE);
        emit('\n');
        dispatch();
        emit(TOOL_RESPONSE_END);
        emit('\n');
        emit(THINK);
        emit('\n');
        emit('\n');
        emit(THINK_END);
        emit('\n');
    }
}
