#include "arkita-extension-v1.h"

#include <array>
#include <charconv>
#include <cmath>
#include <optional>
#include <string>

namespace {

const ArkitaExtensionHostV1 *arkita;

struct Target {
    std::string host;
    std::array<double, 3> position, normal;
};
struct DoorTool {
    std::string definition, input;
    std::optional<Target> target;
    double width = .9, height = 2.04;
} tool;


std::string number(double value) {
    std::array<char, 32> text{};
    const auto result = std::to_chars(text.data(), text.data() + text.size(), value);
    return {text.data(), result.ptr};
}

std::string vectorJson(const std::array<double, 3> &point) {
    return "[" + number(point[0]) + "," + number(point[1]) + "," + number(point[2]) + "]";
}

std::string placementJson(const Target &target) {
    // The identifiers here come directly from Arkita and contain only ASCII letters, digits, underscores and hyphens.
    return "{\"definitionId\":\"" + tool.definition + "\",\"punchHostId\":\"" + target.host +
        "\",\"position\":" + vectorJson(target.position) + ",\"punchNormal\":" + vectorJson(target.normal) +
        ",\"options\":{\"DoorWidth\":" + number(tool.width) + ",\"DoorHeight\":" + number(tool.height) + "}}";
}

void message(const std::string &text) { arkita->show_message(arkita->context, text.c_str()); }

void prompt() {
    message(tool.input.empty() ? "Porte " + number(tool.width) + " m × " + number(tool.height) +
        " m · Visez un mur. Saisissez largeur x hauteur puis Entrée."
        : "Dimensions · " + tool.input + " · Entrée pour appliquer.");
}

bool applyDimensions() {
    if (tool.input.empty())
        return true;
    const auto separator = tool.input.find_first_of("xX;");
    double width, height;
    if (separator == std::string::npos ||
        !arkita->parse_length(arkita->context, tool.input.substr(0, separator).c_str(), &width) ||
        !arkita->parse_length(arkita->context, tool.input.substr(separator + 1).c_str(), &height) ||
        !(width > 0 && height > 0)) {
        message("Saisissez deux longueurs positives, par exemple 900 mm x 2040 mm.");
        return false;
    }
    tool.width = width;
    tool.height = height;
    tool.input.clear();
    prompt();
    return true;
}

void preview() {
    if (!tool.target) {
        arkita->preview_punch_component(arkita->context, nullptr);
        return;
    }
    const auto request = placementJson(*tool.target);
    arkita->preview_punch_component(arkita->context, request.c_str());
}

void viewportEvent(void *, const ArkitaViewportEventV1 *event) {
    switch (event->kind) {
    case ARKITA_VIEWPORT_MOVE_V1:
    case ARKITA_VIEWPORT_CLICK_V1:
        tool.target.reset();
        if (const auto *wall = event->wall; wall && std::abs(wall->inward_normal[2]) <= 1e-6) {
            const auto *point = wall->position;
            const auto *normal = wall->inward_normal;
            tool.target = Target{wall->occurrence_id, {point[0], point[1], point[2]}, {normal[0], normal[1], normal[2]}};
        }
        if (event->kind == ARKITA_VIEWPORT_MOVE_V1) {
            preview();
            return;
        }
        if (!tool.target) {
            message("Visez une face verticale d’un mur solide.");
            return;
        }
        if (!applyDimensions())
            return;
        if (arkita->place_punch_component(arkita->context, placementJson(*tool.target).c_str(), nullptr, nullptr)) {
            arkita->finish_viewport_tool(arkita->context);
            message("Porte posée et mur percé. Un seul Ctrl+Z annule la pose.");
        } else {
            message("La porte ne tient pas à cet endroit ou ses options de largeur et de hauteur sont indisponibles.");
        }
        return;
    case ARKITA_VIEWPORT_TEXT_V1:
        if (tool.input.size() < 100 && event->text) {
            tool.input += event->text;
            prompt();
        }
        return;
    case ARKITA_VIEWPORT_BACKSPACE_V1:
        if (!tool.input.empty()) {
            size_t last = tool.input.size() - 1;
            while (last && (static_cast<unsigned char>(tool.input[last]) & 0xc0) == 0x80)
                --last;
            tool.input.resize(last);
        }
        prompt();
        return;
    case ARKITA_VIEWPORT_ENTER_V1:
        if (applyDimensions())
            preview();
        return;
    case ARKITA_VIEWPORT_LEAVE_V1:
        tool.target.reset();
        preview();
        return;
    }
}

void start(void *) {
    const auto context = arkita->context;
    const auto needed = arkita->selected_punch_definition(context, nullptr, 0);
    if (needed < 2) {
        message("Sélectionnez un composant de porte avec un volume de percement et les options DoorWidth et DoorHeight.");
        return;
    }
    tool.definition.resize(needed);
    arkita->selected_punch_definition(context, tool.definition.data(), needed);
    tool.definition.pop_back();
    tool.input.clear();
    tool.target.reset();
    if (arkita->start_viewport_tool(context, viewportEvent, nullptr))
        prompt();
}

void placeDoor(void *, const char *arguments, void *response, ArkitaMcpReplyV1 reply) {
    arkita->place_punch_component(arkita->context, arguments, response, reply);
}

int activate(const ArkitaExtensionHostV1 *host) {
    arkita = host;
    const auto context = arkita->context;
    return arkita->add_action(context, "Poser la porte sélectionnée", start, nullptr) &&
        host->publish_mcp_tool(context, "place_door",
            "Place a parametrized door and cut a specified vertical wall in one undoable operation. Coordinates and dimensions are in metres.",
            R"({"type":"object","additionalProperties":false,"required":["definitionId","punchHostId","position","punchNormal","options"],"properties":{"definitionId":{"type":"string","minLength":1},"punchHostId":{"type":"string","minLength":1},"position":{"type":"array","items":{"type":"number"},"minItems":3,"maxItems":3},"punchNormal":{"type":"array","prefixItems":[{"type":"number"},{"type":"number"},{"type":"number","minimum":-0.000001,"maximum":0.000001}],"minItems":3,"maxItems":3},"options":{"type":"object","additionalProperties":false,"required":["DoorWidth","DoorHeight"],"properties":{"DoorWidth":{"type":"number","exclusiveMinimum":0},"DoorHeight":{"type":"number","exclusiveMinimum":0}}}}})",
            0, placeDoor, nullptr);
}

void deactivate() { arkita = nullptr; }

} // namespace

const ArkitaExtensionV1 *arkita_extension_v1() {
    static const ArkitaExtensionV1 extension{
        ARKITA_EXTENSION_ABI_V1, "example.door-placement", "Pose de porte", activate, deactivate,
    };
    return &extension;
}
