#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>

std::string get_word_from_qs() {
    const char* qs = std::getenv("QUERY_STRING");
    if (!qs) return "";
    std::string s(qs);
    auto pos = s.find("word=");
    if (pos == std::string::npos) return "";
    return s.substr(pos + 5);
}

int main(){
    // CGI header
    std::cout << "Content-Type: text/html\r\n\r\n";

    std::string word = get_word_from_qs();
    if (word.empty()) {
        std::cout << "<p>Please enter a word.</p>";
        return 0;
    }

    // Very basic HTML-escape of '<' and '>'
    for (auto& c : word) {
        if (c == '<') c = '?';
        if (c == '>') c = '?';
    }

    // Build and run curl command
    std::string cmd = "curl -s \"https://api.dictionaryapi.dev/api/v2/entries/en/" + word + "\"";
    FILE* pipe = popen(cmd.c_str(), "r");
    if (!pipe) {
        std::cout << "<p>Failed to fetch definition.</p>";
        return 1;
    }

    // Output the raw JSON inside <pre>
    std::cout << "<!DOCTYPE html><html><body>";
    std::cout << "<h2>Definitions for:&nbsp;" << word << "</h2>";
    std::cout << "<pre>";
    char buf[256];
    while (fgets(buf, sizeof(buf), pipe)) {
        std::cout << buf;
    }
    std::cout << "</pre></body></html>";
    pclose(pipe);
    return 0;
}