#ifndef ARKITA_EXTENSION_V1_H
#define ARKITA_EXTENSION_V1_H

#include <stddef.h>
#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

#define ARKITA_EXTENSION_ABI_V1 1u
#if defined(_WIN32)
#define ARKITA_EXTENSION_EXPORT __declspec(dllexport)
#else
#define ARKITA_EXTENSION_EXPORT __attribute__((visibility("default")))
#endif

typedef void (*ArkitaExtensionActionV1)(void *user_data);

typedef struct ArkitaViewportClickV1 {
    double viewport_x, viewport_y; /* Logical pixels, from the viewport's top left. */
    int has_point;
    double point[3]; /* Metres in the active edit context, when has_point is 1. */
} ArkitaViewportClickV1;

typedef void (*ArkitaViewportClickHandlerV1)(void *user_data, const ArkitaViewportClickV1 *click);
typedef int (*ArkitaExtensionOperationV1)(void *user_data);

/* Returns 1 once a valid UTF-8 JSON object is copied. Call before returning from the handler.
   The reply context and arguments belong to the host and are valid only during the call. */
typedef int (*ArkitaMcpReplyV1)(void *reply_context, const char *result_json, int is_error);
typedef void (*ArkitaMcpToolHandlerV1)(void *user_data, const char *arguments_json,
                                      void *reply_context, ArkitaMcpReplyV1 reply);

typedef enum ArkitaViewportEventKindV1 {
    ARKITA_VIEWPORT_MOVE_V1, ARKITA_VIEWPORT_CLICK_V1, ARKITA_VIEWPORT_TEXT_V1,
    ARKITA_VIEWPORT_BACKSPACE_V1, ARKITA_VIEWPORT_ENTER_V1, ARKITA_VIEWPORT_LEAVE_V1
} ArkitaViewportEventKindV1;

typedef struct ArkitaWallHitV1 {
    const char *occurrence_id;
    const char *face_id;
    double position[3]; /* Metres, in the viewport's editing coordinates. */
    double inward_normal[3];
} ArkitaWallHitV1;

typedef struct ArkitaViewportEventV1 {
    ArkitaViewportEventKindV1 kind;
    double viewport_x, viewport_y;
    const char *text;
    const ArkitaWallHitV1 *wall; /* Hit and text are valid for this callback only. */
} ArkitaViewportEventV1;

typedef void (*ArkitaViewportHandlerV1)(void *user_data, const ArkitaViewportEventV1 *event);

typedef void (*ArkitaModelObserverV1)(void *user_data);
typedef void (*ArkitaPanelSubmitV1)(void *user_data, const char *changed_fields_json);

/* Retain this table only while active. Call it on Arkita's UI thread. Strings are UTF-8. */
typedef struct ArkitaExtensionHostV1 {
    uint32_t abi_version;
    void *context;
    /* Register during activate. Returns 1 on success. */
    int (*add_action)(void *context, const char *label, ArkitaExtensionActionV1 action, void *user_data);
    void (*show_message)(void *context, const char *message);
    /* Returns bytes required including the terminator, or 0 with no drawing open.
       Copies the name only if the supplied buffer is large enough. */
    size_t (*active_drawing_name)(void *context, char *buffer, size_t capacity);
    /* Coordinates in metres in the current edit context. Returns 1 on success. */
    int (*add_guide_point)(void *context, double x, double y, double z);

    size_t (*selection_count)(void *context);
    /* UTF-8, including terminator. Returns 0 if index is outside the selection. */
    size_t (*selection_entity_id)(void *context, size_t index, char *buffer, size_t capacity);
    /* Arms a single left click. Escape, tool/context changes or deactivation cancel it. */
    int (*start_viewport_click)(void *context, ArkitaViewportClickHandlerV1 click, void *user_data);
    /* Runs synchronously on the UI thread. Return 1 to apply staged edits as one undo step. */
    int (*run_operation)(void *context, ArkitaExtensionOperationV1 operation, void *user_data);
    /* Only during run_operation. Uses the selection captured at the start of the operation.
       origin may be null or point to three coordinates in metres in the active edit context. */
    int (*create_component_from_selection)(void *context, const char *name, const char *description,
                                            const double *origin);

    /* Register during activate. Local name uses lower-case ASCII, digits and underscores.
       input_schema_json is a draft-2020-12 object schema. read_only is an MCP hint.
       The handler runs synchronously on Arkita's UI thread. */
    int (*publish_mcp_tool)(void *context, const char *name, const char *description,
                            const char *input_schema_json, int read_only,
                            ArkitaMcpToolHandlerV1 handler, void *user_data);

    /* A persistent tool exits on Escape, a context change, or finish_viewport_tool. */
    int (*start_viewport_tool)(void *context, ArkitaViewportHandlerV1 handler, void *user_data);
    void (*finish_viewport_tool)(void *context);
    /* UTF-8 buffer length including terminator, or 0 when nothing suitable is selected. */
    size_t (*selected_punch_definition)(void *context, char *buffer, size_t capacity);
    int (*parse_length)(void *context, const char *text, double *metres);
    /* JSON object with definitionId, punchHostId, position, punchNormal, and optional options.
       The preview is asynchronous and accepts null to clear it. Placement is synchronous and
       adds one undo entry. The optional reply receives an object with IDs or an error. */
    int (*preview_punch_component)(void *context, const char *placement_json);
    int (*place_punch_component)(void *context, const char *placement_json, void *reply_context, ArkitaMcpReplyV1 reply);

    /* Register during activate. The callback runs on the UI thread after activation and
       after changes to the selection or drawing context. Changes can be coalesced. */
    int (*observe_model)(void *context, ArkitaModelObserverV1 observer, void *user_data);
    /* Query {} for selection, or {"entityIds":[...]} for up to 128 occurrences in
       the current edit context. Reply contains {context, components} or {error}. */
    int (*inspect_components)(void *context, const char *query_json, void *reply_context, ArkitaMcpReplyV1 reply);
    /* Submit {context, entityIds, options}. Copy context from inspect_components.
       The same options apply to each occurrence. Null resets a single option. */
    int (*set_component_options)(void *context, const char *batch_json, void *reply_context, ArkitaMcpReplyV1 reply);
    /* Register during activate. IDs use lower-case ASCII, digits and underscores. */
    int (*register_panel)(void *context, const char *id, const char *title, ArkitaPanelSubmitV1 submit, void *user_data);
    int (*show_panel)(void *context, const char *id);
    /* View {summary, submitLabel, submitUnchanged?, fields:[{id, label, value, placeholder, choices:[{label,value}]}]}.
       Fields without choices submit strings. Choices submit their JSON values. Only edited
       fields are submitted. Set submitUnchanged to allow submission before editing any
       field. All strings and JSON bytes passed to callbacks are borrowed. */
    int (*update_panel)(void *context, const char *id, const char *view_json);

    /* Query {section?, id?, definitionId?, offset?, limit?, context?} on the Arkita UI thread.
       Sections: entities (default), definitions, materials, tags. With definitionId,
       entities are read from that definition. Copy context into subsequent pages. */
    int (*inspect_model)(void *context, const char *query_json, void *reply_context, ArkitaMcpReplyV1 reply);
    /* Execute {context, edits, label?} in one undo step. Copy context from inspect_model.
       The optional label is displayed next to Undo and Redo.
       Each edit accepts an optional unique key. A later edit can refer to that
       result using {"ref":"key"}, or use a persistent model ID string directly.
       Geometry uses drawing-world metres in the active collection, and local
       metres in a definition created in this transaction. See the guide for edits.
       The reply contains results in operation order or the index of the failed edit. */
    int (*edit_model)(void *context, const char *transaction_json, void *reply_context, ArkitaMcpReplyV1 reply);
} ArkitaExtensionHostV1;

typedef struct ArkitaExtensionV1 {
    uint32_t abi_version;
    const char *id;
    const char *name;
    /* Return 1 to enable the registered actions. On failure release any allocated state. */
    int (*activate)(const ArkitaExtensionHostV1 *host);
    /* Optional. Release resources and stop background work before returning. */
    void (*deactivate)(void);
} ArkitaExtensionV1;

ARKITA_EXTENSION_EXPORT const ArkitaExtensionV1 *arkita_extension_v1(void);

#ifdef __cplusplus
}
#endif
#endif
