#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define FILE_PATH "/srv/http/work_orders_debug.json"
#define TEMP_PATH "/srv/http/work_orders_debug_tmp.json"

void update_bezig_field(char *block, int bezig) {
    char *bezig_pos = strstr(block, "\"bezig\"");
    if (bezig_pos) {
        // Update existing value
        char *colon = strchr(bezig_pos, ':');
        if (colon) {
            char *after = colon + 1;
            while (*after == ' ' || *after == '\t') after++;
            char *end = after;
            while (*end && *end != ',' && *end != '}') end++;

            // Overwrite safely
            char new_block[4096];
            int prefix_len = after - block;
            strncpy(new_block, block, prefix_len);
            new_block[prefix_len] = '\0';

            snprintf(new_block + prefix_len, sizeof(new_block) - prefix_len, "%s%s",
                     bezig ? "true" : "false", end);

            strncpy(block, new_block, 4095);
            block[4095] = '\0';
        }
    } else {
        // Insert field before last }
        char *last_brace = strrchr(block, '}');
        if (last_brace) {
            int needs_comma = *(last_brace - 1) != '{';  // check if existing field exists
            *last_brace = '\0';
            snprintf(last_brace, 4096 - (last_brace - block),
                     "%s%s\"bezig\": %s\n  }",
                     needs_comma ? ",\n  " : "",
                     "", bezig ? "true" : "false");
        }
    }
}

int main(void) {
    printf("Content-Type: text/plain\r\n\r\n");

    char *len_str = getenv("CONTENT_LENGTH");
    int len = len_str ? atoi(len_str) : 0;
    if (len <= 0 || len > 1024) {
        printf("Ongeldige invoer");
        return 1;
    }

    char post[1025] = {0};
    fread(post, 1, len, stdin);
    post[len] = '\0';

    int id = 0, bezig = 0;
    sscanf(post, "id=%d&bezig=%d", &id, &bezig);
    if (id <= 0) {
        printf("Ongeldig ID");
        return 1;
    }

    FILE *in = fopen(FILE_PATH, "r");
    if (!in) {
        printf("Kan JSON-bestand niet openen");
        return 1;
    }

    char json[65536];
    size_t size = fread(json, 1, sizeof(json) - 1, in);
    fclose(in);
    json[size] = '\0';

    FILE *out = fopen(TEMP_PATH, "w");
    if (!out) {
        printf("Kan tijdelijk bestand niet schrijven");
        return 1;
    }

    fprintf(out, "[\n");
    char *p = json;
    int first = 1;

    while ((p = strchr(p, '{'))) {
        char *end = p;
        int depth = 0;
        while (*end) {
            if (*end == '{') depth++;
            else if (*end == '}') depth--;
            if (depth == 0) break;
            end++;
        }
        if (depth != 0 || !*end) break;

        char block[4096];
        int block_len = end - p + 1;
        strncpy(block, p, block_len);
        block[block_len] = '\0';

        int current_id = 0;
        if (sscanf(strstr(block, "\"id\""), "\"id\": %d", &current_id) != 1) {
            p = end + 1;
            continue;
        }

        if (current_id == id) {
            update_bezig_field(block, bezig);
        }

        if (!first) fprintf(out, ",\n");
        fprintf(out, "  %s", block);
        first = 0;

        p = end + 1;
    }

    fprintf(out, "\n]\n");
    fclose(out);

    rename(TEMP_PATH, FILE_PATH);
    printf("OK");
    return 0;
}
