#include "arkita-extension-v1.h"

#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMap>
#include <QStringList>
#include <cmath>
#include <utility>

namespace {
constexpr auto panelId = "component_inspector";
const ArkitaExtensionHostV1 *host = nullptr;
QJsonObject context;
QJsonArray entityIds;
QMap<QString, QJsonObject> editableFields;

void *hostContext() { return host->context; }

void status(const QString &message) {
    host->show_message(hostContext(), message.toUtf8().constData());
}

int copyReply(void *data, const char *json, int) {
    *static_cast<QJsonObject *>(data) = QJsonDocument::fromJson(json).object();
    return 1;
}

QString textValue(const QJsonValue &value) {
    if (value.isDouble())
        return QString::number(value.toDouble(), 'g', 15);
    if (value.isBool())
        return value.toBool() ? QStringLiteral("Oui") : QStringLiteral("Non");
    return value.toString();
}

struct LengthDisplay { double metresPerUnit; const char *symbol; };
LengthDisplay lengthDisplay(const QString &unit) {
    if (unit == "millimetre") return {.001, "mm"};
    if (unit == "centimetre") return {.01, "cm"};
    if (unit == "inch") return {.0254, "in"};
    if (unit == "foot") return {.3048, "ft"};
    return {1, "m"};
}

QJsonArray inputChoices(const QJsonObject &attribute) {
    const auto choices = attribute.value("choices").toArray();
    if (!choices.isEmpty() || attribute.value("dataType") != "boolean")
        return choices;
    return {QJsonObject{{"label", "Oui"}, {"value", true}}, QJsonObject{{"label", "Non"}, {"value", false}}};
}

bool canEdit(const QJsonObject &attribute) {
    return attribute.value("visible").toBool(true) && attribute.value("editable").toBool() &&
           attribute.value("formula").toString().trimmed().isEmpty();
}

bool matchesField(const QJsonObject &component, const QJsonObject &field) {
    if (component.value("locked").toBool())
        return false;
    for (const auto &row : component.value("attributes").toArray()) {
        const auto attribute = row.toObject();
        if (attribute.value("name") == field.value("name"))
            return canEdit(attribute) && attribute.value("dataType") == field.value("dataType") &&
                   attribute.value("unit") == field.value("unit") && inputChoices(attribute) == inputChoices(field);
    }
    return false;
}

void refresh(void *) {
    QJsonObject drawing;
    host->inspect_components(hostContext(), "{}", &drawing, copyReply);
    context = drawing.value("context").toObject();
    entityIds = {};
    editableFields.clear();
    const auto components = drawing.value("components").toArray();
    const auto display = lengthDisplay(drawing.value("displayUnit").toString());
    QStringList summary;
    if (drawing.value("error") == "document_not_found")
        summary.append(QStringLiteral("Ouvrez un dessin pour inspecter ses composants."));
    else if (drawing.contains("error"))
        summary.append(QStringLiteral("Lecture impossible (%1).").arg(drawing.value("error").toString()));
    else if (components.isEmpty())
        summary.append(QStringLiteral("Sélectionnez un ou plusieurs composants dans le dessin."));

    for (const auto &entry : components) {
        const auto component = entry.toObject();
        entityIds.append(component.value("entityId"));
        const auto definition = component.value("name").toString();
        const auto occurrence = component.value("occurrenceName").toString();
        const auto title = occurrence.isEmpty() || occurrence == definition ? definition
            : QStringLiteral("%1 (%2)").arg(occurrence, definition);
        QStringList dimensions;
        for (const auto &length : component.value("dimensionsMm").toArray())
            dimensions.append(textValue(length.toDouble() * .001 / display.metresPerUnit));
        auto details = QStringLiteral("%1 · %2 %3").arg(title, dimensions.join(QStringLiteral(" × ")), display.symbol);
        const auto material = component.value("materialName").toString(component.value("materialId").toString());
        if (!material.isEmpty())
            details += QStringLiteral("\nMatériau d’occurrence · %1").arg(material);
        if (component.value("locked").toBool())
            details += QStringLiteral("\nVerrouillé");
        const auto values = component.value("values").toObject();
        for (const auto &row : component.value("attributes").toArray()) {
            const auto attribute = row.toObject();
            const auto name = attribute.value("name").toString();
            const auto value = values.value(name);
            if (value.isUndefined())
                continue;
            const auto unit = attribute.value("unit").toString();
            if (unit == "metre" || unit == "model") {
                const auto metres = value.toDouble() * (unit == "model" ? .001 : 1.);
                details += QStringLiteral("\n%1 · %2 %3").arg(name, textValue(metres / display.metresPerUnit), display.symbol);
            } else {
                const auto suffix = unit.isEmpty() ? QString{} : QStringLiteral(" (%1)").arg(unit);
                details += QStringLiteral("\n%1 · %2%3").arg(name, textValue(value), suffix);
            }
        }
        summary.append(details);
    }

    QJsonArray fields;
    if (components.size() > 128) {
        summary.prepend(QStringLiteral("Sélectionnez au plus 128 occurrences pour modifier leurs options."));
    } else if (!components.isEmpty()) {
        const auto first = components.first().toObject();
        for (const auto &row : first.value("attributes").toArray()) {
            const auto attribute = row.toObject();
            bool common = true;
            bool mixed = false;
            const auto name = attribute.value("name").toString();
            const auto value = first.value("values").toObject().value(name);
            for (const auto &entry : components) {
                const auto component = entry.toObject();
                common &= matchesField(component, attribute);
                mixed |= component.value("values").toObject().value(name) != value;
            }
            if (!common)
                continue;

            const auto unit = attribute.value("unit").toString();
            const bool length = unit == "metre" || unit == "model";
            const auto choices = inputChoices(attribute);
            const auto suffix = length && choices.isEmpty() ? QString::fromLatin1(display.symbol) : unit;
            QJsonObject field{{"id", name}, {"label", suffix.isEmpty() ? name : QStringLiteral("%1 (%2)").arg(name, suffix)},
                              {"choices", choices}};
            if (mixed)
                field.insert("placeholder", QStringLiteral("Valeurs différentes"));
            else if (!choices.isEmpty())
                field.insert("value", value);
            else if (length)
                field.insert("value", textValue(value.toDouble() * (unit == "model" ? .001 : 1.) / display.metresPerUnit));
            else
                field.insert("value", textValue(value));
            fields.append(field);
            editableFields.insert(name, attribute);
        }
        if (fields.isEmpty())
            summary.append(QStringLiteral("Aucune option publique commune et modifiable."));
    }
    const auto view = QJsonDocument(QJsonObject{{"summary", summary.join("\n\n")}, {"fields", fields},
        {"submitLabel", QStringLiteral("Appliquer à la sélection")}}).toJson(QJsonDocument::Compact);
    host->update_panel(hostContext(), panelId, view.constData());
}

void submit(void *, const char *json) {
    const auto fields = QJsonDocument::fromJson(json).object();
    QJsonObject options;
    for (auto it = fields.constBegin(); it != fields.constEnd(); ++it) {
        const auto attribute = editableFields.value(it.key());
        if (attribute.isEmpty())
            return;
        QJsonValue value = it.value();
        if (attribute.value("dataType") == "number" && inputChoices(attribute).isEmpty()) {
            const auto unit = attribute.value("unit").toString();
            const auto text = value.toString().trimmed();
            double number = 0;
            bool valid = false;
            if (unit == "metre" || unit == "model") {
                const bool negative = text.startsWith('-');
                const auto magnitude = negative ? text.sliced(1) : text;
                valid = host->parse_length(hostContext(), magnitude.toUtf8().constData(), &number) == 1;
                if (negative)
                    number = -number;
                if (unit == "model")
                    number *= 1000.;
            } else {
                auto normalized = text;
                number = normalized.replace(',', '.').toDouble(&valid);
            }
            if (!valid || !std::isfinite(number)) {
                status(QStringLiteral("Valeur numérique invalide pour %1.").arg(it.key()));
                return;
            }
            value = number;
        }
        options.insert(it.key(), value);
    }
    QJsonObject current;
    host->inspect_components(hostContext(), "{}", &current, copyReply);
    QJsonArray selection;
    for (const auto &component : current.value("components").toArray())
        selection.append(component.toObject().value("entityId"));
    if (current.value("context") != context || selection != entityIds) {
        status(QStringLiteral("La sélection ou le dessin a changé. Vérifiez les occurrences avant de réessayer."));
        return;
    }
    const auto request = QJsonDocument(QJsonObject{{"context", context}, {"entityIds", entityIds},
        {"options", options}}).toJson(QJsonDocument::Compact);
    QJsonObject result;
    if (host->set_component_options(hostContext(), request.constData(), &result, copyReply))
        status(QStringLiteral("Options appliquées à %1 occurrence(s).").arg(entityIds.size()));
    else
        status(QStringLiteral("Options non appliquées (%1).").arg(result.value("error").toString()));
}

void openPanel(void *) { host->show_panel(hostContext(), panelId); }

void inspectMcp(void *, const char *json, void *replyData, ArkitaMcpReplyV1 reply) {
    host->inspect_components(hostContext(), json, replyData, reply);
}

void updateMcp(void *, const char *json, void *replyData, ArkitaMcpReplyV1 reply) {
    host->set_component_options(hostContext(), json, replyData, reply);
}

int activate(const ArkitaExtensionHostV1 *api) {
    if (!api || api->abi_version != ARKITA_EXTENSION_ABI_V1)
        return 0;
    host = api;
    return host->register_panel(hostContext(), panelId, "Inspecteur de composants", submit, nullptr) &&
           host->observe_model(hostContext(), refresh, nullptr) &&
           host->add_action(hostContext(), "Ouvrir l’inspecteur de composants", openPanel, nullptr) &&
           host->publish_mcp_tool(hostContext(), "inspect_components", "Read selected or specified component occurrences, their dimensions, material and attributes.",
               R"({"type":"object","properties":{"entityIds":{"type":"array","minItems":1,"maxItems":128,"uniqueItems":true,"items":{"type":"string","minLength":1}}},"additionalProperties":false})",
               1, inspectMcp, nullptr) &&
           host->publish_mcp_tool(hostContext(), "set_options", "Set the same public options on multiple occurrences in one undoable operation. Use the context returned by inspect_components and attribute storage units.",
               R"({"type":"object","properties":{"context":{"type":"object","properties":{"documentId":{"type":"string"},"epoch":{"type":"string"},"expectedStateRevision":{"type":"string"},"editPath":{"type":"array","items":{"type":"string"}}},"required":["documentId","epoch","expectedStateRevision","editPath"],"additionalProperties":false},"entityIds":{"type":"array","minItems":1,"maxItems":128,"uniqueItems":true,"items":{"type":"string","minLength":1}},"options":{"type":"object","minProperties":1,"additionalProperties":{"type":["string","number","boolean","null"]}}},"required":["context","entityIds","options"],"additionalProperties":false})",
               0, updateMcp, nullptr);
}

void deactivate() {
    host = nullptr;
    context = {};
    entityIds = {};
    editableFields.clear();
}

const ArkitaExtensionV1 extension{ARKITA_EXTENSION_ABI_V1, "example.component-inspector", "Inspecteur de composants", activate, deactivate};
} // namespace

const ArkitaExtensionV1 *arkita_extension_v1(void) { return &extension; }
