/*
 * Didactyl Blossom tool argument validation tests.
 */

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

#include "../src/config.h"
#include "../src/tools/tools.h"
#include "../src/tools/tools_internal.h"

static int tests_run = 0;
static int tests_passed = 0;

#define TEST_ASSERT(cond, msg) do { \
    tests_run++; \
    if (cond) { tests_passed++; printf("✅ %s\n", msg); } \
    else { printf("❌ %s\n", msg); } \
} while (0)

static int json_contains_error(const char* json, const char* needle) {
    return json && strstr(json, "\"success\":false") && strstr(json, needle);
}

static int write_file_text(const char* path, const char* text) {
    FILE* fp = fopen(path, "wb");
    if (!fp) return -1;
    size_t n = fwrite(text, 1, strlen(text), fp);
    fclose(fp);
    return (n == strlen(text)) ? 0 : -1;
}

int main(void) {
    printf("Didactyl Blossom tool validation tests\n");
    printf("======================================\n");

    didactyl_config_t cfg;
    memset(&cfg, 0, sizeof(cfg));
    snprintf(cfg.tools.shell.working_directory, sizeof(cfg.tools.shell.working_directory), "%s", ".");
    cfg.tools.blossom_max_upload_bytes = 16;
    cfg.tools.blossom_max_download_bytes = 1024;

    tools_context_t ctx;
    memset(&ctx, 0, sizeof(ctx));
    ctx.cfg = &cfg;

    char* out = execute_blossom_upload(&ctx, "{\"server\":\"http://example.com\",\"file_path\":\"README.md\"}");
    TEST_ASSERT(json_contains_error(out, "https://"), "blossom_upload rejects non-https server");
    free(out);

    const char* big_file = "tests/.tmp_blossom_big.txt";
    if (write_file_text(big_file, "this payload is intentionally larger than 16 bytes") != 0) {
        printf("❌ setup failed to create temp file\n");
        return 1;
    }

    out = execute_blossom_upload(&ctx, "{\"server\":\"https://example.com\",\"file_path\":\"tests/.tmp_blossom_big.txt\"}");
    TEST_ASSERT(json_contains_error(out, "max upload size"), "blossom_upload enforces configured upload max");
    free(out);

    const char* existing = "tests/.tmp_blossom_existing.txt";
    if (write_file_text(existing, "already here") != 0) {
        printf("❌ setup failed to create existing output file\n");
        remove(big_file);
        return 1;
    }

    out = execute_blossom_download(&ctx,
                                   "{\"server\":\"https://example.com\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"output_path\":\"tests/.tmp_blossom_existing.txt\"}");
    TEST_ASSERT(json_contains_error(out, "output_path exists"), "blossom_download requires overwrite=true when file exists");
    free(out);

    remove(big_file);
    remove(existing);

    printf("\nSummary: %d/%d passed\n", tests_passed, tests_run);
    return (tests_passed == tests_run) ? 0 : 1;
}
