#include "app_core/about_menu.h"
#include "app_core/app_dialog.h"
#include "app_core/app_preferences.h"
#include "app_core/app_frame.h"
#include "app_core/app_input.h"
#include "app_core/app_shutdown.h"
#include "app_core/app_status.h"
#include "app_core/app_startup.h"
#include "app_core/app_thread.h"
#include "app_core/brush_package_import.h"
#include "app_core/brush_package_export.h"
#include "app_core/brush_ui.h"
#include "app_core/canvas_hotkey.h"
#include "app_core/canvas_tool_ui.h"
#include "app_core/canvas_view.h"
#include "app_core/command_convert.h"
#include "app_core/document_animation.h"
#include "app_core/document_canvas.h"
#include "app_core/document_export.h"
#include "app_core/document_import.h"
#include "app_core/document_cloud.h"
#include "app_core/document_layer.h"
#include "app_core/document_platform_io.h"
#include "app_core/document_recording.h"
#include "app_core/document_resize.h"
#include "app_core/document_route.h"
#include "app_core/document_sharing.h"
#include "app_core/document_session.h"
#include "app_core/file_menu.h"
#include "assets/brush_package.h"
#include "app_core/grid_ui.h"
#include "app_core/history_ui.h"
#include "app_core/main_toolbar.h"
#include "app_core/quick_ui.h"
#include "app_core/tools_menu.h"
#include "assets/image_format.h"
#include "assets/image_metadata.h"
#include "assets/image_pixels.h"
#include "assets/ppi_header.h"
#include "document/document.h"
#include "document/ppi_export.h"
#include "document/ppi_import.h"
#include "foundation/parse.h"
#include "foundation/result.h"
#include "paint/blend.h"
#include "paint_renderer/compositor.h"
#include "paint/stroke.h"
#include "paint/stroke_script.h"
#include "renderer_api/recording_renderer.h"
#ifdef PP_PANO_CLI_ENABLE_OPENGL_PLAN
#include "renderer_gl/command_plan.h"
#endif
#include "ui_core/layout_xml.h"

#include <algorithm>
#include <array>
#include <charconv>
#include <cmath>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <iterator>
#include <system_error>
#include <span>
#include <string>
#include <string_view>
#include <vector>

namespace {

struct DocumentArgs {
    std::uint32_t width = 0;
    std::uint32_t height = 0;
    std::uint32_t layers = 1;
    std::uint32_t frames = 1;
    std::uint32_t frame_duration_ms = 100;
};

struct SaveProjectArgs {
    std::string path;
    std::uint32_t width = 0;
    std::uint32_t height = 0;
    std::string layer_name = "Ink";
    float layer_opacity = 1.0F;
    std::uint32_t blend_mode = 0;
    bool alpha_locked = false;
    bool visible = true;
    std::uint32_t layers = 1;
    std::uint32_t frames = 1;
    std::uint32_t frame_duration_ms = 100;
    bool include_test_face_payload = false;
    std::uint32_t payload_layer = 0;
    std::uint32_t payload_frame = 0;
};

struct SaveDocumentProjectArgs {
    std::string path;
    std::uint32_t width = 64;
    std::uint32_t height = 32;
};

struct InspectImageArgs {
    std::string path;
};

struct ImportImageArgs {
    std::string path;
    std::uint32_t document_width = 0;
    std::uint32_t document_height = 0;
    std::uint32_t face = 0;
    std::uint32_t x = 0;
    std::uint32_t y = 0;
};

struct ExportImageArgs {
    std::string path;
    std::uint32_t width = 2;
    std::uint32_t height = 2;
};

struct ParseLayoutArgs {
    std::string path;
};

struct InspectProjectArgs {
    std::string path;
};

struct ClassifyOpenArgs {
    std::string path;
};

struct PlanOpenRouteArgs {
    std::string path;
    bool unsaved = false;
};

struct PlanDocumentFileArgs {
    std::string work_directory;
    std::string name;
    bool target_exists = false;
};

struct PlanNewDocumentArgs {
    std::string work_directory;
    std::string name;
    std::uint32_t resolution_index = 0;
    bool target_exists = false;
};

struct PlanDocumentVersionArgs {
    std::string directory;
    std::string document_name;
    std::vector<std::string> existing_paths;
};

struct PlanDocumentSessionPromptArgs {
    pp::app::DocumentSessionPromptKind kind = pp::app::DocumentSessionPromptKind::close_unsaved_document;
    std::string name = "demo";
};

struct PlanExportTargetArgs {
    std::string kind;
    std::string work_directory;
    std::string directory;
    std::string document_name;
    std::string extension;
    std::string suffix;
};

struct PlanExportMessageArgs {
    std::string kind = "equirectangular";
    std::string destination = "work";
    std::string detail = "D:/Paint";
};

struct PlanExportReportArgs {
    std::string kind = "equirectangular";
    std::string message = "document name must not be empty";
};

struct PlanExportStartArgs {
    bool requires_license = false;
    bool license_valid = true;
    bool has_canvas = true;
};

struct PlanExportMenuArgs {
    std::string kind = "jpeg";
    bool license_valid = true;
    bool has_canvas = true;
};

struct PlanExportSnapshotRouteArgs {
    std::string kind = "equirectangular";
    std::string target_path;
    std::uint32_t captured_face_payloads = 6;
    std::uint32_t pending_face_payloads = 6;
    bool target_supported = true;
    bool platform_supported = true;
};

struct PlanFileMenuArgs {
    std::string command = "new";
};

struct PlanCloudUploadArgs {
    bool has_canvas = true;
    bool new_document = false;
    bool unsaved = false;
};

struct PlanCloudBrowseArgs {
    bool has_canvas = true;
    std::string selected_file;
};

struct PlanCloudUploadAllArgs {
    std::uint32_t file_count = 0;
    bool progress_ui_available = true;
};

struct PlanCloudTransferArgs {
    pp::app::CloudTransferDirection direction = pp::app::CloudTransferDirection::download;
    std::string source = "https://example.invalid/demo.ppi";
    std::string destination = "D:/Paint/demo.ppi";
    bool progress_callback = false;
    bool disable_tls_verification = false;
    std::int64_t progress_total = 100;
    std::int64_t progress_current = 25;
};

struct PlanRecordingSessionArgs {
    bool running = false;
    std::uint32_t frame_count = 0;
    bool platform_deletes_recorded_files = false;
    bool encoder_available = true;
    bool has_canvas = true;
};

struct PlanShareFileArgs {
    std::string path;
};

struct PlanPickedPathArgs {
    std::string path;
};

struct PlanDisplayFileArgs {
    std::string path;
};

struct PlanKeyboardVisibilityArgs {
    bool visible = false;
};

struct PlanCursorVisibilityArgs {
    bool visible = false;
};

struct PlanClipboardWriteArgs {
    std::string text;
};

struct PlanAppPreferencesArgs {
    float ui_scale = 1.0F;
    float display_density = 1.0F;
    float current_scale = 1.0F;
    std::vector<float> scale_options;
    float viewport_scale = 1.0F;
    bool right_to_left = false;
    bool timelapse_enabled = true;
    bool recording_running = false;
    bool vr_controllers_enabled = true;
    int cursor_mode = 0;
};

struct PlanAppDialogArgs {
    pp::app::AppDialogKind kind = pp::app::AppDialogKind::progress;
    std::string title = "Saving";
    std::string message = "Done";
    std::string field_name = "Name";
    std::string ok_caption = "Ok";
    int total = 0;
    bool cancel = false;
};

struct PlanAppStartupArgs {
    int run_counter = 0;
    bool auto_timelapse_enabled = true;
    bool vr_controllers_enabled = true;
    bool license_valid = true;
};

struct PlanAppStartupResourcesArgs {
    float width = 1280.0F;
    float height = 720.0F;
    bool bad_size = false;
};

struct PlanAppFrameArgs {
    bool redraw = false;
    bool animate = false;
    bool has_designer_layout = true;
    bool has_main_layout = true;
    bool has_canvas_node = true;
    bool has_canvas_document = true;
    bool vr_active = false;
    bool ui_visible = true;
    bool vr_only = false;
    float resize_width = 1280.0F;
    float resize_height = 720.0F;
    bool bad_resize = false;
    bool observer_display = true;
    bool observer_on_screen = false;
    bool observer_clipped_out = false;
    bool observer_bad_geometry = false;
};

struct PlanAppThreadArgs {
    std::string kind = "dispatch";
    bool on_target_thread = false;
    bool require_ui_thread = false;
    bool unique = false;
    bool worker_running = true;
    bool wait = false;
    bool request_redraw = false;
    bool redraw = false;
    bool live_reload = false;
    bool joinable = true;
    std::uint32_t queued_tasks = 0;
    int rendered_frames = 0;
    float delta_time_seconds = 0.25F;
    float frame_accumulator = 0.5F;
    float fps_accumulator = 0.9F;
    float reload_accumulator = 0.9F;
    bool bad_timer = false;
};

struct PlanAppInputArgs {
    std::string kind = "pointer";
    float x0 = 100.0F;
    float y0 = 50.0F;
    float x1 = 160.0F;
    float y1 = 130.0F;
    float previous_x0 = 100.0F;
    float previous_y0 = 50.0F;
    float previous_x1 = 130.0F;
    float previous_y1 = 90.0F;
    float zoom = 2.0F;
    bool has_designer_layout = true;
    bool has_main_layout = true;
    bool spacebar = false;
    bool vr_active = false;
    bool key_up = false;
    bool ui_visible = true;
    bool has_canvas = true;
    std::uint32_t main_child_count = 2;
    std::uint32_t panel_child_count = 4;
    bool bad_float = false;
};

struct PlanCommandConvertArgs {
    std::string project_path = "D:/Paint/demo.ppi";
    std::string output_path = "D:/Paint/demo.png";
    int canvas_resolution = 1024;
};

struct PlanBrushPackageExportArgs {
    std::string path;
    std::string author;
    std::string email;
    std::string url;
    std::string description;
    std::string destination_path;
    bool export_data = false;
    bool has_header_image = false;
};

struct PlanBrushPackageImportArgs {
    std::string kind = "ppbr";
    std::string path;
};

struct PlanAppStatusArgs {
    std::string document_name = "no-name";
    bool unsaved = false;
    int resolution = 512;
    int resolution_index = 0;
    float zoom = 1.0F;
    std::uint32_t history_bytes = 0;
    bool recording_running = false;
    bool encoder_available = false;
    std::uint32_t encoded_frames = 0;
    bool framebuffer_fetch = false;
    bool float32_render_targets = false;
    bool float32_linear_filtering = false;
    bool float16_render_targets = false;
};

struct PlanDocumentResizeArgs {
    int current_resolution = 512;
    int selected_resolution_index = 0;
};

struct PlanCanvasClearArgs {
    bool has_canvas = true;
    float r = 0.0F;
    float g = 0.0F;
    float b = 0.0F;
    float a = 0.0F;
};

struct PlanCanvasProjectSaveTargetArgs {
    std::string data_directory = "D:/Paint/data";
    std::string target_path = "D:/Paint/projects/demo.ppi";
    bool target_exists = false;
    bool remove_fails = false;
    bool rename_fails = false;
    bool encoder_available = false;
    bool progress_visible = false;
};

struct PlanCanvasDocumentSnapshotArgs {
    bool has_canvas = true;
    std::uint32_t width = 64;
    std::uint32_t height = 32;
    std::uint32_t layers = 2;
    std::uint32_t frames = 2;
    std::uint32_t frame_duration_ms = 100;
    std::uint32_t current_layer = 1;
    std::uint32_t current_frame = 0;
    std::uint32_t hidden_layer = 0;
    std::uint32_t alpha_locked_layer = 1;
    float opacity = 0.75F;
    int blend_mode = 4;
    std::uint32_t pending_face_payloads_per_layer = pp::document::cube_face_count;
    std::uint32_t captured_face_payloads_per_layer = 0;
};

struct PlanImageImportArgs {
    int width = 0;
    int height = 0;
};

struct PlanLayerRenameArgs {
    std::string old_name = "Layer 1";
    std::string new_name;
};

struct PlanLayerOperationArgs {
    std::string kind = "select";
    int layer_count = 1;
    int index = 0;
    int from_index = 0;
    int to_index = 0;
    int source_index = 0;
    std::string name = "Layer";
    float opacity = 1.0F;
    bool flag = false;
    int blend_mode = 0;
};

struct PlanLayerMenuArgs {
    std::string command = "merge";
    bool has_current_layer = true;
    int current_index = 0;
    int animation_duration = 1;
    std::string current_name = "Layer";
    std::string lower_name = "Layer 0";
};

struct PlanLayerPanelViewArgs {
    int layer_count = 2;
    int current_index = 0;
    int hidden_index = -1;
    int locked_index = -1;
    float current_opacity = 1.0F;
    int current_blend_mode = 0;
};

struct PlanLayerMergeArgs {
    int layer_count = 2;
    int from_index = 1;
    int to_index = 0;
    int animation_duration = 1;
    bool create_history = true;
};

struct PlanAnimationOperationArgs {
    std::string kind = "goto";
    int frame_count = 1;
    int total_duration = 1;
    int current_frame = 0;
    int selected_frame = 0;
    int layer_index = 0;
    std::uint32_t layer_id = 0;
    int current_duration = 1;
    int delta = 1;
    int offset = 1;
    int onion_size = 1;
    bool playback_active = false;
};

struct PlanAnimationPanelActionArgs {
    std::string action = "next";
    int total_duration = 1;
    int current_frame = 0;
    int target_frame = 0;
    bool playback_active = false;
};

struct PlanAnimationPanelViewArgs {
    int layer_count = 2;
    int frame_count = 2;
    int frame_duration = 1;
    int total_duration = 2;
    int current_layer = 0;
    int current_frame = 0;
    std::uint32_t selected_layer_id = 10;
    int selected_frame = 0;
    int onion_size = 1;
    int hidden_layer = -1;
};

struct PlanAnimationTimelineScrubArgs {
    int total_duration = 1;
    float cursor_x = 0.0F;
    float frame_width = pp::app::document_animation_timeline_frame_width;
};

struct PlanBrushOperationArgs {
    std::string kind = "settings";
    std::string path;
    std::string thumbnail_path;
    float r = 1.0F;
    float g = 1.0F;
    float b = 1.0F;
    float a = 1.0F;
    bool has_brush = true;
};

struct PlanBrushRefreshArgs {
    bool update_color = true;
    bool update_brush = true;
    bool has_brush = true;
    bool floating_picker = false;
    bool floating_color = false;
    float tip_flow = 0.9F;
    float tip_size = 64.0F;
    float r = 0.25F;
    float g = 0.5F;
    float b = 0.75F;
    float a = 1.0F;
    bool bad_float = false;
};

struct PlanBrushTextureListArgs {
    std::string kind = "add";
    std::string directory_name = "brushes";
    std::string data_path = "data";
    std::string source_path = "source.png";
    int item_count = 1;
    int current_index = 0;
    int offset = 1;
    bool current_is_user_texture = false;
};

struct PlanBrushPresetListArgs {
    std::string kind = "select";
    int item_count = 1;
    int current_index = 0;
    int offset = 1;
    bool has_current_brush = true;
};

struct PlanBrushStrokeControlArgs {
    std::string kind = "float";
    std::string setting = "tip-size";
    float value = 1.0F;
    bool enabled = true;
    int blend_mode = 0;
};

struct PlanBrushStrokePanelViewArgs {
    float tip_size = 42.5F;
    float jitter_scatter = 0.75F;
    bool dual_enabled = true;
    int tip_blend_mode = 4;
    int pattern_blend_mode = 8;
    std::string tip_thumbnail_path = "data/brushes/thumbs/soft.png";
    std::string dual_thumbnail_path = "data/brushes/thumbs/hard.png";
    std::string pattern_thumbnail_path = "data/patterns/thumbs/noise.png";
    bool bad_float = false;
    bool bad_blend = false;
};

struct PlanPaintFeedbackArgs {
    int width = 64;
    int height = 32;
    bool complex_blend = true;
    bool framebuffer_fetch = false;
    bool explicit_texture_transitions = false;
    bool texture_copy = false;
    bool render_target_blit = false;
    bool render_only_target = false;
    bool depth_target = false;
};

struct PlanStrokeCompositeArgs {
    int width = 64;
    int height = 32;
    int layer_blend_mode = 0;
    int stroke_blend_mode = 0;
    bool dual_brush_blend = false;
    bool pattern_blend = false;
    bool framebuffer_fetch = false;
    bool explicit_texture_transitions = false;
    bool texture_copy = false;
    bool render_target_blit = false;
    bool render_only_target = false;
    bool depth_target = false;
};

struct PlanGridOperationArgs {
    std::string kind = "pick";
    std::string path;
    bool has_heightmap = true;
    bool has_canvas = true;
    bool supports_float32 = false;
    bool supports_float16 = false;
    int texture_resolution = 1024;
    int sample_count = 32;
};

struct PlanHistoryOperationArgs {
    std::string kind = "undo";
    int undo_count = 0;
    int redo_count = 0;
    int memory_bytes = 0;
};

struct PlanMainToolbarArgs {
    std::string command = "undo";
    int undo_count = 0;
    int redo_count = 0;
    int memory_bytes = 0;
    bool has_canvas = true;
};

struct PlanCanvasToolArgs {
    std::string kind = "draw";
    bool current_mode_draw = false;
};

struct PlanCanvasHotkeyArgs {
    std::string event = "key-up";
    std::string key = "z";
    bool ctrl_down = false;
    bool shift_down = false;
    bool mouse_focused = false;
    int undo_count = 1;
    int redo_count = 1;
    int touch_finger_count = 0;
};

struct PlanCanvasToolStateArgs {
    std::string mode = "draw";
    bool picking = false;
    bool touch_lock = false;
};

struct PlanCanvasCursorArgs {
    std::string mode = "draw";
    std::string visibility = "small-brush";
    bool has_brush = true;
    float brush_size = 9.5F;
    bool drawing = false;
    bool alt = false;
    bool resizing = false;
    bool picking = false;
    bool bad_size = false;
};

struct PlanQuickOperationArgs {
    std::string kind = "brush";
    int current_index = 0;
    int slot_index = 0;
    int brush_index = 0;
    int color_index = 0;
    int slot_count = 3;
    bool fire_event = false;
};

struct PlanQuickSliderPreviewArgs {
    bool rtl = false;
    float slider_x = 10.0F;
    float slider_y = 20.0F;
    float slider_height = 40.0F;
    float zoom = 2.0F;
    bool pen_mode = true;
    bool line_mode = false;
    bool bad_float = false;
};

struct PlanToolsMenuArgs {
    std::string command = "shortcuts";
    bool sonarpen_available = false;
};

struct PlanToolsPanelArgs {
    std::string panel = "layers";
    bool already_visible = false;
};

struct PlanAboutMenuArgs {
    std::string command = "news";
    int version_major = 1;
    int version_minor = 0;
    int version_fix = 0;
    bool diagnostics_available = true;
    bool has_canvas = true;
};

struct SimulateAppSessionArgs {
    bool has_canvas = true;
    bool new_document = false;
    bool unsaved = false;
    bool close_prompt_open = false;
    pp::app::DocumentSaveIntent save_intent = pp::app::DocumentSaveIntent::save;
};

struct SimulateStrokeArgs {
    std::uint32_t x1 = 0;
    std::uint32_t y1 = 0;
    std::uint32_t x2 = 0;
    std::uint32_t y2 = 0;
    std::uint32_t spacing = 1;
};

struct SimulateStrokeScriptArgs {
    std::string path;
};

struct ApplyStrokeScriptArgs {
    std::string path;
    std::string output_path;
    std::uint32_t width = 64;
    std::uint32_t height = 32;
};

struct SimulateDocumentEditsArgs {
    std::uint32_t width = 128;
    std::uint32_t height = 64;
};

struct SimulateImageImportArgs {
    std::uint32_t width = 64;
    std::uint32_t height = 32;
};

struct SimulateDocumentExportArgs {
    std::uint32_t width = 64;
    std::uint32_t height = 32;
};

struct SimulateDocumentRenderArgs {
    std::uint32_t width = 64;
    std::uint32_t height = 32;
    std::uint32_t frame = 0;
};

struct SimulateDocumentHistoryArgs {
    std::uint32_t width = 64;
    std::uint32_t height = 32;
    std::uint32_t history_entries = 4;
};

struct RecordRenderArgs {
    std::uint32_t width = 64;
    std::uint32_t height = 32;
    bool exercise_clear = false;
};

void print_error(std::string_view command, std::string_view message)
{
    std::cout << "{\"ok\":false,\"command\":\"" << command
              << "\",\"error\":\"" << message << "\"}\n";
}

std::span<const std::byte> transparent_png_1x1_bytes() noexcept
{
    static constexpr std::array<std::byte, 68> transparent_png_1x1 {
        std::byte { 0x89 }, std::byte { 0x50 }, std::byte { 0x4e }, std::byte { 0x47 },
        std::byte { 0x0d }, std::byte { 0x0a }, std::byte { 0x1a }, std::byte { 0x0a },
        std::byte { 0x00 }, std::byte { 0x00 }, std::byte { 0x00 }, std::byte { 0x0d },
        std::byte { 0x49 }, std::byte { 0x48 }, std::byte { 0x44 }, std::byte { 0x52 },
        std::byte { 0x00 }, std::byte { 0x00 }, std::byte { 0x00 }, std::byte { 0x01 },
        std::byte { 0x00 }, std::byte { 0x00 }, std::byte { 0x00 }, std::byte { 0x01 },
        std::byte { 0x08 }, std::byte { 0x06 }, std::byte { 0x00 }, std::byte { 0x00 },
        std::byte { 0x00 }, std::byte { 0x1f }, std::byte { 0x15 }, std::byte { 0xc4 },
        std::byte { 0x89 }, std::byte { 0x00 }, std::byte { 0x00 }, std::byte { 0x00 },
        std::byte { 0x0b }, std::byte { 0x49 }, std::byte { 0x44 }, std::byte { 0x41 },
        std::byte { 0x54 }, std::byte { 0x78 }, std::byte { 0x9c }, std::byte { 0x63 },
        std::byte { 0x60 }, std::byte { 0x00 }, std::byte { 0x02 }, std::byte { 0x00 },
        std::byte { 0x00 }, std::byte { 0x05 }, std::byte { 0x00 }, std::byte { 0x01 },
        std::byte { 0x7a }, std::byte { 0x5e }, std::byte { 0xab }, std::byte { 0x3f },
        std::byte { 0x00 }, std::byte { 0x00 }, std::byte { 0x00 }, std::byte { 0x00 },
        std::byte { 0x49 }, std::byte { 0x45 }, std::byte { 0x4e }, std::byte { 0x44 },
        std::byte { 0xae }, std::byte { 0x42 }, std::byte { 0x60 }, std::byte { 0x82 },
    };
    return transparent_png_1x1;
}

std::string json_escape(std::string_view value)
{
    constexpr char hex[] = "0123456789abcdef";
    std::string escaped;
    escaped.reserve(value.size());
    for (const char raw : value) {
        const auto ch = static_cast<unsigned char>(raw);
        switch (ch) {
        case '"':
            escaped += "\\\"";
            break;
        case '\\':
            escaped += "\\\\";
            break;
        case '\b':
            escaped += "\\b";
            break;
        case '\f':
            escaped += "\\f";
            break;
        case '\n':
            escaped += "\\n";
            break;
        case '\r':
            escaped += "\\r";
            break;
        case '\t':
            escaped += "\\t";
            break;
        default:
            if (ch < 0x20U) {
                escaped += "\\u00";
                escaped.push_back(hex[(ch >> 4U) & 0x0fU]);
                escaped.push_back(hex[ch & 0x0fU]);
            } else {
                escaped.push_back(static_cast<char>(ch));
            }
            break;
        }
    }
    return escaped;
}

const char* json_bool(bool value) noexcept
{
    return value ? "true" : "false";
}

const char* document_open_kind_name(pp::app::DocumentOpenKind kind) noexcept
{
    switch (kind) {
    case pp::app::DocumentOpenKind::import_abr:
        return "import-abr";
    case pp::app::DocumentOpenKind::import_ppbr:
        return "import-ppbr";
    case pp::app::DocumentOpenKind::open_project:
        return "open-project";
    }

    return "open-project";
}

const char* project_open_decision_name(pp::app::ProjectOpenDecision decision) noexcept
{
    switch (decision) {
    case pp::app::ProjectOpenDecision::open_now:
        return "open-now";
    case pp::app::ProjectOpenDecision::prompt_discard_unsaved:
        return "prompt-discard-unsaved";
    }

    return "open-now";
}

const char* document_open_plan_action_name(pp::app::DocumentOpenPlanAction action) noexcept
{
    switch (action) {
    case pp::app::DocumentOpenPlanAction::open_project_now:
        return "open-project-now";
    case pp::app::DocumentOpenPlanAction::prompt_discard_unsaved_project:
        return "prompt-discard-unsaved-project";
    case pp::app::DocumentOpenPlanAction::prompt_import_abr:
        return "prompt-import-abr";
    case pp::app::DocumentOpenPlanAction::prompt_import_ppbr:
        return "prompt-import-ppbr";
    }

    return "open-project-now";
}

const char* document_image_import_action_name(pp::app::DocumentImageImportAction action) noexcept
{
    switch (action) {
    case pp::app::DocumentImageImportAction::import_equirectangular:
        return "import-equirectangular";
    case pp::app::DocumentImageImportAction::place_transform:
        return "place-transform";
    }

    return "place-transform";
}

const char* close_request_decision_name(pp::app::CloseRequestDecision decision) noexcept
{
    switch (decision) {
    case pp::app::CloseRequestDecision::close_now:
        return "close-now";
    case pp::app::CloseRequestDecision::show_unsaved_prompt:
        return "show-unsaved-prompt";
    case pp::app::CloseRequestDecision::wait_for_existing_prompt:
        return "wait-for-existing-prompt";
    }

    return "close-now";
}

const char* document_save_intent_name(pp::app::DocumentSaveIntent intent) noexcept
{
    switch (intent) {
    case pp::app::DocumentSaveIntent::save:
        return "save";
    case pp::app::DocumentSaveIntent::save_as:
        return "save-as";
    case pp::app::DocumentSaveIntent::save_version:
        return "save-version";
    case pp::app::DocumentSaveIntent::save_dirty_version:
        return "save-dirty-version";
    }

    return "save";
}

const char* document_save_decision_name(pp::app::DocumentSaveDecision decision) noexcept
{
    switch (decision) {
    case pp::app::DocumentSaveDecision::no_op:
        return "no-op";
    case pp::app::DocumentSaveDecision::show_save_dialog:
        return "show-save-dialog";
    case pp::app::DocumentSaveDecision::save_existing:
        return "save-existing";
    case pp::app::DocumentSaveDecision::save_version:
        return "save-version";
    }

    return "no-op";
}

const char* document_canvas_save_writer_action_name(pp::app::DocumentCanvasSaveWriterAction action) noexcept
{
    switch (action) {
    case pp::app::DocumentCanvasSaveWriterAction::use_document_ppi_writer:
        return "use-document-ppi-writer";
    case pp::app::DocumentCanvasSaveWriterAction::use_legacy_project_save:
        return "use-legacy-project-save";
    }

    return "use-legacy-project-save";
}

const char* document_canvas_project_save_write_action_name(
    pp::app::DocumentCanvasProjectSaveWriteAction action) noexcept
{
    switch (action) {
    case pp::app::DocumentCanvasProjectSaveWriteAction::write_direct_to_target:
        return "write-direct-to-target";
    case pp::app::DocumentCanvasProjectSaveWriteAction::write_temporary_then_swap:
        return "write-temporary-then-swap";
    }

    return "write-direct-to-target";
}

const char* document_workflow_decision_name(pp::app::DocumentWorkflowDecision decision) noexcept
{
    switch (decision) {
    case pp::app::DocumentWorkflowDecision::unavailable:
        return "unavailable";
    case pp::app::DocumentWorkflowDecision::continue_now:
        return "continue-now";
    case pp::app::DocumentWorkflowDecision::prompt_save_before_continue:
        return "prompt-save-before-continue";
    }

    return "unavailable";
}

const char* document_session_prompt_kind_name(pp::app::DocumentSessionPromptKind kind) noexcept
{
    switch (kind) {
    case pp::app::DocumentSessionPromptKind::close_unsaved_document:
        return "close-unsaved";
    case pp::app::DocumentSessionPromptKind::save_before_workflow_continue:
        return "save-before-workflow";
    case pp::app::DocumentSessionPromptKind::new_document_overwrite:
        return "new-document-overwrite";
    case pp::app::DocumentSessionPromptKind::document_file_overwrite:
        return "file-overwrite";
    case pp::app::DocumentSessionPromptKind::document_save_error:
        return "save-error";
    }

    return "close-unsaved";
}

pp::foundation::Result<pp::app::DocumentSessionPromptKind> parse_document_session_prompt_kind(
    std::string_view kind)
{
    if (kind == "close-unsaved") {
        return pp::foundation::Result<pp::app::DocumentSessionPromptKind>::success(
            pp::app::DocumentSessionPromptKind::close_unsaved_document);
    }
    if (kind == "save-before-workflow") {
        return pp::foundation::Result<pp::app::DocumentSessionPromptKind>::success(
            pp::app::DocumentSessionPromptKind::save_before_workflow_continue);
    }
    if (kind == "new-document-overwrite") {
        return pp::foundation::Result<pp::app::DocumentSessionPromptKind>::success(
            pp::app::DocumentSessionPromptKind::new_document_overwrite);
    }
    if (kind == "file-overwrite") {
        return pp::foundation::Result<pp::app::DocumentSessionPromptKind>::success(
            pp::app::DocumentSessionPromptKind::document_file_overwrite);
    }
    if (kind == "save-error") {
        return pp::foundation::Result<pp::app::DocumentSessionPromptKind>::success(
            pp::app::DocumentSessionPromptKind::document_save_error);
    }

    return pp::foundation::Result<pp::app::DocumentSessionPromptKind>::failure(
        pp::foundation::Status::invalid_argument("unknown document session prompt kind"));
}

const char* file_menu_command_name(pp::app::FileMenuCommand command) noexcept
{
    switch (command) {
    case pp::app::FileMenuCommand::new_document:
        return "new-document";
    case pp::app::FileMenuCommand::import_image:
        return "import-image";
    case pp::app::FileMenuCommand::open_project:
        return "open-project";
    case pp::app::FileMenuCommand::browse_cloud:
        return "browse";
    case pp::app::FileMenuCommand::save:
        return "save";
    case pp::app::FileMenuCommand::save_as:
        return "save-as";
    case pp::app::FileMenuCommand::save_version:
        return "save-version";
    case pp::app::FileMenuCommand::export_jpeg:
        return "export-jpeg";
    case pp::app::FileMenuCommand::export_submenu:
        return "export-submenu";
    case pp::app::FileMenuCommand::share:
        return "share";
    case pp::app::FileMenuCommand::resize:
        return "resize";
    case pp::app::FileMenuCommand::cloud_upload:
        return "cloud-upload";
    case pp::app::FileMenuCommand::cloud_browse:
        return "cloud-browse";
    }

    return "new-document";
}

const char* file_menu_action_name(pp::app::FileMenuAction action) noexcept
{
    switch (action) {
    case pp::app::FileMenuAction::show_new_document_dialog:
        return "show-new-document-dialog";
    case pp::app::FileMenuAction::pick_image_for_import:
        return "pick-image-for-import";
    case pp::app::FileMenuAction::pick_project_file:
        return "pick-project-file";
    case pp::app::FileMenuAction::show_cloud_browser_dialog:
        return "show-cloud-browser-dialog";
    case pp::app::FileMenuAction::save_document:
        return "save-document";
    case pp::app::FileMenuAction::show_export_jpeg_dialog:
        return "show-export-jpeg-dialog";
    case pp::app::FileMenuAction::show_export_submenu:
        return "show-export-submenu";
    case pp::app::FileMenuAction::share_document:
        return "share-document";
    case pp::app::FileMenuAction::show_resize_dialog:
        return "show-resize-dialog";
    case pp::app::FileMenuAction::upload_to_cloud:
        return "upload-to-cloud";
    case pp::app::FileMenuAction::browse_cloud_documents:
        return "browse-cloud-documents";
    }

    return "show-new-document-dialog";
}

const char* tools_menu_command_name(pp::app::ToolsMenuCommand command) noexcept
{
    switch (command) {
    case pp::app::ToolsMenuCommand::panels:
        return "panels";
    case pp::app::ToolsMenuCommand::options:
        return "options";
    case pp::app::ToolsMenuCommand::clear_grids:
        return "clear-grids";
    case pp::app::ToolsMenuCommand::reset_camera:
        return "reset-camera";
    case pp::app::ToolsMenuCommand::shortcuts:
        return "shortcuts";
    case pp::app::ToolsMenuCommand::sonarpen:
        return "sonarpen";
    }

    return "shortcuts";
}

const char* tools_menu_action_name(pp::app::ToolsMenuAction action) noexcept
{
    switch (action) {
    case pp::app::ToolsMenuAction::show_panels_submenu:
        return "show-panels-submenu";
    case pp::app::ToolsMenuAction::show_options_submenu:
        return "show-options-submenu";
    case pp::app::ToolsMenuAction::clear_grid_overlays:
        return "clear-grid-overlays";
    case pp::app::ToolsMenuAction::reset_camera:
        return "reset-camera";
    case pp::app::ToolsMenuAction::show_shortcuts_dialog:
        return "show-shortcuts-dialog";
    case pp::app::ToolsMenuAction::start_sonarpen:
        return "start-sonarpen";
    case pp::app::ToolsMenuAction::no_op_unavailable:
        return "no-op-unavailable";
    }

    return "no-op-unavailable";
}

const char* tools_panel_name(pp::app::ToolsPanel panel) noexcept
{
    switch (panel) {
    case pp::app::ToolsPanel::presets:
        return "presets";
    case pp::app::ToolsPanel::color:
        return "color";
    case pp::app::ToolsPanel::color_advanced:
        return "color-advanced";
    case pp::app::ToolsPanel::layers:
        return "layers";
    case pp::app::ToolsPanel::brush:
        return "brush";
    case pp::app::ToolsPanel::grids:
        return "grids";
    case pp::app::ToolsPanel::animation:
        return "animation";
    }

    return "layers";
}

const char* tools_panel_action_name(pp::app::ToolsPanelAction action) noexcept
{
    switch (action) {
    case pp::app::ToolsPanelAction::open_floating_panel:
        return "open-floating-panel";
    case pp::app::ToolsPanelAction::no_op_already_visible:
        return "no-op-already-visible";
    }

    return "no-op-already-visible";
}

const char* about_menu_command_name(pp::app::AboutMenuCommand command) noexcept
{
    switch (command) {
    case pp::app::AboutMenuCommand::help_guide:
        return "help";
    case pp::app::AboutMenuCommand::about_app:
        return "about";
    case pp::app::AboutMenuCommand::whats_new:
        return "news";
    case pp::app::AboutMenuCommand::induce_crash:
        return "crash";
    case pp::app::AboutMenuCommand::performance_test:
        return "performance";
    }

    return "help";
}

const char* about_menu_action_name(pp::app::AboutMenuAction action) noexcept
{
    switch (action) {
    case pp::app::AboutMenuAction::show_user_manual:
        return "show-user-manual";
    case pp::app::AboutMenuAction::show_about_dialog:
        return "show-about-dialog";
    case pp::app::AboutMenuAction::show_whats_new_dialog:
        return "show-whats-new-dialog";
    case pp::app::AboutMenuAction::trigger_crash_test:
        return "trigger-crash-test";
    case pp::app::AboutMenuAction::run_performance_test:
        return "run-performance-test";
    case pp::app::AboutMenuAction::no_op_unavailable:
        return "no-op-unavailable";
    }

    return "no-op-unavailable";
}

pp::foundation::Result<pp::app::ToolsMenuCommand> parse_tools_menu_command(std::string_view command)
{
    if (command == "panels") {
        return pp::foundation::Result<pp::app::ToolsMenuCommand>::success(pp::app::ToolsMenuCommand::panels);
    }
    if (command == "options") {
        return pp::foundation::Result<pp::app::ToolsMenuCommand>::success(pp::app::ToolsMenuCommand::options);
    }
    if (command == "clear-grids") {
        return pp::foundation::Result<pp::app::ToolsMenuCommand>::success(pp::app::ToolsMenuCommand::clear_grids);
    }
    if (command == "reset-camera") {
        return pp::foundation::Result<pp::app::ToolsMenuCommand>::success(pp::app::ToolsMenuCommand::reset_camera);
    }
    if (command == "shortcuts") {
        return pp::foundation::Result<pp::app::ToolsMenuCommand>::success(pp::app::ToolsMenuCommand::shortcuts);
    }
    if (command == "sonarpen") {
        return pp::foundation::Result<pp::app::ToolsMenuCommand>::success(pp::app::ToolsMenuCommand::sonarpen);
    }

    return pp::foundation::Result<pp::app::ToolsMenuCommand>::failure(
        pp::foundation::Status::invalid_argument("unknown tools menu command"));
}

pp::foundation::Result<pp::app::ToolsPanel> parse_tools_panel(std::string_view panel)
{
    if (panel == "presets") {
        return pp::foundation::Result<pp::app::ToolsPanel>::success(pp::app::ToolsPanel::presets);
    }
    if (panel == "color") {
        return pp::foundation::Result<pp::app::ToolsPanel>::success(pp::app::ToolsPanel::color);
    }
    if (panel == "color-advanced" || panel == "advanced-color") {
        return pp::foundation::Result<pp::app::ToolsPanel>::success(pp::app::ToolsPanel::color_advanced);
    }
    if (panel == "layers") {
        return pp::foundation::Result<pp::app::ToolsPanel>::success(pp::app::ToolsPanel::layers);
    }
    if (panel == "brush") {
        return pp::foundation::Result<pp::app::ToolsPanel>::success(pp::app::ToolsPanel::brush);
    }
    if (panel == "grids" || panel == "grid") {
        return pp::foundation::Result<pp::app::ToolsPanel>::success(pp::app::ToolsPanel::grids);
    }
    if (panel == "animation") {
        return pp::foundation::Result<pp::app::ToolsPanel>::success(pp::app::ToolsPanel::animation);
    }

    return pp::foundation::Result<pp::app::ToolsPanel>::failure(
        pp::foundation::Status::invalid_argument("unknown tools panel"));
}

pp::foundation::Result<pp::app::AboutMenuCommand> parse_about_menu_command(std::string_view command)
{
    if (command == "help" || command == "help-guide" || command == "manual") {
        return pp::foundation::Result<pp::app::AboutMenuCommand>::success(
            pp::app::AboutMenuCommand::help_guide);
    }
    if (command == "about" || command == "about-app") {
        return pp::foundation::Result<pp::app::AboutMenuCommand>::success(
            pp::app::AboutMenuCommand::about_app);
    }
    if (command == "news" || command == "whats-new") {
        return pp::foundation::Result<pp::app::AboutMenuCommand>::success(
            pp::app::AboutMenuCommand::whats_new);
    }
    if (command == "crash" || command == "induce-crash") {
        return pp::foundation::Result<pp::app::AboutMenuCommand>::success(
            pp::app::AboutMenuCommand::induce_crash);
    }
    if (command == "performance" || command == "perf") {
        return pp::foundation::Result<pp::app::AboutMenuCommand>::success(
            pp::app::AboutMenuCommand::performance_test);
    }

    return pp::foundation::Result<pp::app::AboutMenuCommand>::failure(
        pp::foundation::Status::invalid_argument("unknown about menu command"));
}

const char* document_layer_rename_action_name(pp::app::DocumentLayerRenameAction action) noexcept
{
    switch (action) {
    case pp::app::DocumentLayerRenameAction::no_op_same_name:
        return "no-op-same-name";
    case pp::app::DocumentLayerRenameAction::rename_and_record_undo:
        return "rename-and-record-undo";
    }

    return "no-op-same-name";
}

const char* document_layer_operation_name(pp::app::DocumentLayerOperation operation) noexcept
{
    switch (operation) {
    case pp::app::DocumentLayerOperation::add:
        return "add";
    case pp::app::DocumentLayerOperation::duplicate:
        return "duplicate";
    case pp::app::DocumentLayerOperation::select:
        return "select";
    case pp::app::DocumentLayerOperation::reorder:
        return "reorder";
    case pp::app::DocumentLayerOperation::remove:
        return "remove";
    case pp::app::DocumentLayerOperation::set_opacity:
        return "set-opacity";
    case pp::app::DocumentLayerOperation::set_visibility:
        return "set-visibility";
    case pp::app::DocumentLayerOperation::set_alpha_lock:
        return "set-alpha-lock";
    case pp::app::DocumentLayerOperation::set_blend_mode:
        return "set-blend-mode";
    case pp::app::DocumentLayerOperation::set_highlight:
        return "set-highlight";
    }

    return "select";
}

const char* document_layer_menu_command_name(pp::app::DocumentLayerMenuCommand command) noexcept
{
    switch (command) {
    case pp::app::DocumentLayerMenuCommand::clear:
        return "clear";
    case pp::app::DocumentLayerMenuCommand::rename:
        return "rename";
    case pp::app::DocumentLayerMenuCommand::merge_down:
        return "merge";
    }

    return "clear";
}

const char* document_layer_menu_action_name(pp::app::DocumentLayerMenuAction action) noexcept
{
    switch (action) {
    case pp::app::DocumentLayerMenuAction::clear_current_layer:
        return "clear-current-layer";
    case pp::app::DocumentLayerMenuAction::show_rename_dialog:
        return "show-rename-dialog";
    case pp::app::DocumentLayerMenuAction::merge_with_lower_layer:
        return "merge-with-lower-layer";
    case pp::app::DocumentLayerMenuAction::show_merge_animated_not_supported:
        return "show-merge-animated-not-supported";
    case pp::app::DocumentLayerMenuAction::no_op_select_layer:
        return "no-op-select-layer";
    case pp::app::DocumentLayerMenuAction::no_op_select_upper_layer:
        return "no-op-select-upper-layer";
    }

    return "no-op-select-layer";
}

pp::foundation::Result<pp::app::DocumentLayerMenuCommand> parse_document_layer_menu_command(
    std::string_view command)
{
    if (command == "clear") {
        return pp::foundation::Result<pp::app::DocumentLayerMenuCommand>::success(
            pp::app::DocumentLayerMenuCommand::clear);
    }
    if (command == "rename") {
        return pp::foundation::Result<pp::app::DocumentLayerMenuCommand>::success(
            pp::app::DocumentLayerMenuCommand::rename);
    }
    if (command == "merge" || command == "merge-down") {
        return pp::foundation::Result<pp::app::DocumentLayerMenuCommand>::success(
            pp::app::DocumentLayerMenuCommand::merge_down);
    }

    return pp::foundation::Result<pp::app::DocumentLayerMenuCommand>::failure(
        pp::foundation::Status::invalid_argument("unknown layer menu command"));
}

const char* document_animation_operation_name(pp::app::DocumentAnimationOperation operation) noexcept
{
    switch (operation) {
    case pp::app::DocumentAnimationOperation::add_frame:
        return "add-frame";
    case pp::app::DocumentAnimationOperation::duplicate_frame:
        return "duplicate-frame";
    case pp::app::DocumentAnimationOperation::remove_frame:
        return "remove-frame";
    case pp::app::DocumentAnimationOperation::adjust_duration:
        return "adjust-duration";
    case pp::app::DocumentAnimationOperation::move_frame:
        return "move-frame";
    case pp::app::DocumentAnimationOperation::select_frame:
        return "select-frame";
    case pp::app::DocumentAnimationOperation::goto_frame:
        return "goto-frame";
    case pp::app::DocumentAnimationOperation::goto_next:
        return "goto-next";
    case pp::app::DocumentAnimationOperation::goto_previous:
        return "goto-previous";
    case pp::app::DocumentAnimationOperation::playback_step:
        return "playback-step";
    case pp::app::DocumentAnimationOperation::toggle_playback:
        return "toggle-playback";
    case pp::app::DocumentAnimationOperation::set_onion_size:
        return "set-onion-size";
    }

    return "goto-frame";
}

const char* document_animation_panel_action_name(pp::app::DocumentAnimationPanelAction action) noexcept
{
    switch (action) {
    case pp::app::DocumentAnimationPanelAction::goto_frame:
        return "goto-frame";
    case pp::app::DocumentAnimationPanelAction::next_frame:
        return "next-frame";
    case pp::app::DocumentAnimationPanelAction::previous_frame:
        return "previous-frame";
    case pp::app::DocumentAnimationPanelAction::playback_step:
        return "playback-step";
    case pp::app::DocumentAnimationPanelAction::toggle_playback:
        return "toggle-playback";
    }

    return "goto-frame";
}

pp::foundation::Result<pp::app::DocumentAnimationPanelAction> parse_document_animation_panel_action(
    std::string_view action)
{
    if (action == "goto" || action == "goto-frame") {
        return pp::foundation::Result<pp::app::DocumentAnimationPanelAction>::success(
            pp::app::DocumentAnimationPanelAction::goto_frame);
    }
    if (action == "next" || action == "next-frame") {
        return pp::foundation::Result<pp::app::DocumentAnimationPanelAction>::success(
            pp::app::DocumentAnimationPanelAction::next_frame);
    }
    if (action == "prev" || action == "previous" || action == "previous-frame") {
        return pp::foundation::Result<pp::app::DocumentAnimationPanelAction>::success(
            pp::app::DocumentAnimationPanelAction::previous_frame);
    }
    if (action == "playback" || action == "playback-step") {
        return pp::foundation::Result<pp::app::DocumentAnimationPanelAction>::success(
            pp::app::DocumentAnimationPanelAction::playback_step);
    }
    if (action == "toggle-playback" || action == "play-toggle") {
        return pp::foundation::Result<pp::app::DocumentAnimationPanelAction>::success(
            pp::app::DocumentAnimationPanelAction::toggle_playback);
    }

    return pp::foundation::Result<pp::app::DocumentAnimationPanelAction>::failure(
        pp::foundation::Status::invalid_argument("unknown animation panel action"));
}

const char* brush_ui_texture_slot_name(pp::app::BrushUiTextureSlot slot) noexcept
{
    switch (slot) {
    case pp::app::BrushUiTextureSlot::tip:
        return "tip";
    case pp::app::BrushUiTextureSlot::pattern:
        return "pattern";
    case pp::app::BrushUiTextureSlot::dual:
        return "dual";
    }

    return "tip";
}

const char* brush_ui_operation_name(pp::app::BrushUiOperation operation) noexcept
{
    switch (operation) {
    case pp::app::BrushUiOperation::set_tip_color:
        return "set-tip-color";
    case pp::app::BrushUiOperation::set_texture:
        return "set-texture";
    case pp::app::BrushUiOperation::replace_brush_from_preset:
        return "replace-brush-from-preset";
    case pp::app::BrushUiOperation::stroke_settings_changed:
        return "stroke-settings-changed";
    }

    return "stroke-settings-changed";
}

const char* brush_texture_list_operation_name(pp::app::BrushTextureListOperation operation) noexcept
{
    switch (operation) {
    case pp::app::BrushTextureListOperation::add_texture:
        return "add-texture";
    case pp::app::BrushTextureListOperation::remove_texture:
        return "remove-texture";
    case pp::app::BrushTextureListOperation::move_texture:
        return "move-texture";
    }

    return "add-texture";
}

const char* brush_preset_list_operation_name(pp::app::BrushPresetListOperation operation) noexcept
{
    switch (operation) {
    case pp::app::BrushPresetListOperation::add_current_brush:
        return "add-current-brush";
    case pp::app::BrushPresetListOperation::remove_preset:
        return "remove-preset";
    case pp::app::BrushPresetListOperation::move_preset:
        return "move-preset";
    case pp::app::BrushPresetListOperation::select_preset:
        return "select-preset";
    case pp::app::BrushPresetListOperation::clear_presets:
        return "clear-presets";
    }

    return "select-preset";
}

const char* brush_stroke_control_operation_name(pp::app::BrushStrokeControlOperation operation) noexcept
{
    switch (operation) {
    case pp::app::BrushStrokeControlOperation::set_float:
        return "set-float";
    case pp::app::BrushStrokeControlOperation::set_bool:
        return "set-bool";
    case pp::app::BrushStrokeControlOperation::set_blend_mode:
        return "set-blend-mode";
    case pp::app::BrushStrokeControlOperation::reset_tip_aspect:
        return "reset-tip-aspect";
    case pp::app::BrushStrokeControlOperation::reset_default_brush:
        return "reset-default-brush";
    }

    return "set-float";
}

const char* brush_stroke_float_setting_name(pp::app::BrushStrokeFloatSetting setting) noexcept
{
    switch (setting) {
    case pp::app::BrushStrokeFloatSetting::tip_size: return "tip-size";
    case pp::app::BrushStrokeFloatSetting::tip_spacing: return "tip-spacing";
    case pp::app::BrushStrokeFloatSetting::tip_flow: return "tip-flow";
    case pp::app::BrushStrokeFloatSetting::tip_opacity: return "tip-opacity";
    case pp::app::BrushStrokeFloatSetting::tip_angle: return "tip-angle";
    case pp::app::BrushStrokeFloatSetting::tip_angle_smooth: return "tip-angle-smooth";
    case pp::app::BrushStrokeFloatSetting::tip_mix: return "tip-mix";
    case pp::app::BrushStrokeFloatSetting::tip_wet: return "tip-wet";
    case pp::app::BrushStrokeFloatSetting::tip_noise: return "tip-noise";
    case pp::app::BrushStrokeFloatSetting::tip_hue: return "tip-hue";
    case pp::app::BrushStrokeFloatSetting::tip_saturation: return "tip-saturation";
    case pp::app::BrushStrokeFloatSetting::tip_value: return "tip-value";
    case pp::app::BrushStrokeFloatSetting::jitter_scale: return "jitter-scale";
    case pp::app::BrushStrokeFloatSetting::jitter_angle: return "jitter-angle";
    case pp::app::BrushStrokeFloatSetting::jitter_scatter: return "jitter-scatter";
    case pp::app::BrushStrokeFloatSetting::jitter_flow: return "jitter-flow";
    case pp::app::BrushStrokeFloatSetting::jitter_opacity: return "jitter-opacity";
    case pp::app::BrushStrokeFloatSetting::jitter_hue: return "jitter-hue";
    case pp::app::BrushStrokeFloatSetting::jitter_saturation: return "jitter-saturation";
    case pp::app::BrushStrokeFloatSetting::jitter_value: return "jitter-value";
    case pp::app::BrushStrokeFloatSetting::jitter_aspect: return "jitter-aspect";
    case pp::app::BrushStrokeFloatSetting::dual_size: return "dual-size";
    case pp::app::BrushStrokeFloatSetting::dual_spacing: return "dual-spacing";
    case pp::app::BrushStrokeFloatSetting::dual_scatter: return "dual-scatter";
    case pp::app::BrushStrokeFloatSetting::tip_aspect: return "tip-aspect";
    case pp::app::BrushStrokeFloatSetting::dual_opacity: return "dual-opacity";
    case pp::app::BrushStrokeFloatSetting::dual_flow: return "dual-flow";
    case pp::app::BrushStrokeFloatSetting::dual_rotate: return "dual-rotate";
    case pp::app::BrushStrokeFloatSetting::pattern_scale: return "pattern-scale";
    case pp::app::BrushStrokeFloatSetting::pattern_brightness: return "pattern-brightness";
    case pp::app::BrushStrokeFloatSetting::pattern_contrast: return "pattern-contrast";
    case pp::app::BrushStrokeFloatSetting::pattern_depth: return "pattern-depth";
    }

    return "tip-size";
}

const char* brush_stroke_bool_setting_name(pp::app::BrushStrokeBoolSetting setting) noexcept
{
    switch (setting) {
    case pp::app::BrushStrokeBoolSetting::tip_angle_init: return "tip-angle-init";
    case pp::app::BrushStrokeBoolSetting::tip_angle_follow: return "tip-angle-follow";
    case pp::app::BrushStrokeBoolSetting::tip_flow_pressure: return "tip-flow-pressure";
    case pp::app::BrushStrokeBoolSetting::tip_opacity_pressure: return "tip-opacity-pressure";
    case pp::app::BrushStrokeBoolSetting::tip_size_pressure: return "tip-size-pressure";
    case pp::app::BrushStrokeBoolSetting::jitter_scatter_both_axis: return "jitter-scatter-both-axis";
    case pp::app::BrushStrokeBoolSetting::jitter_aspect_both_axis: return "jitter-aspect-both-axis";
    case pp::app::BrushStrokeBoolSetting::jitter_hsv_each_sample: return "jitter-hsv-each-sample";
    case pp::app::BrushStrokeBoolSetting::tip_invert: return "tip-invert";
    case pp::app::BrushStrokeBoolSetting::tip_flip_x: return "tip-flip-x";
    case pp::app::BrushStrokeBoolSetting::tip_flip_y: return "tip-flip-y";
    case pp::app::BrushStrokeBoolSetting::pattern_enabled: return "pattern-enabled";
    case pp::app::BrushStrokeBoolSetting::dual_enabled: return "dual-enabled";
    case pp::app::BrushStrokeBoolSetting::dual_scatter_both_axis: return "dual-scatter-both-axis";
    case pp::app::BrushStrokeBoolSetting::dual_invert: return "dual-invert";
    case pp::app::BrushStrokeBoolSetting::dual_flip_x: return "dual-flip-x";
    case pp::app::BrushStrokeBoolSetting::dual_flip_y: return "dual-flip-y";
    case pp::app::BrushStrokeBoolSetting::dual_random_flip: return "dual-random-flip";
    case pp::app::BrushStrokeBoolSetting::tip_random_flip_x: return "tip-random-flip-x";
    case pp::app::BrushStrokeBoolSetting::tip_random_flip_y: return "tip-random-flip-y";
    case pp::app::BrushStrokeBoolSetting::pattern_each_sample: return "pattern-each-sample";
    case pp::app::BrushStrokeBoolSetting::pattern_invert: return "pattern-invert";
    case pp::app::BrushStrokeBoolSetting::pattern_flip_x: return "pattern-flip-x";
    case pp::app::BrushStrokeBoolSetting::pattern_flip_y: return "pattern-flip-y";
    case pp::app::BrushStrokeBoolSetting::pattern_random_offset: return "pattern-random-offset";
    }

    return "tip-angle-init";
}

const char* brush_stroke_blend_setting_name(pp::app::BrushStrokeBlendSetting setting) noexcept
{
    switch (setting) {
    case pp::app::BrushStrokeBlendSetting::tip:
        return "tip";
    case pp::app::BrushStrokeBlendSetting::dual:
        return "dual";
    case pp::app::BrushStrokeBlendSetting::pattern:
        return "pattern";
    }

    return "tip";
}

const char* canvas_tool_operation_name(pp::app::CanvasToolOperation operation) noexcept
{
    switch (operation) {
    case pp::app::CanvasToolOperation::select_mode:
        return "select-mode";
    case pp::app::CanvasToolOperation::toggle_picking:
        return "toggle-picking";
    case pp::app::CanvasToolOperation::toggle_touch_lock:
        return "toggle-touch-lock";
    }

    return "select-mode";
}

const char* canvas_tool_toolbar_action_name(pp::app::CanvasToolToolbarAction action) noexcept
{
    switch (action) {
    case pp::app::CanvasToolToolbarAction::select_mode:
        return "select-mode";
    case pp::app::CanvasToolToolbarAction::toggle_picking:
        return "toggle-picking";
    case pp::app::CanvasToolToolbarAction::toggle_touch_lock:
        return "toggle-touch-lock";
    }

    return "select-mode";
}

const char* canvas_tool_mode_name(pp::app::CanvasToolMode mode) noexcept
{
    switch (mode) {
    case pp::app::CanvasToolMode::draw:
        return "draw";
    case pp::app::CanvasToolMode::erase:
        return "erase";
    case pp::app::CanvasToolMode::line:
        return "line";
    case pp::app::CanvasToolMode::camera:
        return "camera";
    case pp::app::CanvasToolMode::grid:
        return "grid";
    case pp::app::CanvasToolMode::copy:
        return "copy";
    case pp::app::CanvasToolMode::cut:
        return "cut";
    case pp::app::CanvasToolMode::fill:
        return "fill";
    case pp::app::CanvasToolMode::mask_free:
        return "mask-free";
    case pp::app::CanvasToolMode::mask_line:
        return "mask-line";
    case pp::app::CanvasToolMode::flood_fill:
        return "bucket";
    }

    return "draw";
}

const char* canvas_tool_transform_action_name(pp::app::CanvasToolTransformAction action) noexcept
{
    switch (action) {
    case pp::app::CanvasToolTransformAction::none:
        return "none";
    case pp::app::CanvasToolTransformAction::copy:
        return "copy";
    case pp::app::CanvasToolTransformAction::cut:
        return "cut";
    }

    return "none";
}

const char* canvas_cursor_visibility_mode_name(pp::app::CanvasCursorVisibilityMode mode) noexcept
{
    switch (mode) {
    case pp::app::CanvasCursorVisibilityMode::never:
        return "never";
    case pp::app::CanvasCursorVisibilityMode::small_brush:
        return "small-brush";
    case pp::app::CanvasCursorVisibilityMode::not_painting:
        return "not-painting";
    case pp::app::CanvasCursorVisibilityMode::always:
        return "always";
    }

    return "never";
}

const char* canvas_hotkey_event_name(pp::app::CanvasHotkeyEvent event) noexcept
{
    switch (event) {
    case pp::app::CanvasHotkeyEvent::key_down:
        return "key-down";
    case pp::app::CanvasHotkeyEvent::key_up:
        return "key-up";
    case pp::app::CanvasHotkeyEvent::touch_tap:
        return "touch-tap";
    }

    return "key-up";
}

const char* canvas_hotkey_key_name(pp::app::CanvasHotkeyKey key) noexcept
{
    switch (key) {
    case pp::app::CanvasHotkeyKey::other:
        return "other";
    case pp::app::CanvasHotkeyKey::android_back:
        return "android-back";
    case pp::app::CanvasHotkeyKey::alt:
        return "alt";
    case pp::app::CanvasHotkeyKey::e:
        return "e";
    case pp::app::CanvasHotkeyKey::s:
        return "s";
    case pp::app::CanvasHotkeyKey::tab:
        return "tab";
    case pp::app::CanvasHotkeyKey::z:
        return "z";
    case pp::app::CanvasHotkeyKey::bracket_left:
        return "bracket-left";
    case pp::app::CanvasHotkeyKey::bracket_right:
        return "bracket-right";
    }

    return "other";
}

const char* canvas_hotkey_action_name(pp::app::CanvasHotkeyAction action) noexcept
{
    switch (action) {
    case pp::app::CanvasHotkeyAction::none:
        return "none";
    case pp::app::CanvasHotkeyAction::select_tool:
        return "select-tool";
    case pp::app::CanvasHotkeyAction::history:
        return "history";
    case pp::app::CanvasHotkeyAction::save_document:
        return "save-document";
    case pp::app::CanvasHotkeyAction::toggle_ui:
        return "toggle-ui";
    case pp::app::CanvasHotkeyAction::adjust_brush_size:
        return "adjust-brush-size";
    case pp::app::CanvasHotkeyAction::show_cursor:
        return "show-cursor";
    }

    return "none";
}

const char* grid_ui_operation_name(pp::app::GridUiOperation operation) noexcept
{
    switch (operation) {
    case pp::app::GridUiOperation::request_heightmap_pick:
        return "request-heightmap-pick";
    case pp::app::GridUiOperation::load_heightmap:
        return "load-heightmap";
    case pp::app::GridUiOperation::clear_heightmap:
        return "clear-heightmap";
    case pp::app::GridUiOperation::reload_heightmap:
        return "reload-heightmap";
    case pp::app::GridUiOperation::render_lightmap:
        return "render-lightmap";
    case pp::app::GridUiOperation::commit_heightmap:
        return "commit-heightmap";
    }

    return "request-heightmap-pick";
}

const char* history_ui_operation_name(pp::app::HistoryUiOperation operation) noexcept
{
    switch (operation) {
    case pp::app::HistoryUiOperation::undo:
        return "undo";
    case pp::app::HistoryUiOperation::redo:
        return "redo";
    case pp::app::HistoryUiOperation::clear:
        return "clear";
    }

    return "undo";
}

const char* main_toolbar_command_name(pp::app::MainToolbarCommand command) noexcept
{
    switch (command) {
    case pp::app::MainToolbarCommand::open_document:
        return "open";
    case pp::app::MainToolbarCommand::save_document:
        return "save";
    case pp::app::MainToolbarCommand::undo:
        return "undo";
    case pp::app::MainToolbarCommand::redo:
        return "redo";
    case pp::app::MainToolbarCommand::clear_history:
        return "clear-history";
    case pp::app::MainToolbarCommand::clear_canvas:
        return "clear-canvas";
    case pp::app::MainToolbarCommand::show_message_box:
        return "message-box";
    case pp::app::MainToolbarCommand::show_settings:
        return "settings";
    }

    return "open";
}

const char* main_toolbar_action_name(pp::app::MainToolbarAction action) noexcept
{
    switch (action) {
    case pp::app::MainToolbarAction::show_open_dialog:
        return "show-open-dialog";
    case pp::app::MainToolbarAction::show_save_dialog:
        return "show-save-dialog";
    case pp::app::MainToolbarAction::invoke_undo:
        return "invoke-undo";
    case pp::app::MainToolbarAction::invoke_redo:
        return "invoke-redo";
    case pp::app::MainToolbarAction::clear_history:
        return "clear-history";
    case pp::app::MainToolbarAction::clear_canvas:
        return "clear-canvas";
    case pp::app::MainToolbarAction::show_message_box:
        return "show-message-box";
    case pp::app::MainToolbarAction::show_settings_dialog:
        return "show-settings-dialog";
    case pp::app::MainToolbarAction::no_op_unavailable:
        return "no-op-unavailable";
    }

    return "no-op-unavailable";
}

const char* quick_ui_slot_kind_name(pp::app::QuickUiSlotKind kind) noexcept
{
    switch (kind) {
    case pp::app::QuickUiSlotKind::brush:
        return "brush";
    case pp::app::QuickUiSlotKind::color:
        return "color";
    }

    return "brush";
}

const char* quick_ui_operation_name(pp::app::QuickUiOperation operation) noexcept
{
    switch (operation) {
    case pp::app::QuickUiOperation::select_slot:
        return "select-slot";
    case pp::app::QuickUiOperation::open_slot_popup:
        return "open-slot-popup";
    case pp::app::QuickUiOperation::restore_state:
        return "restore-state";
    case pp::app::QuickUiOperation::reset_state:
        return "reset-state";
    }

    return "select-slot";
}

const char* document_file_write_decision_name(pp::app::DocumentFileWriteDecision decision) noexcept
{
    switch (decision) {
    case pp::app::DocumentFileWriteDecision::save_now:
        return "save-now";
    case pp::app::DocumentFileWriteDecision::prompt_overwrite:
        return "prompt-overwrite";
    }

    return "save-now";
}

const char* document_export_start_decision_name(pp::app::DocumentExportStartDecision decision) noexcept
{
    switch (decision) {
    case pp::app::DocumentExportStartDecision::start_now:
        return "start-now";
    case pp::app::DocumentExportStartDecision::show_license_disabled:
        return "show-license-disabled";
    case pp::app::DocumentExportStartDecision::unavailable_no_canvas:
        return "unavailable-no-canvas";
    }

    return "unavailable-no-canvas";
}

const char* document_export_menu_kind_name(pp::app::DocumentExportMenuKind kind) noexcept
{
    switch (kind) {
    case pp::app::DocumentExportMenuKind::jpeg:
        return "jpeg";
    case pp::app::DocumentExportMenuKind::png:
        return "png";
    case pp::app::DocumentExportMenuKind::layers:
        return "layers";
    case pp::app::DocumentExportMenuKind::cube_faces:
        return "cube-faces";
    case pp::app::DocumentExportMenuKind::depth:
        return "depth";
    case pp::app::DocumentExportMenuKind::animation_frames:
        return "animation-frames";
    case pp::app::DocumentExportMenuKind::animation_mp4:
        return "animation-mp4";
    case pp::app::DocumentExportMenuKind::timelapse:
        return "timelapse";
    }

    return "jpeg";
}

const char* document_export_menu_action_name(pp::app::DocumentExportMenuAction action) noexcept
{
    switch (action) {
    case pp::app::DocumentExportMenuAction::show_jpeg_dialog:
        return "show-jpeg-dialog";
    case pp::app::DocumentExportMenuAction::show_png_dialog:
        return "show-png-dialog";
    case pp::app::DocumentExportMenuAction::show_layers_dialog:
        return "show-layers-dialog";
    case pp::app::DocumentExportMenuAction::show_cube_faces_dialog:
        return "show-cube-faces-dialog";
    case pp::app::DocumentExportMenuAction::show_depth_dialog:
        return "show-depth-dialog";
    case pp::app::DocumentExportMenuAction::show_animation_frames_dialog:
        return "show-animation-frames-dialog";
    case pp::app::DocumentExportMenuAction::show_animation_mp4_dialog:
        return "show-animation-mp4-dialog";
    case pp::app::DocumentExportMenuAction::show_timelapse_dialog:
        return "show-timelapse-dialog";
    case pp::app::DocumentExportMenuAction::show_license_disabled:
        return "show-license-disabled";
    case pp::app::DocumentExportMenuAction::unavailable_no_canvas:
        return "unavailable-no-canvas";
    }

    return "unavailable-no-canvas";
}

const char* document_export_execution_kind_name(pp::app::DocumentExportExecutionKind kind) noexcept
{
    switch (kind) {
    case pp::app::DocumentExportExecutionKind::equirectangular_file:
        return "equirectangular-file";
    case pp::app::DocumentExportExecutionKind::layers_collection:
        return "layers-collection";
    case pp::app::DocumentExportExecutionKind::layers_stem:
        return "layers-stem";
    case pp::app::DocumentExportExecutionKind::animation_frames_collection:
        return "animation-frames-collection";
    case pp::app::DocumentExportExecutionKind::animation_frames_stem:
        return "animation-frames-stem";
    case pp::app::DocumentExportExecutionKind::depth:
        return "depth";
    case pp::app::DocumentExportExecutionKind::cube_faces:
        return "cube-faces";
    case pp::app::DocumentExportExecutionKind::animation_mp4:
        return "animation-mp4";
    case pp::app::DocumentExportExecutionKind::timelapse:
        return "timelapse";
    }

    return "equirectangular-file";
}

const char* document_export_snapshot_route_action_name(
    pp::app::DocumentExportSnapshotRouteAction action) noexcept
{
    switch (action) {
    case pp::app::DocumentExportSnapshotRouteAction::use_document_snapshot_writer:
        return "use-document-snapshot-writer";
    case pp::app::DocumentExportSnapshotRouteAction::use_legacy_export:
        return "use-legacy-export";
    }

    return "use-legacy-export";
}

pp::foundation::Result<pp::app::DocumentExportMenuKind> parse_document_export_menu_kind(
    std::string_view kind)
{
    if (kind == "jpeg" || kind == "jpg") {
        return pp::foundation::Result<pp::app::DocumentExportMenuKind>::success(
            pp::app::DocumentExportMenuKind::jpeg);
    }
    if (kind == "png") {
        return pp::foundation::Result<pp::app::DocumentExportMenuKind>::success(
            pp::app::DocumentExportMenuKind::png);
    }
    if (kind == "layers") {
        return pp::foundation::Result<pp::app::DocumentExportMenuKind>::success(
            pp::app::DocumentExportMenuKind::layers);
    }
    if (kind == "cube-faces" || kind == "cube") {
        return pp::foundation::Result<pp::app::DocumentExportMenuKind>::success(
            pp::app::DocumentExportMenuKind::cube_faces);
    }
    if (kind == "depth") {
        return pp::foundation::Result<pp::app::DocumentExportMenuKind>::success(
            pp::app::DocumentExportMenuKind::depth);
    }
    if (kind == "animation-frames" || kind == "anim") {
        return pp::foundation::Result<pp::app::DocumentExportMenuKind>::success(
            pp::app::DocumentExportMenuKind::animation_frames);
    }
    if (kind == "animation-mp4" || kind == "mp4") {
        return pp::foundation::Result<pp::app::DocumentExportMenuKind>::success(
            pp::app::DocumentExportMenuKind::animation_mp4);
    }
    if (kind == "timelapse") {
        return pp::foundation::Result<pp::app::DocumentExportMenuKind>::success(
            pp::app::DocumentExportMenuKind::timelapse);
    }

    return pp::foundation::Result<pp::app::DocumentExportMenuKind>::failure(
        pp::foundation::Status::invalid_argument("unknown export menu kind"));
}

pp::foundation::Result<pp::app::DocumentExportExecutionKind> parse_document_export_execution_kind(
    std::string_view kind)
{
    if (kind == "equirectangular" || kind == "equirect" || kind == "image" || kind == "equirectangular-file") {
        return pp::foundation::Result<pp::app::DocumentExportExecutionKind>::success(
            pp::app::DocumentExportExecutionKind::equirectangular_file);
    }
    if (kind == "layers" || kind == "layers-collection") {
        return pp::foundation::Result<pp::app::DocumentExportExecutionKind>::success(
            pp::app::DocumentExportExecutionKind::layers_collection);
    }
    if (kind == "layers-stem") {
        return pp::foundation::Result<pp::app::DocumentExportExecutionKind>::success(
            pp::app::DocumentExportExecutionKind::layers_stem);
    }
    if (kind == "animation-frames" || kind == "frames" || kind == "animation-frames-collection") {
        return pp::foundation::Result<pp::app::DocumentExportExecutionKind>::success(
            pp::app::DocumentExportExecutionKind::animation_frames_collection);
    }
    if (kind == "animation-frames-stem" || kind == "frames-stem") {
        return pp::foundation::Result<pp::app::DocumentExportExecutionKind>::success(
            pp::app::DocumentExportExecutionKind::animation_frames_stem);
    }
    if (kind == "depth") {
        return pp::foundation::Result<pp::app::DocumentExportExecutionKind>::success(
            pp::app::DocumentExportExecutionKind::depth);
    }
    if (kind == "cube-faces" || kind == "cube") {
        return pp::foundation::Result<pp::app::DocumentExportExecutionKind>::success(
            pp::app::DocumentExportExecutionKind::cube_faces);
    }
    if (kind == "animation-mp4" || kind == "mp4") {
        return pp::foundation::Result<pp::app::DocumentExportExecutionKind>::success(
            pp::app::DocumentExportExecutionKind::animation_mp4);
    }
    if (kind == "timelapse") {
        return pp::foundation::Result<pp::app::DocumentExportExecutionKind>::success(
            pp::app::DocumentExportExecutionKind::timelapse);
    }

    return pp::foundation::Result<pp::app::DocumentExportExecutionKind>::failure(
        pp::foundation::Status::invalid_argument("unknown export execution kind"));
}

const char* document_export_success_kind_name(pp::app::DocumentExportSuccessKind kind) noexcept
{
    switch (kind) {
    case pp::app::DocumentExportSuccessKind::equirectangular:
        return "equirectangular";
    case pp::app::DocumentExportSuccessKind::layers:
        return "layers";
    case pp::app::DocumentExportSuccessKind::animation_frames:
        return "animation-frames";
    case pp::app::DocumentExportSuccessKind::depth:
        return "depth";
    case pp::app::DocumentExportSuccessKind::cube_faces:
        return "cube-faces";
    case pp::app::DocumentExportSuccessKind::animation_mp4:
        return "animation-mp4";
    case pp::app::DocumentExportSuccessKind::timelapse:
        return "timelapse";
    }

    return "equirectangular";
}

const char* document_export_success_destination_name(
    pp::app::DocumentExportSuccessDestination destination) noexcept
{
    switch (destination) {
    case pp::app::DocumentExportSuccessDestination::suppressed:
        return "suppressed";
    case pp::app::DocumentExportSuccessDestination::photos:
        return "photos";
    case pp::app::DocumentExportSuccessDestination::pictures_panopainter:
        return "pictures-panopainter";
    case pp::app::DocumentExportSuccessDestination::files_panopainter:
        return "files-panopainter";
    case pp::app::DocumentExportSuccessDestination::work_directory:
        return "work-directory";
    case pp::app::DocumentExportSuccessDestination::path:
        return "path";
    case pp::app::DocumentExportSuccessDestination::generic_success:
        return "generic-success";
    }

    return "suppressed";
}

pp::foundation::Result<pp::app::DocumentExportSuccessKind> parse_document_export_success_kind(
    std::string_view kind)
{
    if (kind == "equirectangular" || kind == "equirect" || kind == "image") {
        return pp::foundation::Result<pp::app::DocumentExportSuccessKind>::success(
            pp::app::DocumentExportSuccessKind::equirectangular);
    }
    if (kind == "layers") {
        return pp::foundation::Result<pp::app::DocumentExportSuccessKind>::success(
            pp::app::DocumentExportSuccessKind::layers);
    }
    if (kind == "animation-frames" || kind == "frames") {
        return pp::foundation::Result<pp::app::DocumentExportSuccessKind>::success(
            pp::app::DocumentExportSuccessKind::animation_frames);
    }
    if (kind == "depth") {
        return pp::foundation::Result<pp::app::DocumentExportSuccessKind>::success(
            pp::app::DocumentExportSuccessKind::depth);
    }
    if (kind == "cube-faces" || kind == "cube") {
        return pp::foundation::Result<pp::app::DocumentExportSuccessKind>::success(
            pp::app::DocumentExportSuccessKind::cube_faces);
    }
    if (kind == "animation-mp4" || kind == "mp4") {
        return pp::foundation::Result<pp::app::DocumentExportSuccessKind>::success(
            pp::app::DocumentExportSuccessKind::animation_mp4);
    }
    if (kind == "timelapse") {
        return pp::foundation::Result<pp::app::DocumentExportSuccessKind>::success(
            pp::app::DocumentExportSuccessKind::timelapse);
    }

    return pp::foundation::Result<pp::app::DocumentExportSuccessKind>::failure(
        pp::foundation::Status::invalid_argument("unknown export message kind"));
}

pp::foundation::Result<pp::app::DocumentExportSuccessDestination> parse_document_export_success_destination(
    std::string_view destination)
{
    if (destination == "suppressed" || destination == "none") {
        return pp::foundation::Result<pp::app::DocumentExportSuccessDestination>::success(
            pp::app::DocumentExportSuccessDestination::suppressed);
    }
    if (destination == "photos") {
        return pp::foundation::Result<pp::app::DocumentExportSuccessDestination>::success(
            pp::app::DocumentExportSuccessDestination::photos);
    }
    if (destination == "pictures" || destination == "pictures-panopainter") {
        return pp::foundation::Result<pp::app::DocumentExportSuccessDestination>::success(
            pp::app::DocumentExportSuccessDestination::pictures_panopainter);
    }
    if (destination == "files" || destination == "files-panopainter") {
        return pp::foundation::Result<pp::app::DocumentExportSuccessDestination>::success(
            pp::app::DocumentExportSuccessDestination::files_panopainter);
    }
    if (destination == "work" || destination == "work-directory") {
        return pp::foundation::Result<pp::app::DocumentExportSuccessDestination>::success(
            pp::app::DocumentExportSuccessDestination::work_directory);
    }
    if (destination == "path") {
        return pp::foundation::Result<pp::app::DocumentExportSuccessDestination>::success(
            pp::app::DocumentExportSuccessDestination::path);
    }
    if (destination == "success" || destination == "generic-success") {
        return pp::foundation::Result<pp::app::DocumentExportSuccessDestination>::success(
            pp::app::DocumentExportSuccessDestination::generic_success);
    }

    return pp::foundation::Result<pp::app::DocumentExportSuccessDestination>::failure(
        pp::foundation::Status::invalid_argument("unknown export message destination"));
}

const char* cloud_upload_action_name(pp::app::CloudUploadAction action) noexcept
{
    switch (action) {
    case pp::app::CloudUploadAction::unavailable_no_canvas:
        return "unavailable-no-canvas";
    case pp::app::CloudUploadAction::show_save_required_warning:
        return "show-save-required-warning";
    case pp::app::CloudUploadAction::prompt_publish:
        return "prompt-publish";
    }

    return "unavailable-no-canvas";
}

const char* cloud_browse_action_name(pp::app::CloudBrowseAction action) noexcept
{
    switch (action) {
    case pp::app::CloudBrowseAction::unavailable_no_canvas:
        return "unavailable-no-canvas";
    case pp::app::CloudBrowseAction::show_browser:
        return "show-browser";
    }

    return "unavailable-no-canvas";
}

const char* cloud_download_selection_action_name(pp::app::CloudDownloadSelectionAction action) noexcept
{
    switch (action) {
    case pp::app::CloudDownloadSelectionAction::wait_for_selection:
        return "wait-for-selection";
    case pp::app::CloudDownloadSelectionAction::start_download:
        return "start-download";
    }

    return "wait-for-selection";
}

const char* cloud_transfer_direction_name(pp::app::CloudTransferDirection direction) noexcept
{
    switch (direction) {
    case pp::app::CloudTransferDirection::download:
        return "download";
    case pp::app::CloudTransferDirection::upload:
        return "upload";
    }

    return "download";
}

const char* cloud_transfer_action_name(pp::app::CloudTransferAction action) noexcept
{
    switch (action) {
    case pp::app::CloudTransferAction::reject_missing_source:
        return "reject-missing-source";
    case pp::app::CloudTransferAction::reject_missing_destination:
        return "reject-missing-destination";
    case pp::app::CloudTransferAction::start_transfer:
        return "start-transfer";
    }

    return "reject-missing-source";
}

const char* app_dialog_kind_name(pp::app::AppDialogKind kind) noexcept
{
    switch (kind) {
    case pp::app::AppDialogKind::progress:
        return "progress";
    case pp::app::AppDialogKind::message:
        return "message";
    case pp::app::AppDialogKind::input:
        return "input";
    }

    return "progress";
}

const char* recording_start_action_name(pp::app::RecordingStartAction action) noexcept
{
    switch (action) {
    case pp::app::RecordingStartAction::start_thread:
        return "start-thread";
    case pp::app::RecordingStartAction::no_op_already_running:
        return "no-op-already-running";
    }

    return "no-op-already-running";
}

const char* recording_stop_action_name(pp::app::RecordingStopAction action) noexcept
{
    switch (action) {
    case pp::app::RecordingStopAction::stop_thread:
        return "stop-thread";
    case pp::app::RecordingStopAction::no_op_not_running:
        return "no-op-not-running";
    }

    return "no-op-not-running";
}

const char* document_share_action_name(pp::app::DocumentShareAction action) noexcept
{
    switch (action) {
    case pp::app::DocumentShareAction::show_save_required_warning:
        return "show-save-required-warning";
    case pp::app::DocumentShareAction::share_now:
        return "share-now";
    }

    return "show-save-required-warning";
}

const char* picked_path_action_name(pp::app::PickedPathAction action) noexcept
{
    switch (action) {
    case pp::app::PickedPathAction::ignore_empty_path:
        return "ignore-empty-path";
    case pp::app::PickedPathAction::invoke_callback:
        return "invoke-callback";
    }

    return "ignore-empty-path";
}

const char* display_file_action_name(pp::app::DisplayFileAction action) noexcept
{
    switch (action) {
    case pp::app::DisplayFileAction::ignore_empty_path:
        return "ignore-empty-path";
    case pp::app::DisplayFileAction::open_external_file:
        return "open-external-file";
    }

    return "ignore-empty-path";
}

const char* virtual_keyboard_action_name(pp::app::VirtualKeyboardAction action) noexcept
{
    switch (action) {
    case pp::app::VirtualKeyboardAction::show_keyboard:
        return "show-keyboard";
    case pp::app::VirtualKeyboardAction::hide_keyboard:
        return "hide-keyboard";
    }

    return "hide-keyboard";
}

const char* cursor_visibility_action_name(pp::app::CursorVisibilityAction action) noexcept
{
    switch (action) {
    case pp::app::CursorVisibilityAction::show_cursor:
        return "show-cursor";
    case pp::app::CursorVisibilityAction::hide_cursor:
        return "hide-cursor";
    }

    return "hide-cursor";
}

const char* clipboard_read_action_name(pp::app::ClipboardReadAction action) noexcept
{
    switch (action) {
    case pp::app::ClipboardReadAction::read_text:
        return "read-text";
    }

    return "read-text";
}

const char* clipboard_write_action_name(pp::app::ClipboardWriteAction action) noexcept
{
    switch (action) {
    case pp::app::ClipboardWriteAction::write_text:
        return "write-text";
    }

    return "write-text";
}

const char* interface_direction_name(pp::app::InterfaceDirection direction) noexcept
{
    switch (direction) {
    case pp::app::InterfaceDirection::left_to_right:
        return "left-to-right";
    case pp::app::InterfaceDirection::right_to_left:
        return "right-to-left";
    }

    return "left-to-right";
}

const char* timelapse_recording_action_name(pp::app::TimelapseRecordingAction action) noexcept
{
    switch (action) {
    case pp::app::TimelapseRecordingAction::no_op:
        return "no-op";
    case pp::app::TimelapseRecordingAction::start_recording:
        return "start-recording";
    case pp::app::TimelapseRecordingAction::stop_recording:
        return "stop-recording";
    }

    return "no-op";
}

const char* command_convert_step_name(pp::app::CommandConvertStep step) noexcept
{
    switch (step) {
    case pp::app::CommandConvertStep::apply_renderer_state:
        return "apply-renderer-state";
    case pp::app::CommandConvertStep::create_canvas:
        return "create-canvas";
    case pp::app::CommandConvertStep::open_project:
        return "open-project";
    case pp::app::CommandConvertStep::export_equirectangular:
        return "export-equirectangular";
    }

    return "unknown";
}

pp::foundation::Result<float> parse_float_arg(std::string_view text)
{
    float value = 0.0F;
    const auto* begin = text.data();
    const auto* end = begin + text.size();
    const auto [ptr, ec] = std::from_chars(begin, end, value);
    if (ec != std::errc {} || ptr != end) {
        return pp::foundation::Result<float>::failure(
            pp::foundation::Status::invalid_argument("invalid floating-point value"));
    }

    if (!std::isfinite(value)) {
        return pp::foundation::Result<float>::failure(
            pp::foundation::Status::invalid_argument("floating-point value must be finite"));
    }

    return pp::foundation::Result<float>::success(value);
}

pp::foundation::Result<int> parse_i32_arg(std::string_view text)
{
    int value = 0;
    const auto* begin = text.data();
    const auto* end = begin + text.size();
    const auto [ptr, ec] = std::from_chars(begin, end, value);
    if (ec != std::errc {} || ptr != end) {
        return pp::foundation::Result<int>::failure(
            pp::foundation::Status::invalid_argument("invalid signed integer value"));
    }

    return pp::foundation::Result<int>::success(value);
}

pp::foundation::Result<std::int64_t> parse_i64_arg(std::string_view text)
{
    std::int64_t value = 0;
    const auto* begin = text.data();
    const auto* end = begin + text.size();
    const auto [ptr, ec] = std::from_chars(begin, end, value);
    if (ec != std::errc {} || ptr != end) {
        return pp::foundation::Result<std::int64_t>::failure(
            pp::foundation::Status::invalid_argument("invalid signed integer value"));
    }

    return pp::foundation::Result<std::int64_t>::success(value);
}

void print_help()
{
    std::cout
        << "pano_cli commands:\n"
        << "  apply-stroke-script --path FILE --output FILE [--width N] [--height N]\n"
        << "  create-document --width N --height N [--layers N] [--frames N] [--frame-duration-ms N]\n"
        << "  export-image --path FILE [--width N] [--height N]\n"
        << "  inspect-image --path FILE\n"
        << "  import-image --path FILE [--document-width N] [--document-height N] [--face N] [--x N] [--y N]\n"
        << "  inspect-project --path FILE\n"
        << "  classify-open --path FILE\n"
        << "  plan-open-route --path FILE [--unsaved]\n"
        << "  plan-file-menu --command new|import|open|browse|save|save-as|save-version|export|export-submenu|share|resize|cloud-upload|cloud-browse\n"
        << "  plan-new-document --work-dir DIR --name NAME [--resolution-index N] [--target-exists]\n"
        << "  plan-document-file --work-dir DIR --name NAME [--target-exists]\n"
        << "  plan-document-version --directory DIR --doc-name NAME [--existing-path FILE]\n"
        << "  plan-document-session-prompt --kind close-unsaved|save-before-workflow|new-document-overwrite|file-overwrite|save-error [--name NAME]\n"
        << "  plan-export-start [--requires-license] [--demo] [--no-canvas]\n"
        << "  plan-export-menu --kind jpeg|png|layers|cube-faces|depth|animation-frames|animation-mp4|timelapse [--demo] [--no-canvas]\n"
        << "  plan-export-snapshot-route --kind equirectangular|layers-collection|layers-stem|animation-frames-collection|animation-frames-stem|cube-faces|depth [--target-path FILE] [--captured-face-payloads N] [--pending-face-payloads N] [--unsupported-target] [--unsupported-platform]\n"
        << "  plan-export-target --kind file|collection|stem|cube-faces|name --doc-name NAME [--work-dir DIR] [--directory DIR] [--extension EXT] [--suffix SUFFIX]\n"
        << "  plan-export-message --kind equirectangular|layers|animation-frames|depth|cube-faces|animation-mp4|timelapse --destination photos|pictures|files|work|path|success|suppressed [--detail TEXT]\n"
        << "  plan-export-report --kind license-disabled|equirectangular|layers|animation-frames|depth|cube-faces|animation-mp4|timelapse [--message TEXT]\n"
        << "  plan-cloud-upload [--no-canvas] [--new-document] [--unsaved]\n"
        << "  plan-cloud-browse [--no-canvas] [--selected-file FILE]\n"
        << "  plan-cloud-upload-all [--file-count N] [--no-progress-ui]\n"
        << "  plan-cloud-transfer [--direction download|upload] [--source TEXT] [--destination FILE] [--progress] [--disable-tls-verification] [--progress-total N] [--progress-current N]\n"
        << "  plan-app-dialog --kind progress|message|input [--title TEXT] [--message TEXT] [--field-name TEXT] [--ok-caption TEXT] [--total N] [--cancel]\n"
        << "  plan-recording-session [--running] [--frame-count N] [--platform-deletes-recorded-files] [--no-encoder] [--no-canvas]\n"
        << "  plan-app-preferences [--ui-scale N] [--display-density N] [--current-scale N] [--scale-option N] [--viewport-scale N] [--rtl] [--timelapse-disabled] [--recording-running] [--vr-controllers-disabled] [--cursor-mode N]\n"
        << "  plan-app-startup [--run-counter N] [--auto-timelapse-disabled] [--vr-controllers-disabled] [--license-invalid]\n"
        << "  plan-app-startup-resources [--width N] [--height N] [--bad-size]\n"
        << "  plan-app-frame [--redraw] [--animate] [--no-designer-layout] [--no-main-layout] [--no-canvas] [--no-canvas-document] [--vr-active] [--ui-hidden] [--vr-only] [--resize-width N] [--resize-height N] [--bad-resize] [--observer-hidden] [--observer-on-screen] [--observer-clipped-out] [--observer-bad-geometry]\n"
        << "  plan-app-thread --kind dispatch|render-drain|ui-drain|ui-tick|ui-loop|redraw|start|stop [--require-ui-thread] [--on-target-thread] [--unique] [--worker-stopped] [--wait] [--request-redraw] [--redraw] [--live-reload] [--not-joinable] [--queued-tasks N] [--rendered-frames N] [--dt N] [--frame-accumulator N] [--fps-accumulator N] [--reload-accumulator N] [--bad-timer]\n"
        << "  plan-app-input --kind pointer|gesture|cancel|main|key|ui-toggle|stylus [--x N] [--y N] [--x1 N] [--y1 N] [--prev-x N] [--prev-y N] [--prev-x1 N] [--prev-y1 N] [--zoom N] [--no-designer-layout] [--no-main-layout] [--spacebar] [--vr-active] [--key-up] [--ui-hidden] [--no-canvas] [--main-child-count N] [--panel-child-count N] [--bad-float]\n"
        << "  plan-app-shutdown\n"
        << "  plan-command-convert [--project FILE] [--output FILE] [--canvas-resolution N]\n"
        << "  plan-app-status [--doc-name NAME] [--unsaved] [--resolution N] [--resolution-index N] [--zoom N] [--history-bytes N] [--recording-running] [--encoder-available] [--encoded-frames N] [--framebuffer-fetch] [--float32] [--float32-linear] [--float16]\n"
        << "  plan-brush-package-import --kind abr|ppbr --path FILE\n"
        << "  plan-brush-package-export --path FILE [--author NAME] [--email EMAIL] [--url URL] [--description TEXT] [--dest-path DIR] [--export-data|--no-export-data] [--header-image]\n"
        << "  plan-tools-menu --command panels|options|clear-grids|reset-camera|shortcuts|sonarpen [--sonarpen-available]\n"
        << "  plan-tools-panel --panel presets|color|color-advanced|layers|brush|grids|animation [--already-visible]\n"
        << "  plan-about-menu --command help|about|news|crash|performance [--version-major N] [--version-minor N] [--version-fix N] [--no-diagnostics] [--no-canvas]\n"
        << "  plan-canvas-clear [--no-canvas] [--r N] [--g N] [--b N] [--a N]\n"
        << "  plan-canvas-document-snapshot [--no-canvas] [--width N] [--height N] [--layers N] [--frames N] [--frame-duration-ms N] [--current-layer N] [--current-frame N] [--hidden-layer N] [--alpha-locked-layer N] [--opacity N] [--blend-mode N] [--pending-face-payloads-per-layer N] [--captured-face-payloads-per-layer N]\n"
        << "  plan-image-import --width N --height N\n"
        << "  plan-document-resize [--current-resolution N] [--selected-resolution-index N]\n"
        << "  plan-layer-rename --old-name NAME --new-name NAME\n"
        << "  plan-layer-menu --command clear|rename|merge [--no-current-layer] [--current-index N] [--animation-duration N] [--current-name NAME] [--lower-name NAME]\n"
        << "  plan-layer-panel-view [--layer-count N] [--current-index N] [--hidden-index N] [--locked-index N] [--current-opacity N] [--current-blend-mode N]\n"
        << "  plan-layer-merge [--layer-count N] [--from-index N] [--to-index N] [--animation-duration N] [--no-history]\n"
        << "  plan-layer-operation --kind add|duplicate|select|reorder|remove|opacity|visibility|alpha-lock|blend-mode|highlight [--layer-count N] [--index N] [--from-index N] [--to-index N] [--source-index N] [--name NAME] [--opacity N] [--blend-mode N] [--enabled]\n"
        << "  plan-animation-operation --kind add|duplicate|remove|duration|move|select|goto|next|prev|playback|toggle-playback|onion [--frame-count N] [--total-duration N] [--current-frame N] [--selected-frame N] [--layer-index N] [--layer-id N] [--current-duration N] [--delta N] [--offset N] [--onion-size N] [--playing]\n"
        << "  plan-animation-panel-action --action goto|next|prev|playback|toggle-playback [--total-duration N] [--current-frame N] [--target-frame N] [--playing]\n"
        << "  plan-animation-panel-view [--layer-count N] [--frame-count N] [--frame-duration N] [--total-duration N] [--current-layer N] [--current-frame N] [--selected-layer-id N] [--selected-frame N] [--onion-size N] [--hidden-layer N]\n"
        << "  plan-animation-timeline-scrub [--total-duration N] [--cursor-x N] [--frame-width N]\n"
        << "  plan-brush-operation --kind color|tip|pattern|dual|preset|settings [--path FILE] [--thumb FILE] [--r N] [--g N] [--b N] [--a N] [--no-brush]\n"
        << "  plan-brush-refresh [--color|--no-color] [--brush|--no-brush-update] [--no-brush] [--floating-picker] [--floating-color] [--tip-flow N] [--tip-size N] [--r N] [--g N] [--b N] [--a N] [--bad-float]\n"
        << "  plan-brush-texture-list --kind add|remove|move [--dir NAME] [--data-path DIR] [--source FILE] [--item-count N] [--current-index N] [--offset N] [--user-texture]\n"
        << "  plan-brush-preset-list --kind add|remove|move|up|down|select|clear [--item-count N] [--current-index N] [--offset N] [--no-current-brush]\n"
        << "  plan-brush-stroke-control --kind float|bool|blend|tip-aspect-reset|default-reset [--setting NAME] [--value N] [--enabled|--disabled] [--blend-mode N]\n"
        << "  plan-brush-stroke-panel-view [--tip-size N] [--jitter-scatter N] [--dual-enabled|--dual-disabled] [--tip-blend-mode N] [--pattern-blend-mode N] [--tip-thumb FILE] [--dual-thumb FILE] [--pattern-thumb FILE] [--bad-float] [--bad-blend]\n"
        << "  plan-paint-feedback [--width N] [--height N] [--simple|--complex] [--framebuffer-fetch] [--texture-copy] [--blit] [--explicit-transitions] [--render-only] [--depth]\n"
        << "  plan-stroke-composite [--width N] [--height N] [--layer-blend N] [--stroke-blend N] [--dual-blend] [--pattern-blend] [--framebuffer-fetch] [--texture-copy] [--blit] [--explicit-transitions] [--render-only] [--depth]\n"
        << "  plan-canvas-hotkey --event key-down|key-up|touch-tap --key e|z|s|tab|alt|android-back|bracket-left|bracket-right [--ctrl] [--shift] [--mouse-focus] [--undo-count N] [--redo-count N] [--touch-fingers N]\n"
        << "  plan-canvas-tool --kind draw|erase|line|camera|grid|copy|cut|fill|mask-free|mask-line|bucket|pick|touch-lock [--current-mode-draw]\n"
        << "  plan-canvas-tool-toolbar\n"
        << "  plan-canvas-tool-state [--mode draw|erase|line|camera|grid|copy|cut|fill|mask-free|mask-line|bucket] [--picking] [--touch-lock]\n"
        << "  plan-canvas-camera-reset\n"
        << "  plan-canvas-view-density [--density N] [--bad-float]\n"
        << "  plan-canvas-view-cursor-mode [--mode N]\n"
        << "  plan-canvas-cursor [--mode draw|erase|line|camera|grid|copy|cut|fill|mask-free|mask-line|bucket] [--visibility never|small-brush|not-painting|always] [--brush-size N] [--no-brush] [--drawing] [--alt] [--resizing] [--picking] [--bad-size]\n"
        << "  plan-canvas-project-save-target [--data-dir DIR] [--path FILE] [--target-exists] [--remove-fails] [--rename-fails] [--encoder] [--progress]\n"
        << "  plan-grid-operation --kind pick|load|reload|clear|render|commit [--path FILE] [--no-heightmap] [--no-canvas] [--float32] [--float16] [--texture-resolution N] [--samples N]\n"
        << "  plan-history-operation --kind undo|redo|clear [--undo-count N] [--redo-count N] [--memory-bytes N]\n"
        << "  plan-main-toolbar --command open|save|undo|redo|clear-history|clear-canvas|message-box|settings [--undo-count N] [--redo-count N] [--memory-bytes N] [--no-canvas]\n"
        << "  plan-quick-operation --kind brush|color|restore|reset [--current-index N] [--slot-index N] [--brush-index N] [--color-index N] [--slot-count N] [--fire-event]\n"
        << "  plan-quick-slider-preview [--rtl] [--slider-x N] [--slider-y N] [--slider-height N] [--zoom N] [--pen-mode|--no-pen-mode] [--line-mode|--no-line-mode] [--bad-float]\n"
        << "  plan-share-file [--path FILE]\n"
        << "  plan-picked-path [--path FILE]\n"
        << "  plan-display-file [--path FILE]\n"
        << "  plan-keyboard-visibility [--visible]\n"
        << "  plan-cursor-visibility [--visible]\n"
        << "  plan-clipboard-read\n"
        << "  plan-clipboard-write [--text TEXT]\n"
        << "  load-project --path FILE\n"
        << "  parse-layout --path FILE\n"
        << "  record-render [--width N] [--height N] [--exercise-clear]\n"
        << "  save-document-project --path FILE [--width N] [--height N]\n"
        << "  save-project --path FILE --width N --height N [--layer-name NAME] [--layer-opacity N] [--blend-mode N] [--alpha-locked] [--hidden] [--layers N] [--frames N] [--frame-duration-ms N] [--include-test-face-payload] [--payload-layer N] [--payload-frame N]\n"
        << "  simulate-document-edits [--width N] [--height N]\n"
        << "  simulate-document-export [--width N] [--height N]\n"
        << "  simulate-document-render [--width N] [--height N] [--frame N]\n"
        << "  simulate-document-history [--width N] [--height N] [--history N]\n"
        << "  simulate-app-session [--no-canvas] [--new-document] [--unsaved] [--close-prompt-open] [--save-intent save|save-as|save-version|save-dirty-version]\n"
        << "  simulate-blend\n"
        << "  simulate-image-import [--width N] [--height N]\n"
        << "  simulate-stroke --x1 N --y1 N --x2 N --y2 N [--spacing N]\n"
        << "  simulate-stroke-script --path FILE\n"
        << "  --help\n";
}

pp::foundation::Status parse_document_args(int argc, char** argv, DocumentArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--width" || key == "--height" || key == "--layers" || key == "--frames"
            || key == "--frame-duration-ms") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }

            if (key == "--width") {
                args.width = value.value();
            } else if (key == "--height") {
                args.height = value.value();
            } else if (key == "--layers") {
                args.layers = value.value();
            } else if (key == "--frames") {
                args.frames = value.value();
            } else {
                args.frame_duration_ms = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.width == 0 || args.height == 0) {
        return pp::foundation::Status::invalid_argument("width and height must be greater than zero");
    }

    if (args.layers == 0) {
        return pp::foundation::Status::invalid_argument("layer count must be greater than zero");
    }

    if (args.frames == 0) {
        return pp::foundation::Status::invalid_argument("frame count must be greater than zero");
    }

    if (args.frame_duration_ms == 0) {
        return pp::foundation::Status::invalid_argument("frame duration must be greater than zero");
    }

    return pp::foundation::Status::success();
}

int create_document(int argc, char** argv)
{
    DocumentArgs args;
    const auto status = parse_document_args(argc, argv, args);
    if (!status.ok()) {
        print_error("create-document", status.message);
        return 2;
    }

    const auto document_result = pp::document::CanvasDocument::create(
        pp::document::DocumentConfig {
            .width = args.width,
            .height = args.height,
            .layer_count = args.layers,
        });
    if (!document_result) {
        print_error("create-document", document_result.status().message);
        return 2;
    }

    auto document = document_result.value();
    const auto duration_status = document.set_frame_duration(0, args.frame_duration_ms);
    if (!duration_status.ok()) {
        print_error("create-document", duration_status.message);
        return 2;
    }

    for (std::uint32_t i = 1; i < args.frames; ++i) {
        const auto added_frame = document.add_frame(args.frame_duration_ms);
        if (!added_frame) {
            print_error("create-document", added_frame.status().message);
            return 2;
        }
    }

    std::cout << "{\"ok\":true,\"command\":\"create-document\",\"document\":{"
              << "\"width\":" << document.width()
              << ",\"height\":" << document.height()
              << ",\"layers\":" << document.layers().size()
              << ",\"activeLayer\":" << document.active_layer_index()
              << ",\"frames\":" << document.frames().size()
              << ",\"activeFrame\":" << document.active_frame_index()
              << ",\"animationDurationMs\":" << document.animation_duration_ms()
              << "}}\n";
    return 0;
}

pp::foundation::Result<pp::document::CanvasDocument> create_export_sample_document(
    std::uint32_t width,
    std::uint32_t height)
{
    const std::vector<std::uint8_t> red_pixel { 255, 0, 0, 255 };
    const std::vector<std::uint8_t> blue_pixel { 0, 0, 255, 128 };
    const pp::document::AnimationFrame root_frames[] {
        { .duration_ms = 100, .face_pixels = {} },
        { .duration_ms = 250, .face_pixels = {} },
    };
    const pp::document::AnimationFrame base_frames[] {
        {
            .duration_ms = 100,
            .face_pixels = {
                pp::document::LayerFacePixels {
                    .face_index = 0,
                    .x = 2,
                    .y = 3,
                    .width = 1,
                    .height = 1,
                    .rgba8 = red_pixel,
                },
            },
        },
        { .duration_ms = 250, .face_pixels = {} },
    };
    const pp::document::AnimationFrame paint_frames[] {
        {
            .duration_ms = 333,
            .face_pixels = {
                pp::document::LayerFacePixels {
                    .face_index = 5,
                    .x = 4,
                    .y = 5,
                    .width = 1,
                    .height = 1,
                    .rgba8 = blue_pixel,
                },
            },
        },
    };
    const pp::document::DocumentLayerConfig layers[] {
        {
            .name = "Base",
            .visible = true,
            .alpha_locked = false,
            .opacity = 1.0F,
            .blend_mode = pp::paint::BlendMode::normal,
            .frames = std::span<const pp::document::AnimationFrame>(base_frames, 2),
        },
        {
            .name = "Paint",
            .visible = false,
            .alpha_locked = true,
            .opacity = 0.5F,
            .blend_mode = pp::paint::BlendMode::overlay,
            .frames = std::span<const pp::document::AnimationFrame>(paint_frames, 1),
        },
    };

    return pp::document::CanvasDocument::create_from_snapshot(
        pp::document::DocumentSnapshotConfig {
            .width = width,
            .height = height,
            .layers = std::span<const pp::document::DocumentLayerConfig>(layers, 2),
            .frames = std::span<const pp::document::AnimationFrame>(root_frames, 2),
            .selection_masks = {},
        });
}

pp::foundation::Status parse_save_document_project_args(
    int argc,
    char** argv,
    SaveDocumentProjectArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.path = argv[++i];
        } else if (key == "--width" || key == "--height") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }

            if (key == "--width") {
                args.width = value.value();
            } else {
                args.height = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.path.empty()) {
        return pp::foundation::Status::invalid_argument("path must not be empty");
    }

    if (args.width < 8 || args.height < 8) {
        return pp::foundation::Status::out_of_range("width and height must be at least 8 for document export");
    }

    return pp::foundation::Status::success();
}

int save_document_project(int argc, char** argv)
{
    SaveDocumentProjectArgs args;
    const auto status = parse_save_document_project_args(argc, argv, args);
    if (!status.ok()) {
        print_error("save-document-project", status.message);
        return 2;
    }

    const auto document = create_export_sample_document(args.width, args.height);
    if (!document) {
        print_error("save-document-project", document.status().message);
        return 2;
    }

    const auto exported = pp::document::export_ppi_project_document(document.value());
    if (!exported) {
        print_error("save-document-project", exported.status().message);
        return 2;
    }

    std::ofstream stream(args.path, std::ios::binary);
    if (!stream) {
        print_error("save-document-project", "project file could not be opened for writing");
        return 2;
    }

    const auto& bytes = exported.value();
    stream.write(reinterpret_cast<const char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()));
    if (!stream) {
        print_error("save-document-project", "project file could not be written");
        return 2;
    }

    const auto decoded = pp::assets::decode_ppi_project_images(bytes);
    if (!decoded) {
        print_error("save-document-project", decoded.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"save-document-project\""
              << ",\"path\":\"" << json_escape(args.path) << "\""
              << ",\"format\":\"ppi\""
              << ",\"bytes\":" << bytes.size()
              << ",\"document\":{\"width\":" << document.value().width()
              << ",\"height\":" << document.value().height()
              << ",\"layers\":" << document.value().layers().size()
              << ",\"frames\":" << document.value().frames().size()
              << ",\"facePayloads\":" << document.value().face_pixel_payload_count()
              << "},\"export\":{\"dirtyFaces\":" << decoded.value().project.body.summary.dirty_face_count
              << ",\"rgbaFacePayloads\":" << decoded.value().project.body.summary.rgba_face_payload_count
              << ",\"compressedBytes\":" << decoded.value().project.body.summary.compressed_face_bytes
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_save_project_args(int argc, char** argv, SaveProjectArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--path" || key == "--layer-name") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            if (key == "--path") {
                args.path = argv[++i];
            } else {
                args.layer_name = argv[++i];
            }
        } else if (key == "--layer-opacity") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.layer_opacity = value.value();
        } else if (key == "--alpha-locked") {
            args.alpha_locked = true;
        } else if (key == "--hidden") {
            args.visible = false;
        } else if (key == "--width" || key == "--height" || key == "--layers" || key == "--frames"
            || key == "--blend-mode" || key == "--frame-duration-ms" || key == "--payload-layer"
            || key == "--payload-frame") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }

            if (key == "--width") {
                args.width = value.value();
            } else if (key == "--height") {
                args.height = value.value();
            } else if (key == "--layers") {
                args.layers = value.value();
            } else if (key == "--frames") {
                args.frames = value.value();
            } else if (key == "--blend-mode") {
                args.blend_mode = value.value();
            } else if (key == "--payload-layer") {
                args.payload_layer = value.value();
            } else if (key == "--payload-frame") {
                args.payload_frame = value.value();
            } else {
                args.frame_duration_ms = value.value();
            }
        } else if (key == "--include-test-face-payload") {
            args.include_test_face_payload = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.path.empty()) {
        return pp::foundation::Status::invalid_argument("path must not be empty");
    }

    if (args.width == 0 || args.height == 0) {
        return pp::foundation::Status::invalid_argument("width and height must be greater than zero");
    }

    if (args.layer_name.empty()) {
        return pp::foundation::Status::invalid_argument("layer name must not be empty");
    }

    if (args.layer_opacity < 0.0F || args.layer_opacity > 1.0F) {
        return pp::foundation::Status::out_of_range("layer opacity must be in the range [0, 1]");
    }

    if (args.blend_mode > 4U) {
        return pp::foundation::Status::out_of_range("blend mode must be in the range [0, 4]");
    }

    if (args.layers == 0) {
        return pp::foundation::Status::invalid_argument("layer count must be greater than zero");
    }

    if (args.frames == 0) {
        return pp::foundation::Status::invalid_argument("frame count must be greater than zero");
    }

    if (args.frame_duration_ms == 0) {
        return pp::foundation::Status::invalid_argument("frame duration must be greater than zero");
    }

    if (args.include_test_face_payload && args.payload_layer >= args.layers) {
        return pp::foundation::Status::out_of_range("payload layer must be inside the generated layer list");
    }

    if (args.include_test_face_payload && args.payload_frame >= args.frames) {
        return pp::foundation::Status::out_of_range("payload frame must be inside the generated frame list");
    }

    if (!args.include_test_face_payload && (args.payload_layer != 0 || args.payload_frame != 0)) {
        return pp::foundation::Status::invalid_argument(
            "payload layer/frame options require --include-test-face-payload");
    }

    return pp::foundation::Status::success();
}

int save_project(int argc, char** argv)
{
    SaveProjectArgs args;
    const auto status = parse_save_project_args(argc, argv, args);
    if (!status.ok()) {
        print_error("save-project", status.message);
        return 2;
    }

    const auto test_payload = transparent_png_1x1_bytes();
    const pp::assets::PpiDirtyFacePayloadConfig dirty_faces[] {
        {
            .layer_index = args.payload_layer,
            .frame_index = args.payload_frame,
            .face_index = 0,
            .x = 0,
            .y = 0,
            .width = 1,
            .height = 1,
            .png_rgba8 = test_payload,
        },
    };
    const auto project = pp::assets::create_minimal_ppi_project(pp::assets::PpiMinimalProjectConfig {
        .width = args.width,
        .height = args.height,
        .layer_name = args.layer_name,
        .layer_metadata = pp::assets::PpiLayerMetadataConfig {
            .opacity = args.layer_opacity,
            .blend_mode = args.blend_mode,
            .alpha_locked = args.alpha_locked,
            .visible = args.visible,
        },
        .layer_count = args.layers,
        .frame_count = args.frames,
        .frame_duration_ms = args.frame_duration_ms,
        .dirty_faces = args.include_test_face_payload
            ? std::span<const pp::assets::PpiDirtyFacePayloadConfig>(dirty_faces, 1)
            : std::span<const pp::assets::PpiDirtyFacePayloadConfig>(),
    });
    if (!project) {
        print_error("save-project", project.status().message);
        return 2;
    }

    std::ofstream stream(args.path, std::ios::binary);
    if (!stream) {
        print_error("save-project", "project file could not be opened for writing");
        return 2;
    }

    const auto& bytes = project.value();
    stream.write(reinterpret_cast<const char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()));
    if (!stream) {
        print_error("save-project", "project file could not be written");
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"save-project\""
              << ",\"path\":\"" << json_escape(args.path) << "\""
              << ",\"format\":\"ppi\""
              << ",\"bytes\":" << bytes.size()
              << ",\"document\":{\"width\":" << args.width
              << ",\"height\":" << args.height
              << ",\"layers\":" << args.layers
              << ",\"frames\":" << args.frames
              << ",\"layerName\":\"" << json_escape(args.layer_name) << "\""
              << ",\"layerOpacity\":" << args.layer_opacity
              << ",\"blendMode\":" << args.blend_mode
              << ",\"alphaLocked\":" << (args.alpha_locked ? "true" : "false")
              << ",\"visible\":" << (args.visible ? "true" : "false")
              << ",\"frameDurationMs\":" << args.frame_duration_ms
              << ",\"facePayloads\":" << (args.include_test_face_payload ? 1 : 0)
              << ",\"payloadLayer\":" << args.payload_layer
              << ",\"payloadFrame\":" << args.payload_frame
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_inspect_image_args(int argc, char** argv, InspectImageArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            args.path = argv[++i];
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.path.empty()) {
        return pp::foundation::Status::invalid_argument("path must not be empty");
    }

    return pp::foundation::Status::success();
}

int inspect_image(int argc, char** argv)
{
    InspectImageArgs args;
    const auto status = parse_inspect_image_args(argc, argv, args);
    if (!status.ok()) {
        print_error("inspect-image", status.message);
        return 2;
    }

    std::ifstream stream(args.path, std::ios::binary);
    if (!stream) {
        print_error("inspect-image", "image file could not be opened");
        return 2;
    }

    const std::vector<char> chars {
        std::istreambuf_iterator<char>(stream),
        std::istreambuf_iterator<char>()
    };
    const auto* data = reinterpret_cast<const std::byte*>(chars.data());
    const auto format = pp::assets::detect_image_format(std::span<const std::byte>(data, chars.size()));
    if (!format) {
        print_error("inspect-image", format.status().message);
        return 2;
    }

    pp::foundation::Result<pp::assets::ImageMetadata> metadata =
        pp::foundation::Result<pp::assets::ImageMetadata>::failure(
            pp::foundation::Status::invalid_argument("image metadata is unavailable"));
    if (format.value() == pp::assets::ImageFormat::png) {
        metadata = pp::assets::parse_png_metadata(std::span<const std::byte>(data, chars.size()));
        if (!metadata) {
            print_error("inspect-image", metadata.status().message);
            return 2;
        }
    }

    std::cout << "{\"ok\":true,\"command\":\"inspect-image\",\"format\":\""
              << pp::assets::image_format_name(format.value())
              << "\",\"bytes\":" << chars.size();

    if (metadata) {
        std::cout << ",\"metadata\":{\"width\":" << metadata.value().width
                  << ",\"height\":" << metadata.value().height
                  << ",\"bitDepth\":" << static_cast<int>(metadata.value().bit_depth)
                  << ",\"components\":" << static_cast<int>(metadata.value().components)
                  << ",\"colorType\":\"" << pp::assets::image_color_type_name(metadata.value().color_type)
                  << "\"}";
    } else {
        std::cout << ",\"metadata\":null";
    }

    std::cout << "}\n";
    return 0;
}

pp::foundation::Status parse_import_image_args(int argc, char** argv, ImportImageArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            args.path = argv[++i];
        } else if (key == "--document-width" || key == "--document-height"
            || key == "--face" || key == "--x" || key == "--y") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }

            if (key == "--document-width") {
                args.document_width = value.value();
            } else if (key == "--document-height") {
                args.document_height = value.value();
            } else if (key == "--face") {
                args.face = value.value();
            } else if (key == "--x") {
                args.x = value.value();
            } else {
                args.y = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.path.empty()) {
        return pp::foundation::Status::invalid_argument("path must not be empty");
    }

    if ((args.document_width == 0) != (args.document_height == 0)) {
        return pp::foundation::Status::invalid_argument(
            "document width and height must both be omitted or both be greater than zero");
    }

    return pp::foundation::Status::success();
}

int import_image(int argc, char** argv)
{
    ImportImageArgs args;
    const auto status = parse_import_image_args(argc, argv, args);
    if (!status.ok()) {
        print_error("import-image", status.message);
        return 2;
    }

    std::ifstream stream(args.path, std::ios::binary);
    if (!stream) {
        print_error("import-image", "image file could not be opened");
        return 2;
    }

    const std::vector<char> chars {
        std::istreambuf_iterator<char>(stream),
        std::istreambuf_iterator<char>()
    };
    const auto* data = reinterpret_cast<const std::byte*>(chars.data());
    const auto image_result = pp::assets::decode_png_rgba8(std::span<const std::byte>(data, chars.size()));
    if (!image_result) {
        print_error("import-image", image_result.status().message);
        return 2;
    }

    const auto& image = image_result.value();
    const std::uint32_t document_width = args.document_width == 0 ? image.width : args.document_width;
    const std::uint32_t document_height = args.document_height == 0 ? image.height : args.document_height;
    const auto document_result = pp::document::CanvasDocument::create(
        pp::document::DocumentConfig {
            .width = document_width,
            .height = document_height,
            .layer_count = 1,
        });
    if (!document_result) {
        print_error("import-image", document_result.status().message);
        return 2;
    }

    auto document = document_result.value();
    const auto import_status = document.set_layer_frame_face_pixels(
        0,
        0,
        pp::document::LayerFacePixels {
            .face_index = args.face,
            .x = args.x,
            .y = args.y,
            .width = image.width,
            .height = image.height,
            .rgba8 = image.pixels,
        });
    if (!import_status.ok()) {
        print_error("import-image", import_status.message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"import-image\""
              << ",\"source\":\"" << json_escape(args.path) << "\""
              << ",\"image\":{\"format\":\"png\",\"width\":" << image.width
              << ",\"height\":" << image.height
              << ",\"bytes\":" << image.pixels.size()
              << "},\"document\":{\"width\":" << document.width()
              << ",\"height\":" << document.height()
              << ",\"layers\":" << document.layers().size()
              << ",\"frames\":" << document.frames().size()
              << ",\"facePayloads\":" << document.face_pixel_payload_count()
              << "},\"payload\":{\"face\":" << args.face
              << ",\"x\":" << args.x
              << ",\"y\":" << args.y
              << ",\"width\":" << image.width
              << ",\"height\":" << image.height
              << ",\"bytes\":" << image.pixels.size()
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_export_image_args(int argc, char** argv, ExportImageArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            args.path = argv[++i];
        } else if (key == "--width" || key == "--height") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }

            if (key == "--width") {
                args.width = value.value();
            } else {
                args.height = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.path.empty()) {
        return pp::foundation::Status::invalid_argument("path must not be empty");
    }

    if (args.width == 0 || args.height == 0) {
        return pp::foundation::Status::invalid_argument("width and height must be greater than zero");
    }

    constexpr std::uint64_t max_cli_export_bytes = 64ULL * 1024ULL * 1024ULL;
    if (static_cast<std::uint64_t>(args.width) > max_cli_export_bytes / 4ULL / static_cast<std::uint64_t>(args.height)) {
        return pp::foundation::Status::out_of_range("export image exceeds the CLI automation size limit");
    }

    return pp::foundation::Status::success();
}

int export_image(int argc, char** argv)
{
    ExportImageArgs args;
    const auto status = parse_export_image_args(argc, argv, args);
    if (!status.ok()) {
        print_error("export-image", status.message);
        return 2;
    }

    std::vector<std::uint8_t> pixels(
        static_cast<std::size_t>(args.width) * static_cast<std::size_t>(args.height) * 4U);
    for (std::uint32_t y = 0; y < args.height; ++y) {
        for (std::uint32_t x = 0; x < args.width; ++x) {
            const auto offset = (static_cast<std::size_t>(y) * args.width + x) * 4U;
            pixels[offset + 0U] = static_cast<std::uint8_t>((x * 37U) & 0xffU);
            pixels[offset + 1U] = static_cast<std::uint8_t>((y * 53U) & 0xffU);
            pixels[offset + 2U] = static_cast<std::uint8_t>(((x + y) * 29U) & 0xffU);
            pixels[offset + 3U] = 255U;
        }
    }

    const auto encoded = pp::assets::encode_png_rgba8(args.width, args.height, pixels);
    if (!encoded) {
        print_error("export-image", encoded.status().message);
        return 2;
    }

    std::ofstream stream(args.path, std::ios::binary);
    if (!stream) {
        print_error("export-image", "image file could not be opened for writing");
        return 2;
    }

    const auto& bytes = encoded.value();
    stream.write(reinterpret_cast<const char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()));
    if (!stream) {
        print_error("export-image", "image file could not be written");
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"export-image\""
              << ",\"path\":\"" << json_escape(args.path) << "\""
              << ",\"image\":{\"format\":\"png\",\"width\":" << args.width
              << ",\"height\":" << args.height
              << ",\"bytes\":" << pixels.size()
              << "},\"file\":{\"bytes\":" << bytes.size()
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_inspect_project_args(int argc, char** argv, InspectProjectArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            args.path = argv[++i];
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.path.empty()) {
        return pp::foundation::Status::invalid_argument("path must not be empty");
    }

    return pp::foundation::Status::success();
}

pp::foundation::Status parse_classify_open_args(int argc, char** argv, ClassifyOpenArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            args.path = argv[++i];
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.path.empty()) {
        return pp::foundation::Status::invalid_argument("path must not be empty");
    }

    return pp::foundation::Status::success();
}

int classify_open(int argc, char** argv)
{
    ClassifyOpenArgs args;
    const auto status = parse_classify_open_args(argc, argv, args);
    if (!status.ok()) {
        print_error("classify-open", status.message);
        return 2;
    }

    const auto route = pp::app::classify_document_open_path(args.path);
    if (!route) {
        print_error("classify-open", route.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"classify-open\""
              << ",\"route\":{\"kind\":\"" << document_open_kind_name(route.value().kind)
              << "\",\"path\":\"" << json_escape(route.value().path)
              << "\",\"directory\":\"" << json_escape(route.value().directory)
              << "\",\"name\":\"" << json_escape(route.value().name)
              << "\",\"extension\":\"" << json_escape(route.value().extension)
              << "\"}}\n";
    return 0;
}

pp::foundation::Status parse_plan_open_route_args(
    int argc,
    char** argv,
    PlanOpenRouteArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.path = argv[++i];
        } else if (key == "--unsaved") {
            args.unsaved = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.path.empty()) {
        return pp::foundation::Status::invalid_argument("path must not be empty");
    }

    return pp::foundation::Status::success();
}

int plan_open_route(int argc, char** argv)
{
    PlanOpenRouteArgs args;
    const auto status = parse_plan_open_route_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-open-route", status.message);
        return 2;
    }

    const auto route = pp::app::classify_document_open_path(args.path);
    if (!route) {
        print_error("plan-open-route", route.status().message);
        return 2;
    }

    const auto action = pp::app::plan_document_open(route.value().kind, args.unsaved);
    std::cout << "{\"ok\":true,\"command\":\"plan-open-route\""
              << ",\"route\":{\"kind\":\"" << document_open_kind_name(route.value().kind)
              << "\",\"path\":\"" << json_escape(route.value().path)
              << "\",\"directory\":\"" << json_escape(route.value().directory)
              << "\",\"name\":\"" << json_escape(route.value().name)
              << "\",\"extension\":\"" << json_escape(route.value().extension)
              << "\"},\"state\":{\"unsaved\":" << json_bool(args.unsaved)
              << "},\"plan\":{\"action\":\"" << document_open_plan_action_name(action)
              << "\"}}\n";
    return 0;
}

pp::foundation::Status parse_plan_file_menu_args(
    int argc,
    char** argv,
    PlanFileMenuArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--command") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.command = argv[++i];
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_file_menu(int argc, char** argv)
{
    PlanFileMenuArgs args;
    const auto status = parse_plan_file_menu_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-file-menu", status.message);
        return 2;
    }

    const auto command = pp::app::parse_file_menu_command(args.command);
    if (!command) {
        print_error("plan-file-menu", command.status().message);
        return 2;
    }

    const auto plan = pp::app::plan_file_menu_command(command.value());
    std::cout << "{\"ok\":true,\"command\":\"plan-file-menu\""
              << ",\"state\":{\"command\":\"" << json_escape(args.command)
              << "\"},\"plan\":{\"command\":\"" << file_menu_command_name(plan.command)
              << "\",\"action\":\"" << file_menu_action_name(plan.action)
              << "\",\"saveIntent\":\"" << document_save_intent_name(plan.save_intent)
              << "\",\"exportKind\":\"" << document_export_menu_kind_name(plan.export_kind)
              << "\"}}\n";
    return 0;
}

pp::foundation::Status parse_plan_document_file_args(
    int argc,
    char** argv,
    PlanDocumentFileArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--work-dir") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.work_directory = argv[++i];
        } else if (key == "--name") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.name = argv[++i];
        } else if (key == "--target-exists") {
            args.target_exists = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.work_directory.empty()) {
        return pp::foundation::Status::invalid_argument("work directory must not be empty");
    }

    return pp::foundation::Status::success();
}

int plan_document_file(int argc, char** argv)
{
    PlanDocumentFileArgs args;
    const auto status = parse_plan_document_file_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-document-file", status.message);
        return 2;
    }

    const auto plan = pp::app::plan_document_file_save(
        args.work_directory,
        args.name,
        [&args](const std::string&) {
            return args.target_exists;
        });
    if (!plan) {
        print_error("plan-document-file", plan.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-document-file\""
              << ",\"target\":{\"name\":\"" << json_escape(plan.value().target.name)
              << "\",\"directory\":\"" << json_escape(plan.value().target.directory)
              << "\",\"path\":\"" << json_escape(plan.value().target.path)
              << "\",\"exists\":" << json_bool(args.target_exists)
              << "},\"decision\":\""
              << document_file_write_decision_name(plan.value().write_decision)
              << "\"}\n";
    return 0;
}

pp::foundation::Status parse_plan_new_document_args(
    int argc,
    char** argv,
    PlanNewDocumentArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--work-dir") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.work_directory = argv[++i];
        } else if (key == "--name") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.name = argv[++i];
        } else if (key == "--resolution-index") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto parsed = pp::foundation::parse_u32(argv[++i]);
            if (!parsed) {
                return parsed.status();
            }
            args.resolution_index = parsed.value();
        } else if (key == "--target-exists") {
            args.target_exists = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.work_directory.empty()) {
        return pp::foundation::Status::invalid_argument("work directory must not be empty");
    }

    return pp::foundation::Status::success();
}

int plan_new_document(int argc, char** argv)
{
    PlanNewDocumentArgs args;
    const auto status = parse_plan_new_document_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-new-document", status.message);
        return 2;
    }

    const auto plan = pp::app::plan_new_document(
        args.work_directory,
        args.name,
        static_cast<int>(args.resolution_index),
        [&args](const std::string&) {
            return args.target_exists;
        });
    if (!plan) {
        print_error("plan-new-document", plan.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-new-document\""
              << ",\"target\":{\"name\":\"" << json_escape(plan.value().target.name)
              << "\",\"directory\":\"" << json_escape(plan.value().target.directory)
              << "\",\"path\":\"" << json_escape(plan.value().target.path)
              << "\",\"exists\":" << json_bool(args.target_exists)
              << "},\"document\":{\"resolution\":" << plan.value().resolution
              << ",\"resolutionIndex\":" << args.resolution_index
              << "},\"decision\":\""
              << document_file_write_decision_name(plan.value().write_decision)
              << "\"}\n";
    return 0;
}

pp::foundation::Status parse_plan_document_version_args(
    int argc,
    char** argv,
    PlanDocumentVersionArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--directory") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.directory = argv[++i];
        } else if (key == "--doc-name") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.document_name = argv[++i];
        } else if (key == "--existing-path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.existing_paths.push_back(argv[++i]);
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.directory.empty()) {
        return pp::foundation::Status::invalid_argument("directory must not be empty");
    }

    if (args.document_name.empty()) {
        return pp::foundation::Status::invalid_argument("document name must not be empty");
    }

    return pp::foundation::Status::success();
}

int plan_document_version(int argc, char** argv)
{
    PlanDocumentVersionArgs args;
    const auto status = parse_plan_document_version_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-document-version", status.message);
        return 2;
    }

    const auto target = pp::app::find_next_document_version_target(
        args.directory,
        args.document_name,
        [&args](const std::string& path) {
            return std::find(args.existing_paths.begin(), args.existing_paths.end(), path)
                != args.existing_paths.end();
        });
    if (!target) {
        print_error("plan-document-version", target.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-document-version\""
              << ",\"input\":{\"directory\":\"" << json_escape(args.directory)
              << "\",\"documentName\":\"" << json_escape(args.document_name)
              << "\",\"existingPaths\":" << args.existing_paths.size()
              << "},\"target\":{\"name\":\"" << json_escape(target.value().name)
              << "\",\"path\":\"" << json_escape(target.value().path)
              << "\"}}\n";
    return 0;
}

pp::foundation::Status parse_plan_document_session_prompt_args(
    int argc,
    char** argv,
    PlanDocumentSessionPromptArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto kind = parse_document_session_prompt_kind(argv[++i]);
            if (!kind) {
                return kind.status();
            }
            args.kind = kind.value();
        } else if (key == "--name") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.name = argv[++i];
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_document_session_prompt(int argc, char** argv)
{
    PlanDocumentSessionPromptArgs args;
    const auto status = parse_plan_document_session_prompt_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-document-session-prompt", status.message);
        return 2;
    }

    const auto plan = pp::app::plan_document_session_prompt(args.kind, args.name);
    std::cout << "{\"ok\":true,\"command\":\"plan-document-session-prompt\""
              << ",\"kind\":\"" << document_session_prompt_kind_name(args.kind)
              << "\",\"name\":\"" << json_escape(args.name)
              << "\",\"plan\":{\"title\":\"" << json_escape(plan.title)
              << "\",\"message\":\"" << json_escape(plan.message)
              << "\",\"okCaption\":\"" << json_escape(plan.ok_caption)
              << "\",\"cancelCaption\":\"" << json_escape(plan.cancel_caption)
              << "\",\"showCancel\":" << json_bool(plan.show_cancel)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_export_start_args(
    int argc,
    char** argv,
    PlanExportStartArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--requires-license") {
            args.requires_license = true;
        } else if (key == "--demo") {
            args.license_valid = false;
        } else if (key == "--no-canvas") {
            args.has_canvas = false;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_export_start(int argc, char** argv)
{
    PlanExportStartArgs args;
    const auto status = parse_plan_export_start_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-export-start", status.message);
        return 2;
    }

    const auto decision = pp::app::plan_document_export_start(
        args.requires_license,
        args.license_valid,
        args.has_canvas);
    std::cout << "{\"ok\":true,\"command\":\"plan-export-start\""
              << ",\"state\":{\"requiresLicense\":" << json_bool(args.requires_license)
              << ",\"licenseValid\":" << json_bool(args.license_valid)
              << ",\"hasCanvas\":" << json_bool(args.has_canvas)
              << "},\"decision\":\"" << document_export_start_decision_name(decision)
              << "\"}\n";
    return 0;
}

pp::foundation::Status parse_plan_export_menu_args(
    int argc,
    char** argv,
    PlanExportMenuArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.kind = argv[++i];
        } else if (key == "--demo") {
            args.license_valid = false;
        } else if (key == "--no-canvas") {
            args.has_canvas = false;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_export_menu(int argc, char** argv)
{
    PlanExportMenuArgs args;
    const auto status = parse_plan_export_menu_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-export-menu", status.message);
        return 2;
    }

    const auto kind = parse_document_export_menu_kind(args.kind);
    if (!kind) {
        print_error("plan-export-menu", kind.status().message);
        return 2;
    }

    const auto plan = pp::app::plan_document_export_menu_action(
        kind.value(),
        args.has_canvas,
        args.license_valid);
    std::cout << "{\"ok\":true,\"command\":\"plan-export-menu\""
              << ",\"state\":{\"kind\":\"" << json_escape(args.kind)
              << "\",\"licenseValid\":" << json_bool(args.license_valid)
              << ",\"hasCanvas\":" << json_bool(args.has_canvas)
              << "},\"plan\":{\"kind\":\"" << document_export_menu_kind_name(plan.kind)
              << "\",\"action\":\"" << document_export_menu_action_name(plan.action)
              << "\",\"opensDialog\":" << json_bool(plan.opens_dialog)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_export_snapshot_route_args(
    int argc,
    char** argv,
    PlanExportSnapshotRouteArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.kind = argv[++i];
        } else if (key == "--target-path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.target_path = argv[++i];
        } else if (key == "--captured-face-payloads") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.captured_face_payloads = value.value();
        } else if (key == "--pending-face-payloads") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.pending_face_payloads = value.value();
        } else if (key == "--unsupported-target") {
            args.target_supported = false;
        } else if (key == "--unsupported-platform") {
            args.platform_supported = false;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_export_snapshot_route(int argc, char** argv)
{
    PlanExportSnapshotRouteArgs args;
    const auto status = parse_plan_export_snapshot_route_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-export-snapshot-route", status.message);
        return 2;
    }

    const auto kind = parse_document_export_execution_kind(args.kind);
    if (!kind) {
        print_error("plan-export-snapshot-route", kind.status().message);
        return 2;
    }

    pp::app::DocumentCanvasSaveSnapshotReport report;
    report.captured_face_payloads = args.captured_face_payloads;
    report.pending_face_payloads = args.pending_face_payloads;
    report.payload_complete = args.captured_face_payloads >= args.pending_face_payloads;
    report.can_export_ppi = report.payload_complete;

    const bool target_supported = args.target_supported
        && pp::app::document_export_snapshot_target_supported(kind.value(), args.target_path);
    const auto plan = pp::app::plan_document_export_snapshot_route(
        kind.value(),
        report,
        target_supported,
        args.platform_supported);

    std::cout << "{\"ok\":true,\"command\":\"plan-export-snapshot-route\""
              << ",\"state\":{\"kind\":\"" << json_escape(args.kind)
              << "\",\"targetPath\":\"" << json_escape(args.target_path)
              << "\",\"capturedFacePayloads\":" << args.captured_face_payloads
              << ",\"pendingFacePayloads\":" << args.pending_face_payloads
              << ",\"payloadComplete\":" << json_bool(report.payload_complete)
              << ",\"targetSupported\":" << json_bool(target_supported)
              << ",\"platformSupported\":" << json_bool(args.platform_supported)
              << "},\"plan\":{\"kind\":\"" << document_export_execution_kind_name(plan.kind)
              << "\",\"action\":\"" << document_export_snapshot_route_action_name(plan.action)
              << "\",\"usesDocumentSnapshotWriter\":" << json_bool(plan.uses_document_snapshot_writer)
              << ",\"fallbackReason\":\"" << json_escape(std::string(plan.fallback_reason))
              << "\"}}\n";
    return 0;
}

pp::foundation::Status parse_plan_export_message_args(
    int argc,
    char** argv,
    PlanExportMessageArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.kind = argv[++i];
        } else if (key == "--destination") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.destination = argv[++i];
        } else if (key == "--detail") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.detail = argv[++i];
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_export_message(int argc, char** argv)
{
    PlanExportMessageArgs args;
    const auto status = parse_plan_export_message_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-export-message", status.message);
        return 2;
    }

    const auto kind = parse_document_export_success_kind(args.kind);
    if (!kind) {
        print_error("plan-export-message", kind.status().message);
        return 2;
    }

    const auto destination = parse_document_export_success_destination(args.destination);
    if (!destination) {
        print_error("plan-export-message", destination.status().message);
        return 2;
    }

    const auto plan = pp::app::plan_document_export_success_dialog(
        kind.value(),
        destination.value(),
        args.detail);
    std::cout << "{\"ok\":true,\"command\":\"plan-export-message\""
              << ",\"state\":{\"kind\":\"" << json_escape(args.kind)
              << "\",\"destination\":\"" << json_escape(args.destination)
              << "\",\"detail\":\"" << json_escape(args.detail)
              << "\"},\"plan\":{\"kind\":\"" << document_export_success_kind_name(plan.kind)
              << "\",\"destination\":\"" << document_export_success_destination_name(plan.destination)
              << "\",\"showDialog\":" << json_bool(plan.show_dialog)
              << ",\"title\":\"" << json_escape(plan.dialog.title)
              << "\",\"message\":\"" << json_escape(plan.dialog.message)
              << "\"}}\n";
    return 0;
}

pp::foundation::Status parse_plan_export_report_args(
    int argc,
    char** argv,
    PlanExportReportArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.kind = argv[++i];
        } else if (key == "--message") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.message = argv[++i];
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_export_report(int argc, char** argv)
{
    PlanExportReportArgs args;
    const auto status = parse_plan_export_report_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-export-report", status.message);
        return 2;
    }

    pp::app::AppMessageDialogPlan dialog;
    if (args.kind == "license-disabled") {
        dialog = pp::app::plan_document_export_license_disabled_dialog();
    } else {
        const auto kind = parse_document_export_success_kind(args.kind);
        if (!kind) {
            print_error("plan-export-report", kind.status().message);
            return 2;
        }
        dialog = pp::app::plan_document_export_failure_dialog(kind.value(), args.message);
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-export-report\""
              << ",\"state\":{\"kind\":\"" << json_escape(args.kind)
              << "\",\"message\":\"" << json_escape(args.message)
              << "\"},\"dialog\":{\"title\":\"" << json_escape(dialog.title)
              << "\",\"message\":\"" << json_escape(dialog.message)
              << "\",\"showCancel\":" << json_bool(dialog.show_cancel)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_cloud_upload_args(
    int argc,
    char** argv,
    PlanCloudUploadArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--no-canvas") {
            args.has_canvas = false;
        } else if (key == "--new-document") {
            args.new_document = true;
        } else if (key == "--unsaved") {
            args.unsaved = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_cloud_upload(int argc, char** argv)
{
    PlanCloudUploadArgs args;
    const auto status = parse_plan_cloud_upload_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-cloud-upload", status.message);
        return 2;
    }

    const auto plan = pp::app::plan_cloud_upload(
        args.has_canvas,
        args.new_document,
        args.unsaved);
    std::cout << "{\"ok\":true,\"command\":\"plan-cloud-upload\""
              << ",\"state\":{\"hasCanvas\":" << json_bool(args.has_canvas)
              << ",\"newDocument\":" << json_bool(args.new_document)
              << ",\"unsaved\":" << json_bool(args.unsaved)
              << "},\"decision\":\"" << cloud_upload_action_name(plan.action)
              << "\",\"saveBeforeUpload\":" << json_bool(plan.save_before_upload);
    if (plan.action == pp::app::CloudUploadAction::show_save_required_warning
        || plan.action == pp::app::CloudUploadAction::prompt_publish) {
        const auto prompt = plan.action == pp::app::CloudUploadAction::show_save_required_warning
            ? pp::app::plan_cloud_save_required_prompt()
            : pp::app::plan_cloud_publish_prompt();
        std::cout << ",\"prompt\":{\"title\":\"" << json_escape(prompt.title)
                  << "\",\"message\":\"" << json_escape(prompt.message)
                  << "\",\"okCaption\":\"" << json_escape(prompt.ok_caption)
                  << "\",\"cancelCaption\":\"" << json_escape(prompt.cancel_caption)
                  << "\",\"showCancel\":" << json_bool(prompt.show_cancel)
                  << "}";
    }
    std::cout << "}\n";
    return 0;
}

pp::foundation::Status parse_plan_cloud_browse_args(
    int argc,
    char** argv,
    PlanCloudBrowseArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--no-canvas") {
            args.has_canvas = false;
        } else if (key == "--selected-file") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.selected_file = argv[++i];
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_cloud_browse(int argc, char** argv)
{
    PlanCloudBrowseArgs args;
    const auto status = parse_plan_cloud_browse_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-cloud-browse", status.message);
        return 2;
    }

    const auto browse = pp::app::plan_cloud_browse(args.has_canvas);
    const auto selection = pp::app::plan_cloud_download_selection(args.selected_file);
    std::cout << "{\"ok\":true,\"command\":\"plan-cloud-browse\""
              << ",\"state\":{\"hasCanvas\":" << json_bool(args.has_canvas)
              << ",\"selectedFile\":\"" << json_escape(args.selected_file)
              << "\"},\"browseDecision\":\"" << cloud_browse_action_name(browse)
              << "\",\"selectionDecision\":\"" << cloud_download_selection_action_name(selection)
              << "\"}\n";
    return 0;
}

pp::foundation::Status parse_plan_cloud_upload_all_args(
    int argc,
    char** argv,
    PlanCloudUploadAllArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--file-count") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.file_count = value.value();
        } else if (key == "--no-progress-ui") {
            args.progress_ui_available = false;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_cloud_upload_all(int argc, char** argv)
{
    PlanCloudUploadAllArgs args;
    const auto status = parse_plan_cloud_upload_all_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-cloud-upload-all", status.message);
        return 2;
    }

    const auto plan = pp::app::plan_cloud_bulk_upload(args.file_count, args.progress_ui_available);
    std::cout << "{\"ok\":true,\"command\":\"plan-cloud-upload-all\""
              << ",\"state\":{\"fileCount\":" << args.file_count
              << ",\"progressUiAvailable\":" << json_bool(args.progress_ui_available)
              << "},\"plan\":{\"fileCount\":" << plan.file_count
              << ",\"progressTotal\":" << plan.progress_total
              << ",\"showProgress\":" << json_bool(plan.show_progress)
              << "}";
    if (plan.show_progress) {
        const auto progress = pp::app::plan_cloud_bulk_upload_progress_dialog(plan.progress_total);
        std::cout << ",\"progressDialog\":{\"title\":\"" << json_escape(progress.title)
                  << "\",\"total\":" << progress.total
                  << ",\"count\":" << progress.count
                  << ",\"progressFraction\":" << progress.progress_fraction
                  << "}";
    }
    std::cout << "}\n";
    return 0;
}

pp::foundation::Status parse_plan_cloud_transfer_args(
    int argc,
    char** argv,
    PlanCloudTransferArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--direction") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const std::string_view value(argv[++i]);
            if (value == "download") {
                args.direction = pp::app::CloudTransferDirection::download;
            } else if (value == "upload") {
                args.direction = pp::app::CloudTransferDirection::upload;
            } else {
                return pp::foundation::Status::invalid_argument("unknown transfer direction");
            }
        } else if (key == "--source") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.source = argv[++i];
        } else if (key == "--destination") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.destination = argv[++i];
        } else if (key == "--progress") {
            args.progress_callback = true;
        } else if (key == "--disable-tls-verification") {
            args.disable_tls_verification = true;
        } else if (key == "--progress-total") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i64_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.progress_total = value.value();
        } else if (key == "--progress-current") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i64_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.progress_current = value.value();
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_cloud_transfer(int argc, char** argv)
{
    PlanCloudTransferArgs args;
    const auto status = parse_plan_cloud_transfer_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-cloud-transfer", status.message);
        return 2;
    }

    const auto transfer = args.direction == pp::app::CloudTransferDirection::download
        ? pp::app::plan_cloud_download_transfer(
            args.source,
            args.destination,
            args.progress_callback,
            args.disable_tls_verification)
        : pp::app::plan_cloud_upload_transfer(
            args.source,
            args.progress_callback,
            args.disable_tls_verification);
    const auto progress = pp::app::plan_cloud_transfer_progress(
        args.progress_total,
        args.progress_current);
    std::cout << "{\"ok\":true,\"command\":\"plan-cloud-transfer\""
              << ",\"state\":{\"direction\":\"" << cloud_transfer_direction_name(args.direction)
              << "\",\"source\":\"" << json_escape(args.source)
              << "\",\"destination\":\"" << json_escape(args.destination)
              << "\",\"progressCallback\":" << json_bool(args.progress_callback)
              << ",\"disableTlsVerification\":" << json_bool(args.disable_tls_verification)
              << ",\"progressTotal\":" << args.progress_total
              << ",\"progressCurrent\":" << args.progress_current
              << "},\"plan\":{\"direction\":\"" << cloud_transfer_direction_name(transfer.direction)
              << "\",\"action\":\"" << cloud_transfer_action_name(transfer.action)
              << "\",\"enableProgress\":" << json_bool(transfer.enable_progress)
              << ",\"disableTlsVerification\":" << json_bool(transfer.disable_tls_verification)
              << "},\"progress\":{\"notify\":" << json_bool(progress.notify)
              << ",\"fraction\":" << progress.fraction
              << "}";
    if (transfer.direction == pp::app::CloudTransferDirection::download
        && transfer.action == pp::app::CloudTransferAction::start_transfer) {
        const auto prompt = pp::app::plan_cloud_download_progress_prompt();
        std::cout << ",\"progressPrompt\":{\"title\":\"" << json_escape(prompt.title)
                  << "\",\"message\":\"" << json_escape(prompt.message)
                  << "\",\"showCancel\":" << json_bool(prompt.show_cancel)
                  << ",\"formattedMessage\":\""
                  << json_escape(pp::app::format_cloud_download_progress_message(progress.fraction))
                  << "\"}";
    }
    std::cout << "}\n";
    return 0;
}

pp::foundation::Status parse_plan_app_dialog_args(
    int argc,
    char** argv,
    PlanAppDialogArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const std::string_view value(argv[++i]);
            if (value == "progress") {
                args.kind = pp::app::AppDialogKind::progress;
            } else if (value == "message") {
                args.kind = pp::app::AppDialogKind::message;
            } else if (value == "input") {
                args.kind = pp::app::AppDialogKind::input;
            } else {
                return pp::foundation::Status::invalid_argument("unknown app dialog kind");
            }
        } else if (key == "--title") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.title = argv[++i];
        } else if (key == "--message") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.message = argv[++i];
        } else if (key == "--field-name") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.field_name = argv[++i];
        } else if (key == "--ok-caption") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.ok_caption = argv[++i];
        } else if (key == "--total") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.total = value.value();
        } else if (key == "--cancel") {
            args.cancel = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_app_dialog(int argc, char** argv)
{
    PlanAppDialogArgs args;
    const auto status = parse_plan_app_dialog_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-app-dialog", status.message);
        return 2;
    }

    switch (args.kind) {
    case pp::app::AppDialogKind::progress:
    {
        const auto plan = pp::app::plan_app_progress_dialog(args.title, args.total);
        std::cout << "{\"ok\":true,\"command\":\"plan-app-dialog\""
                  << ",\"kind\":\"" << app_dialog_kind_name(args.kind)
                  << "\",\"plan\":{\"title\":\"" << json_escape(plan.title)
                  << "\",\"total\":" << plan.total
                  << ",\"count\":" << plan.count
                  << ",\"progressFraction\":" << plan.progress_fraction
                  << "}}\n";
        return 0;
    }
    case pp::app::AppDialogKind::message:
    {
        const auto plan = pp::app::plan_app_message_dialog(args.title, args.message, args.cancel);
        std::cout << "{\"ok\":true,\"command\":\"plan-app-dialog\""
                  << ",\"kind\":\"" << app_dialog_kind_name(args.kind)
                  << "\",\"plan\":{\"title\":\"" << json_escape(plan.title)
                  << "\",\"message\":\"" << json_escape(plan.message)
                  << "\",\"okCaption\":\"" << json_escape(plan.ok_caption)
                  << "\",\"cancelCaption\":\"" << json_escape(plan.cancel_caption)
                  << "\",\"showCancel\":" << json_bool(plan.show_cancel)
                  << "}}\n";
        return 0;
    }
    case pp::app::AppDialogKind::input:
    {
        const auto plan = pp::app::plan_app_input_dialog(args.title, args.field_name, args.ok_caption);
        if (!plan) {
            print_error("plan-app-dialog", plan.status().message);
            return 2;
        }
        std::cout << "{\"ok\":true,\"command\":\"plan-app-dialog\""
                  << ",\"kind\":\"" << app_dialog_kind_name(args.kind)
                  << "\",\"plan\":{\"title\":\"" << json_escape(plan.value().title)
                  << "\",\"fieldName\":\"" << json_escape(plan.value().field_name)
                  << "\",\"okCaption\":\"" << json_escape(plan.value().ok_caption)
                  << "}}\n";
        return 0;
    }
    }

    print_error("plan-app-dialog", "unknown app dialog kind");
    return 2;
}

pp::foundation::Status parse_plan_recording_session_args(
    int argc,
    char** argv,
    PlanRecordingSessionArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--running") {
            args.running = true;
        } else if (key == "--frame-count") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.frame_count = value.value();
        } else if (key == "--platform-deletes-recorded-files") {
            args.platform_deletes_recorded_files = true;
        } else if (key == "--no-encoder") {
            args.encoder_available = false;
        } else if (key == "--no-canvas") {
            args.has_canvas = false;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_recording_session(int argc, char** argv)
{
    PlanRecordingSessionArgs args;
    const auto status = parse_plan_recording_session_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-recording-session", status.message);
        return 2;
    }

    const auto start = pp::app::plan_recording_start(args.running);
    const auto stop = pp::app::plan_recording_stop(args.running);
    const auto clear = pp::app::plan_recording_clear(
        args.running,
        args.platform_deletes_recorded_files);
    const auto export_plan = pp::app::plan_recording_export(args.frame_count);
    const auto progress_dialog = pp::app::plan_recording_export_progress_dialog(export_plan);
    const auto worker = pp::app::plan_recording_worker_iteration(
        args.running,
        args.encoder_available,
        args.has_canvas);
    std::cout << "{\"ok\":true,\"command\":\"plan-recording-session\""
              << ",\"state\":{\"running\":" << json_bool(args.running)
              << ",\"frameCount\":" << args.frame_count
              << ",\"platformDeletesRecordedFiles\":" << json_bool(args.platform_deletes_recorded_files)
              << ",\"encoderAvailable\":" << json_bool(args.encoder_available)
              << ",\"hasCanvas\":" << json_bool(args.has_canvas)
              << "},\"startDecision\":\"" << recording_start_action_name(start)
              << "\",\"stopDecision\":\"" << recording_stop_action_name(stop)
              << "\",\"clear\":{\"stopRunningRecording\":" << json_bool(clear.stop_running_recording)
              << ",\"deleteRecordedFiles\":" << json_bool(clear.delete_recorded_files)
              << ",\"frameCountAfterClear\":" << clear.frame_count_after_clear
              << "},\"export\":{\"frameCount\":" << export_plan.frame_count
              << ",\"progressTotal\":" << export_plan.progress_total
              << ",\"progressDialog\":{\"title\":\"" << json_escape(progress_dialog.title)
              << "\",\"total\":" << progress_dialog.total
              << ",\"count\":" << progress_dialog.count
              << ",\"progressFraction\":" << progress_dialog.progress_fraction
              << "}"
              << "},\"worker\":{\"continueRunning\":" << json_bool(worker.continue_running)
              << ",\"encodeFrame\":" << json_bool(worker.encode_frame)
              << ",\"clearDirtyStroke\":" << json_bool(worker.clear_dirty_stroke)
              << ",\"updateFrameLabel\":" << json_bool(worker.update_frame_label)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_app_preferences_args(
    int argc,
    char** argv,
    PlanAppPreferencesArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--ui-scale" || key == "--display-density" || key == "--current-scale"
            || key == "--scale-option" || key == "--viewport-scale") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--ui-scale") {
                args.ui_scale = value.value();
            } else if (key == "--display-density") {
                args.display_density = value.value();
            } else if (key == "--current-scale") {
                args.current_scale = value.value();
            } else if (key == "--scale-option") {
                args.scale_options.push_back(value.value());
            } else {
                args.viewport_scale = value.value();
            }
        } else if (key == "--rtl") {
            args.right_to_left = true;
        } else if (key == "--timelapse-disabled") {
            args.timelapse_enabled = false;
        } else if (key == "--recording-running") {
            args.recording_running = true;
        } else if (key == "--vr-controllers-disabled") {
            args.vr_controllers_enabled = false;
        } else if (key == "--cursor-mode") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.cursor_mode = static_cast<int>(value.value());
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_app_preferences(int argc, char** argv)
{
    PlanAppPreferencesArgs args;
    const auto status = parse_plan_app_preferences_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-app-preferences", status.message);
        return 2;
    }

    const auto ui_scale = pp::app::plan_ui_scale(args.ui_scale, args.display_density);
    const auto scale_selection = pp::app::plan_scale_option_selection(
        args.current_scale,
        args.scale_options);
    const auto viewport_scale = pp::app::plan_viewport_scale(args.viewport_scale);
    const auto direction = pp::app::plan_interface_direction(args.right_to_left);
    const auto timelapse = pp::app::plan_timelapse_preference(
        args.timelapse_enabled,
        args.recording_running);
    const auto vr_controllers = pp::app::plan_vr_controllers_preference(args.vr_controllers_enabled);
    const auto cursor_mode = pp::app::plan_canvas_cursor_mode(args.cursor_mode);

    std::cout << "{\"ok\":true,\"command\":\"plan-app-preferences\""
              << ",\"state\":{\"uiScale\":" << args.ui_scale
              << ",\"displayDensity\":" << args.display_density
              << ",\"currentScale\":" << args.current_scale
              << ",\"scaleOptions\":" << args.scale_options.size()
              << ",\"viewportScale\":" << args.viewport_scale
              << ",\"rtl\":" << json_bool(args.right_to_left)
              << ",\"timelapseEnabled\":" << json_bool(args.timelapse_enabled)
              << ",\"recordingRunning\":" << json_bool(args.recording_running)
              << ",\"vrControllersEnabled\":" << json_bool(args.vr_controllers_enabled)
              << ",\"cursorMode\":" << args.cursor_mode
              << "},\"uiScale\":{\"scale\":" << ui_scale.scale
              << ",\"displayDensity\":" << ui_scale.display_density
              << ",\"fontScale\":" << ui_scale.font_scale
              << "},\"scaleSelection\":{\"hasSelection\":" << json_bool(scale_selection.has_selection)
              << ",\"index\":" << scale_selection.index
              << "},\"viewportScale\":{\"scale\":" << viewport_scale.scale
              << "},\"direction\":\"" << interface_direction_name(direction.direction)
              << "\",\"timelapse\":{\"enabled\":" << json_bool(timelapse.enabled)
              << ",\"recordingAction\":\"" << timelapse_recording_action_name(timelapse.recording_action)
              << "\"},\"vrControllers\":{\"enabled\":" << json_bool(vr_controllers.value)
              << "},\"cursor\":{\"mode\":" << cursor_mode.value
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_app_startup_args(
    int argc,
    char** argv,
    PlanAppStartupArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--run-counter") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.run_counter = value.value();
        } else if (key == "--auto-timelapse-disabled") {
            args.auto_timelapse_enabled = false;
        } else if (key == "--vr-controllers-disabled") {
            args.vr_controllers_enabled = false;
        } else if (key == "--license-invalid") {
            args.license_valid = false;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_app_startup(int argc, char** argv)
{
    PlanAppStartupArgs args;
    const auto status = parse_plan_app_startup_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-app-startup", status.message);
        return 2;
    }

    const auto plan = pp::app::plan_app_startup(
        args.run_counter,
        args.auto_timelapse_enabled,
        args.vr_controllers_enabled,
        args.license_valid);
    if (!plan) {
        print_error("plan-app-startup", plan.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-app-startup\""
              << ",\"state\":{\"runCounter\":" << args.run_counter
              << ",\"autoTimelapseEnabled\":" << json_bool(args.auto_timelapse_enabled)
              << ",\"vrControllersEnabled\":" << json_bool(args.vr_controllers_enabled)
              << ",\"licenseValid\":" << json_bool(args.license_valid)
              << "},\"plan\":{\"previousRunCounter\":" << plan.value().previous_run_counter
              << ",\"nextRunCounter\":" << plan.value().next_run_counter
              << ",\"savePreferences\":" << json_bool(plan.value().save_preferences)
              << ",\"startTimelapse\":" << json_bool(plan.value().start_timelapse)
              << ",\"vrControllersEnabled\":" << json_bool(plan.value().vr_controllers_enabled)
              << ",\"showLicenseWarning\":" << json_bool(plan.value().show_license_warning)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_app_startup_resources_args(
    int argc,
    char** argv,
    PlanAppStartupResourcesArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--width") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.width = value.value();
        } else if (key == "--height") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.height = value.value();
        } else if (key == "--bad-size") {
            args.bad_size = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_app_startup_resources(int argc, char** argv)
{
    PlanAppStartupResourcesArgs args;
    const auto status = parse_plan_app_startup_resources_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-app-startup-resources", status.message);
        return 2;
    }

    const auto plan = pp::app::plan_app_startup_resources(
        args.bad_size ? 0.0F : args.width,
        args.bad_size ? std::nanf("") : args.height);
    if (!plan) {
        print_error("plan-app-startup-resources", plan.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-app-startup-resources\""
              << ",\"plan\":{\"uiRenderTargetWidth\":" << plan.value().ui_render_target_width
              << ",\"uiRenderTargetHeight\":" << plan.value().ui_render_target_height
              << ",\"initializeShaders\":" << json_bool(plan.value().initialize_shaders)
              << ",\"initializeAssets\":" << json_bool(plan.value().initialize_assets)
              << ",\"initializeLayout\":" << json_bool(plan.value().initialize_layout)
              << ",\"updateTitle\":" << json_bool(plan.value().update_title)
              << ",\"createUiRenderTarget\":" << json_bool(plan.value().create_ui_render_target)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_app_frame_args(
    int argc,
    char** argv,
    PlanAppFrameArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--redraw") {
            args.redraw = true;
        } else if (key == "--animate") {
            args.animate = true;
        } else if (key == "--no-designer-layout") {
            args.has_designer_layout = false;
        } else if (key == "--no-main-layout") {
            args.has_main_layout = false;
        } else if (key == "--no-canvas") {
            args.has_canvas_node = false;
            args.has_canvas_document = false;
        } else if (key == "--no-canvas-document") {
            args.has_canvas_document = false;
        } else if (key == "--vr-active") {
            args.vr_active = true;
        } else if (key == "--ui-hidden") {
            args.ui_visible = false;
        } else if (key == "--vr-only") {
            args.vr_only = true;
        } else if (key == "--resize-width") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.resize_width = value.value();
        } else if (key == "--resize-height") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.resize_height = value.value();
        } else if (key == "--bad-resize") {
            args.bad_resize = true;
        } else if (key == "--observer-hidden") {
            args.observer_display = false;
        } else if (key == "--observer-on-screen") {
            args.observer_on_screen = true;
        } else if (key == "--observer-clipped-out") {
            args.observer_clipped_out = true;
        } else if (key == "--observer-bad-geometry") {
            args.observer_bad_geometry = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_app_frame(int argc, char** argv)
{
    PlanAppFrameArgs args;
    const auto status = parse_plan_app_frame_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-app-frame", status.message);
        return 2;
    }

    const auto surface = pp::app::plan_app_initial_surface();
    const auto update = pp::app::plan_app_frame_update(args.redraw, args.animate);
    const auto tick = pp::app::plan_app_frame_tick(args.has_designer_layout, args.has_main_layout);
    const auto draw = pp::app::plan_app_frame_draw(
        args.has_canvas_node,
        args.has_canvas_document,
        args.vr_active,
        args.ui_visible,
        args.vr_only);
    const auto resize = pp::app::plan_app_resize(
        args.bad_resize ? 0.0F : args.resize_width,
        args.bad_resize ? std::nanf("") : args.resize_height);
    if (!resize) {
        print_error("plan-app-frame", resize.status().message);
        return 2;
    }
    const pp::app::AppUiObserverParentClip parent_clips[] {
        {
            .clip = {
                .x = 0.0F,
                .y = 0.0F,
                .width = args.observer_clipped_out ? 10.0F : 80.0F,
                .height = args.observer_clipped_out ? 10.0F : 60.0F,
            },
            .padding_top = args.observer_clipped_out ? 0.0F : 5.0F,
            .padding_right = args.observer_clipped_out ? 0.0F : 5.0F,
            .padding_bottom = args.observer_clipped_out ? 0.0F : 5.0F,
            .padding_left = args.observer_clipped_out ? 0.0F : 5.0F,
        },
    };
    const auto observer = pp::app::plan_app_ui_observer(
        true,
        args.observer_display,
        args.observer_on_screen,
        {
            .x = args.observer_bad_geometry ? std::nanf("") : (args.observer_clipped_out ? 100.0F : 10.0F),
            .y = args.observer_clipped_out ? 100.0F : 20.0F,
            .width = args.observer_clipped_out ? 10.0F : 100.0F,
            .height = args.observer_clipped_out ? 10.0F : 50.0F,
        },
        parent_clips,
        540.0F,
        args.observer_bad_geometry ? 0.0F : 2.0F,
        10.0F,
        5.0F);
    if (!observer) {
        print_error("plan-app-frame", observer.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-app-frame\""
              << ",\"surface\":{\"width\":" << surface.width
              << ",\"height\":" << surface.height
              << "},\"update\":{\"updateFrame\":" << json_bool(update.update_frame)
              << ",\"updateLayouts\":" << json_bool(update.update_layouts)
              << ",\"refreshCanvasToolbar\":" << json_bool(update.refresh_canvas_toolbar)
              << "},\"tick\":{\"tickDesignerLayout\":" << json_bool(tick.tick_designer_layout)
              << ",\"tickMainLayout\":" << json_bool(tick.tick_main_layout)
              << "},\"draw\":{\"drawCanvasStroke\":" << json_bool(draw.draw_canvas_stroke)
              << ",\"drawVrUi\":" << json_bool(draw.draw_vr_ui)
              << ",\"drawMainUi\":" << json_bool(draw.draw_main_ui)
              << ",\"resetRedraw\":" << json_bool(draw.reset_redraw)
              << "},\"resize\":{\"width\":" << resize.value().width
              << ",\"height\":" << resize.value().height
              << ",\"renderTargetWidth\":" << resize.value().render_target_width
              << ",\"renderTargetHeight\":" << resize.value().render_target_height
              << ",\"recreateUiRenderTarget\":" << json_bool(resize.value().recreate_ui_render_target)
              << ",\"requestRedraw\":" << json_bool(resize.value().request_redraw)
              << "},\"observer\":{\"drawNode\":" << json_bool(observer.value().draw_node)
              << ",\"notifyEnterScreen\":" << json_bool(observer.value().notify_enter_screen)
              << ",\"notifyLeaveScreen\":" << json_bool(observer.value().notify_leave_screen)
              << ",\"nextOnScreen\":" << json_bool(observer.value().next_on_screen)
              << ",\"visibleWidth\":" << observer.value().visible_clip.width
              << ",\"visibleHeight\":" << observer.value().visible_clip.height
              << ",\"scissorX\":" << observer.value().scissor_x
              << ",\"scissorY\":" << observer.value().scissor_y
              << ",\"scissorWidth\":" << observer.value().scissor_width
              << ",\"scissorHeight\":" << observer.value().scissor_height
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_app_thread_args(
    int argc,
    char** argv,
    PlanAppThreadArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.kind = argv[++i];
        } else if (key == "--require-ui-thread") {
            args.require_ui_thread = true;
        } else if (key == "--on-target-thread") {
            args.on_target_thread = true;
        } else if (key == "--unique") {
            args.unique = true;
        } else if (key == "--worker-stopped") {
            args.worker_running = false;
        } else if (key == "--wait") {
            args.wait = true;
        } else if (key == "--request-redraw") {
            args.request_redraw = true;
        } else if (key == "--redraw") {
            args.redraw = true;
        } else if (key == "--live-reload") {
            args.live_reload = true;
        } else if (key == "--not-joinable") {
            args.joinable = false;
        } else if (key == "--bad-timer") {
            args.bad_timer = true;
        } else if (key == "--queued-tasks") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.queued_tasks = value.value();
        } else if (key == "--rendered-frames") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.rendered_frames = value.value();
        } else if (key == "--dt" || key == "--frame-accumulator"
            || key == "--fps-accumulator" || key == "--reload-accumulator") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--dt") {
                args.delta_time_seconds = value.value();
            } else if (key == "--frame-accumulator") {
                args.frame_accumulator = value.value();
            } else if (key == "--fps-accumulator") {
                args.fps_accumulator = value.value();
            } else {
                args.reload_accumulator = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_app_thread(int argc, char** argv)
{
    PlanAppThreadArgs args;
    const auto status = parse_plan_app_thread_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-app-thread", status.message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-app-thread\",\"kind\":\""
              << json_escape(args.kind) << "\"";

    if (args.kind == "dispatch") {
        const auto plan = pp::app::plan_app_task_dispatch(
            args.on_target_thread,
            args.unique,
            args.queued_tasks,
            args.worker_running,
            args.wait,
            args.request_redraw,
            args.require_ui_thread);
        std::cout << ",\"plan\":{\"executeImmediately\":" << json_bool(plan.execute_immediately)
                  << ",\"queueTask\":" << json_bool(plan.queue_task)
                  << ",\"removeMatchingUniqueTask\":" << json_bool(plan.remove_matching_unique_task)
                  << ",\"notifyWorker\":" << json_bool(plan.notify_worker)
                  << ",\"waitForCompletion\":" << json_bool(plan.wait_for_completion)
                  << ",\"requestRedraw\":" << json_bool(plan.request_redraw)
                  << ",\"rejectUnsafeCrossThreadDispatch\":" << json_bool(plan.reject_unsafe_cross_thread_dispatch)
                  << "}}\n";
        return 0;
    }

    if (args.kind == "render-drain" || args.kind == "ui-drain") {
        const auto plan = args.kind == "render-drain"
            ? pp::app::plan_app_render_queue_drain(args.queued_tasks)
            : pp::app::plan_app_ui_queue_drain(args.queued_tasks);
        std::cout << ",\"plan\":{\"markRunning\":" << json_bool(plan.mark_running)
                  << ",\"drainTasks\":" << json_bool(plan.drain_tasks)
                  << ",\"wrapInRenderContext\":" << json_bool(plan.wrap_in_render_context)
                  << ",\"taskCount\":" << plan.task_count
                  << "}}\n";
        return 0;
    }

    if (args.kind == "ui-tick") {
        const auto plan = pp::app::plan_app_ui_thread_tick(args.queued_tasks, args.redraw);
        std::cout << ",\"plan\":{\"markRunning\":" << json_bool(plan.mark_running)
                  << ",\"executeTasks\":" << json_bool(plan.execute_tasks)
                  << ",\"tickApp\":" << json_bool(plan.tick_app)
                  << ",\"updateBeforeRender\":" << json_bool(plan.update_before_render)
                  << ",\"enqueueRenderFrame\":" << json_bool(plan.enqueue_render_frame)
                  << ",\"taskCount\":" << plan.task_count
                  << "}}\n";
        return 0;
    }

    if (args.kind == "ui-loop") {
        const auto plan = pp::app::plan_app_ui_loop_timers(
            args.bad_timer ? -1.0F : args.delta_time_seconds,
            args.frame_accumulator,
            args.fps_accumulator,
            args.reload_accumulator,
            args.rendered_frames,
            args.live_reload);
        if (!plan) {
            print_error("plan-app-thread", plan.status().message);
            return 2;
        }
        std::cout << ",\"plan\":{\"updatePlatformFrame\":" << json_bool(plan.value().update_platform_frame)
                  << ",\"frameAccumulator\":" << plan.value().frame_accumulator
                  << ",\"fpsAccumulator\":" << plan.value().fps_accumulator
                  << ",\"reloadAccumulator\":" << plan.value().reload_accumulator
                  << ",\"reportRenderedFrames\":" << json_bool(plan.value().report_rendered_frames)
                  << ",\"reportedFrameCount\":" << plan.value().reported_frame_count
                  << ",\"renderedFramesAfterReport\":" << plan.value().rendered_frames_after_report
                  << ",\"checkLiveAssetReload\":" << json_bool(plan.value().check_live_asset_reload)
                  << "}}\n";
        return 0;
    }

    if (args.kind == "redraw") {
        const auto plan = pp::app::plan_app_ui_loop_redraw(args.redraw, args.rendered_frames);
        std::cout << ",\"plan\":{\"tickApp\":" << json_bool(plan.tick_app)
                  << ",\"updateBeforeRender\":" << json_bool(plan.update_before_render)
                  << ",\"enqueueRenderFrame\":" << json_bool(plan.enqueue_render_frame)
                  << ",\"resetFrameAccumulator\":" << json_bool(plan.reset_frame_accumulator)
                  << ",\"renderedFrames\":" << plan.rendered_frames
                  << "}}\n";
        return 0;
    }

    if (args.kind == "start") {
        const auto plan = pp::app::plan_app_thread_start();
        std::cout << ",\"plan\":{\"startThread\":" << json_bool(plan.start_thread)
                  << ",\"markRunning\":" << json_bool(plan.mark_running)
                  << "}}\n";
        return 0;
    }

    if (args.kind == "stop") {
        const auto plan = pp::app::plan_app_thread_stop(args.joinable);
        std::cout << ",\"plan\":{\"markNotRunning\":" << json_bool(plan.mark_not_running)
                  << ",\"notifyWorker\":" << json_bool(plan.notify_worker)
                  << ",\"joinThread\":" << json_bool(plan.join_thread)
                  << "}}\n";
        return 0;
    }

    print_error("plan-app-thread", "unknown app thread plan kind");
    return 2;
}

pp::foundation::Status parse_plan_app_input_args(
    int argc,
    char** argv,
    PlanAppInputArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        auto parse_next_float = [&](float& target) -> pp::foundation::Status {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            target = value.value();
            return pp::foundation::Status::success();
        };

        if (key == "--kind") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.kind = argv[++i];
        } else if (key == "--x") {
            const auto status = parse_next_float(args.x0);
            if (!status.ok()) {
                return status;
            }
        } else if (key == "--y") {
            const auto status = parse_next_float(args.y0);
            if (!status.ok()) {
                return status;
            }
        } else if (key == "--x1") {
            const auto status = parse_next_float(args.x1);
            if (!status.ok()) {
                return status;
            }
        } else if (key == "--y1") {
            const auto status = parse_next_float(args.y1);
            if (!status.ok()) {
                return status;
            }
        } else if (key == "--prev-x") {
            const auto status = parse_next_float(args.previous_x0);
            if (!status.ok()) {
                return status;
            }
        } else if (key == "--prev-y") {
            const auto status = parse_next_float(args.previous_y0);
            if (!status.ok()) {
                return status;
            }
        } else if (key == "--prev-x1") {
            const auto status = parse_next_float(args.previous_x1);
            if (!status.ok()) {
                return status;
            }
        } else if (key == "--prev-y1") {
            const auto status = parse_next_float(args.previous_y1);
            if (!status.ok()) {
                return status;
            }
        } else if (key == "--zoom") {
            const auto status = parse_next_float(args.zoom);
            if (!status.ok()) {
                return status;
            }
        } else if (key == "--no-designer-layout") {
            args.has_designer_layout = false;
        } else if (key == "--no-main-layout") {
            args.has_main_layout = false;
        } else if (key == "--spacebar") {
            args.spacebar = true;
        } else if (key == "--vr-active") {
            args.vr_active = true;
        } else if (key == "--key-up") {
            args.key_up = true;
        } else if (key == "--ui-hidden") {
            args.ui_visible = false;
        } else if (key == "--no-canvas") {
            args.has_canvas = false;
        } else if (key == "--main-child-count") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.main_child_count = value.value();
        } else if (key == "--panel-child-count") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.panel_child_count = value.value();
        } else if (key == "--bad-float") {
            args.bad_float = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_app_input(int argc, char** argv)
{
    PlanAppInputArgs args;
    const auto status = parse_plan_app_input_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-app-input", status.message);
        return 2;
    }

    if (args.bad_float) {
        args.zoom = 0.0F;
    }

    if (args.kind == "pointer") {
        const auto plan = pp::app::plan_app_pointer_dispatch(
            args.x0,
            args.y0,
            args.zoom,
            args.has_designer_layout,
            args.has_main_layout);
        if (!plan) {
            print_error("plan-app-input", plan.status().message);
            return 2;
        }
        std::cout << "{\"ok\":true,\"command\":\"plan-app-input\",\"kind\":\"pointer\""
                  << ",\"requestRedraw\":" << json_bool(plan.value().request_redraw)
                  << ",\"dispatchDesignerFirst\":" << json_bool(plan.value().dispatch_designer_first)
                  << ",\"dispatchMainIfNotConsumed\":" << json_bool(plan.value().dispatch_main_if_not_consumed)
                  << ",\"normalizedX\":" << plan.value().normalized_x
                  << ",\"normalizedY\":" << plan.value().normalized_y
                  << "}\n";
        return 0;
    }

    if (args.kind == "gesture") {
        const auto plan = pp::app::plan_app_gesture_dispatch(
            args.x0,
            args.y0,
            args.x1,
            args.y1,
            args.previous_x0,
            args.previous_y0,
            args.previous_x1,
            args.previous_y1,
            args.zoom,
            args.has_main_layout);
        if (!plan) {
            print_error("plan-app-input", plan.status().message);
            return 2;
        }
        std::cout << "{\"ok\":true,\"command\":\"plan-app-input\",\"kind\":\"gesture\""
                  << ",\"requestRedraw\":" << json_bool(plan.value().request_redraw)
                  << ",\"dispatchMain\":" << json_bool(plan.value().dispatch_main)
                  << ",\"normalizedX\":" << plan.value().normalized_x
                  << ",\"normalizedY\":" << plan.value().normalized_y
                  << ",\"distance\":" << plan.value().distance
                  << ",\"distanceDelta\":" << plan.value().distance_delta
                  << ",\"positionDeltaX\":" << plan.value().position_delta_x
                  << ",\"positionDeltaY\":" << plan.value().position_delta_y
                  << "}\n";
        return 0;
    }

    if (args.kind == "cancel") {
        const auto plan = pp::app::plan_app_mouse_cancel_dispatch(
            args.has_designer_layout,
            args.has_main_layout);
        std::cout << "{\"ok\":true,\"command\":\"plan-app-input\",\"kind\":\"cancel\""
                  << ",\"requestRedraw\":" << json_bool(plan.request_redraw)
                  << ",\"dispatchDesignerFirst\":" << json_bool(plan.dispatch_designer_first)
                  << ",\"dispatchMainIfNotConsumed\":" << json_bool(plan.dispatch_main_if_not_consumed)
                  << "}\n";
        return 0;
    }

    if (args.kind == "main") {
        const auto plan = pp::app::plan_app_main_input_dispatch(args.has_main_layout);
        std::cout << "{\"ok\":true,\"command\":\"plan-app-input\",\"kind\":\"main\""
                  << ",\"requestRedraw\":" << json_bool(plan.request_redraw)
                  << ",\"dispatchMain\":" << json_bool(plan.dispatch_main)
                  << "}\n";
        return 0;
    }

    if (args.kind == "key") {
        const auto down = pp::app::plan_app_key_down_dispatch(
            args.has_main_layout,
            args.spacebar,
            args.vr_active);
        const auto up = pp::app::plan_app_key_up_dispatch(args.has_main_layout);
        const auto& plan = args.key_up ? up : down;
        std::cout << "{\"ok\":true,\"command\":\"plan-app-input\",\"kind\":\"key\""
                  << ",\"requestRedraw\":" << json_bool(plan.request_redraw)
                  << ",\"dispatchMain\":" << json_bool(plan.dispatch_main)
                  << ",\"setKeyDown\":" << json_bool(plan.set_key_down)
                  << ",\"syncVrCameraRotation\":" << json_bool(plan.sync_vr_camera_rotation)
                  << "}\n";
        return 0;
    }

    if (args.kind == "ui-toggle") {
        const auto plan = pp::app::plan_app_ui_visibility_toggle(
            args.ui_visible,
            args.has_main_layout,
            args.main_child_count,
            args.panel_child_count);
        if (!plan) {
            print_error("plan-app-input", plan.status().message);
            return 2;
        }
        std::cout << "{\"ok\":true,\"command\":\"plan-app-input\",\"kind\":\"ui-toggle\""
                  << ",\"nextUiVisible\":" << json_bool(plan.value().next_ui_visible)
                  << ",\"firstPanelChildIndex\":" << plan.value().first_panel_child_index
                  << ",\"panelChildCount\":" << plan.value().panel_child_count
                  << "}\n";
        return 0;
    }

    if (args.kind == "stylus") {
        const auto plan = pp::app::plan_app_stylus_attach(args.has_canvas);
        std::cout << "{\"ok\":true,\"command\":\"plan-app-input\",\"kind\":\"stylus\""
                  << ",\"setHasStylus\":" << json_bool(plan.set_has_stylus)
                  << ",\"enableCanvasTouchLock\":" << json_bool(plan.enable_canvas_touch_lock)
                  << "}\n";
        return 0;
    }

    print_error("plan-app-input", "unknown input plan kind");
    return 2;
}

int plan_app_shutdown(int argc, char** argv)
{
    static_cast<void>(argv);
    if (argc > 2) {
        print_error("plan-app-shutdown", "unknown option");
        return 2;
    }

    const auto plan = pp::app::plan_app_shutdown();
    std::cout << "{\"ok\":true,\"command\":\"plan-app-shutdown\""
              << ",\"plan\":{\"saveUiState\":" << json_bool(plan.save_ui_state)
              << ",\"terminateStrokePreviewRenderer\":" << json_bool(plan.terminate_stroke_preview_renderer)
              << ",\"stopRecording\":" << json_bool(plan.stop_recording)
              << ",\"invalidateTextures\":" << json_bool(plan.invalidate_textures)
              << ",\"invalidateShaders\":" << json_bool(plan.invalidate_shaders)
              << ",\"unloadLayouts\":" << json_bool(plan.unload_layouts)
              << ",\"destroyUiRenderTarget\":" << json_bool(plan.destroy_ui_render_target)
              << ",\"destroyFacePlane\":" << json_bool(plan.destroy_face_plane)
              << ",\"releasePanelNodes\":" << json_bool(plan.release_panel_nodes)
              << ",\"clearQuickModeState\":" << json_bool(plan.clear_quick_mode_state)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_command_convert_args(
    int argc,
    char** argv,
    PlanCommandConvertArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--project") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.project_path = argv[++i];
        } else if (key == "--output") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.output_path = argv[++i];
        } else if (key == "--canvas-resolution") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.canvas_resolution = value.value();
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_command_convert(int argc, char** argv)
{
    PlanCommandConvertArgs args;
    const auto status = parse_plan_command_convert_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-command-convert", status.message);
        return 2;
    }

    const auto plan = pp::app::plan_command_convert(
        args.project_path,
        args.output_path,
        args.canvas_resolution);
    if (!plan) {
        print_error("plan-command-convert", plan.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-command-convert\""
              << ",\"project\":\"" << json_escape(plan.value().project_path)
              << "\",\"output\":\"" << json_escape(plan.value().output_path)
              << "\",\"canvasResolution\":" << plan.value().canvas_resolution
              << ",\"steps\":[";
    for (std::size_t i = 0; i < plan.value().steps.size(); ++i) {
        if (i > 0) {
            std::cout << ",";
        }
        std::cout << "\"" << command_convert_step_name(plan.value().steps[i]) << "\"";
    }
    std::cout << "]}\n";
    return 0;
}

pp::foundation::Status parse_plan_brush_package_import_args(
    int argc,
    char** argv,
    PlanBrushPackageImportArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind" || key == "--path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            if (key == "--kind") {
                args.kind = argv[++i];
            } else {
                args.path = argv[++i];
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

pp::foundation::Result<pp::app::BrushPackageImportKind> parse_brush_package_import_kind(
    std::string_view kind)
{
    if (kind == "abr") {
        return pp::foundation::Result<pp::app::BrushPackageImportKind>::success(
            pp::app::BrushPackageImportKind::abr);
    }
    if (kind == "ppbr") {
        return pp::foundation::Result<pp::app::BrushPackageImportKind>::success(
            pp::app::BrushPackageImportKind::ppbr);
    }

    return pp::foundation::Result<pp::app::BrushPackageImportKind>::failure(
        pp::foundation::Status::invalid_argument("unknown brush package import kind"));
}

class CliBrushPackageImportServices final : public pp::app::BrushPackageImportServices {
public:
    void import_brush_package(pp::app::BrushPackageImportKind kind, std::string_view path) override
    {
        imports += 1;
        last_kind = kind;
        last_path = std::string(path);
    }

    int imports = 0;
    pp::app::BrushPackageImportKind last_kind = pp::app::BrushPackageImportKind::ppbr;
    std::string last_path;
};

int plan_brush_package_import(int argc, char** argv)
{
    PlanBrushPackageImportArgs args;
    const auto status = parse_plan_brush_package_import_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-brush-package-import", status.message);
        return 2;
    }

    const auto kind = parse_brush_package_import_kind(args.kind);
    if (!kind) {
        print_error("plan-brush-package-import", kind.status().message);
        return 2;
    }

    CliBrushPackageImportServices services;
    const auto import_status = pp::app::execute_brush_package_import(kind.value(), args.path, services);
    if (!import_status.ok()) {
        print_error("plan-brush-package-import", import_status.message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-brush-package-import\""
              << ",\"request\":{\"kind\":\"" << pp::app::brush_package_import_kind_name(services.last_kind)
              << "\",\"path\":\"" << json_escape(services.last_path)
              << "\"},\"dispatches\":" << services.imports
              << "}\n";
    return 0;
}

pp::foundation::Status parse_plan_brush_package_export_args(
    int argc,
    char** argv,
    PlanBrushPackageExportArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--path" || key == "--author" || key == "--email" || key == "--url"
            || key == "--description" || key == "--dest-path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            if (key == "--path") {
                args.path = argv[++i];
            } else if (key == "--author") {
                args.author = argv[++i];
            } else if (key == "--email") {
                args.email = argv[++i];
            } else if (key == "--url") {
                args.url = argv[++i];
            } else if (key == "--description") {
                args.description = argv[++i];
            } else {
                args.destination_path = argv[++i];
            }
        } else if (key == "--export-data") {
            args.export_data = true;
        } else if (key == "--no-export-data") {
            args.export_data = false;
        } else if (key == "--header-image") {
            args.has_header_image = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

class CliBrushPackageExportServices final : public pp::app::BrushPackageExportServices {
public:
    void export_brush_package(std::string_view path, const pp::app::BrushPackageExportRequest& request) override
    {
        exports += 1;
        last_path = std::string(path);
        last_request = request;
    }

    int exports = 0;
    std::string last_path;
    pp::app::BrushPackageExportRequest last_request;
};

int plan_brush_package_export(int argc, char** argv)
{
    PlanBrushPackageExportArgs args;
    const auto status = parse_plan_brush_package_export_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-brush-package-export", status.message);
        return 2;
    }

    pp::app::BrushPackageExportRequest request;
    request.author = args.author;
    request.email = args.email;
    request.url = args.url;
    request.description = args.description;
    request.destination_path = args.destination_path;
    request.export_data = args.export_data;
    request.has_header_image = args.has_header_image;

    CliBrushPackageExportServices services;
    const auto export_status = pp::app::execute_brush_package_export(args.path, request, services);
    if (!export_status.ok()) {
        print_error("plan-brush-package-export", export_status.message);
        return 2;
    }

    const auto paths = pp::assets::plan_ppbr_export_paths(
        args.path,
        args.destination_path,
        args.export_data,
        args.destination_path.empty()
            ? pp::assets::PpbrDataDirectoryPolicy::next_to_package
            : pp::assets::PpbrDataDirectoryPolicy::override_directory);
    if (!paths) {
        print_error("plan-brush-package-export", paths.status().message);
        return 2;
    }
    const auto success_dialog = pp::app::plan_brush_package_export_success_dialog(services.last_path);

    std::cout << "{\"ok\":true,\"command\":\"plan-brush-package-export\""
              << ",\"request\":{\"path\":\"" << json_escape(services.last_path)
              << "\",\"author\":\"" << json_escape(services.last_request.author)
              << "\",\"email\":\"" << json_escape(services.last_request.email)
              << "\",\"url\":\"" << json_escape(services.last_request.url)
              << "\",\"description\":\"" << json_escape(services.last_request.description)
              << "\",\"destPath\":\"" << json_escape(services.last_request.destination_path)
              << "\",\"exportData\":" << json_bool(services.last_request.export_data)
              << ",\"hasHeaderImage\":" << json_bool(services.last_request.has_header_image)
              << "},\"paths\":{\"package\":\"" << json_escape(paths.value().package_path)
              << "\",\"directory\":\"" << json_escape(paths.value().directory)
              << "\",\"stem\":\"" << json_escape(paths.value().stem)
              << "\",\"extension\":\"" << json_escape(paths.value().extension)
              << "\",\"dataDirectory\":\"" << json_escape(paths.value().data_directory)
              << "\",\"dataDirectoryEnabled\":" << json_bool(paths.value().data_directory_enabled)
              << "},\"successDialog\":{\"title\":\"" << json_escape(success_dialog.title)
              << "\",\"message\":\"" << json_escape(success_dialog.message)
              << "\",\"showCancel\":" << json_bool(success_dialog.show_cancel)
              << "},\"dispatches\":" << services.exports
              << "}\n";
    return 0;
}

pp::foundation::Status parse_plan_tools_menu_args(
    int argc,
    char** argv,
    PlanToolsMenuArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--command") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.command = argv[++i];
        } else if (key == "--sonarpen-available") {
            args.sonarpen_available = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_tools_menu(int argc, char** argv)
{
    PlanToolsMenuArgs args;
    const auto status = parse_plan_tools_menu_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-tools-menu", status.message);
        return 2;
    }

    const auto command = parse_tools_menu_command(args.command);
    if (!command) {
        print_error("plan-tools-menu", command.status().message);
        return 2;
    }

    const auto plan = pp::app::plan_tools_menu_command(command.value(), args.sonarpen_available);

    std::cout << "{\"ok\":true,\"command\":\"plan-tools-menu\""
              << ",\"state\":{\"command\":\"" << json_escape(args.command)
              << "\",\"sonarpenAvailable\":" << json_bool(args.sonarpen_available)
              << "},\"plan\":{\"command\":\"" << tools_menu_command_name(plan.command)
              << "\",\"action\":\"" << tools_menu_action_name(plan.action)
              << "\",\"label\":\"" << json_escape(std::string(plan.label))
              << "\",\"closesRootPopup\":" << json_bool(plan.closes_root_popup)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_tools_panel_args(
    int argc,
    char** argv,
    PlanToolsPanelArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--panel") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.panel = argv[++i];
        } else if (key == "--already-visible") {
            args.already_visible = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_tools_panel(int argc, char** argv)
{
    PlanToolsPanelArgs args;
    const auto status = parse_plan_tools_panel_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-tools-panel", status.message);
        return 2;
    }

    const auto panel = parse_tools_panel(args.panel);
    if (!panel) {
        print_error("plan-tools-panel", panel.status().message);
        return 2;
    }

    const auto plan = pp::app::plan_tools_panel(panel.value(), args.already_visible);

    std::cout << "{\"ok\":true,\"command\":\"plan-tools-panel\""
              << ",\"state\":{\"panel\":\"" << json_escape(args.panel)
              << "\",\"alreadyVisible\":" << json_bool(args.already_visible)
              << "},\"plan\":{\"panel\":\"" << tools_panel_name(plan.panel)
              << "\",\"action\":\"" << tools_panel_action_name(plan.action)
              << "\",\"title\":\"" << json_escape(std::string(plan.title))
              << "\",\"width\":" << plan.width
              << ",\"height\":" << plan.height
              << ",\"minWidth\":" << plan.min_width
              << ",\"minHeight\":" << plan.min_height
              << ",\"droppable\":" << json_bool(plan.droppable)
              << ",\"hidesEmbeddedTitle\":" << json_bool(plan.hides_embedded_title)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_about_menu_args(
    int argc,
    char** argv,
    PlanAboutMenuArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--command") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.command = argv[++i];
        } else if (key == "--version-major" || key == "--version-minor" || key == "--version-fix") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--version-major") {
                args.version_major = value.value();
            } else if (key == "--version-minor") {
                args.version_minor = value.value();
            } else {
                args.version_fix = value.value();
            }
        } else if (key == "--no-diagnostics") {
            args.diagnostics_available = false;
        } else if (key == "--no-canvas") {
            args.has_canvas = false;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_about_menu(int argc, char** argv)
{
    PlanAboutMenuArgs args;
    const auto status = parse_plan_about_menu_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-about-menu", status.message);
        return 2;
    }

    const auto command = parse_about_menu_command(args.command);
    if (!command) {
        print_error("plan-about-menu", command.status().message);
        return 2;
    }

    const auto plan = pp::app::plan_about_menu_command(
        command.value(),
        args.version_major,
        args.version_minor,
        args.version_fix,
        args.diagnostics_available,
        args.has_canvas);

    std::cout << "{\"ok\":true,\"command\":\"plan-about-menu\""
              << ",\"state\":{\"command\":\"" << json_escape(args.command)
              << "\",\"versionMajor\":" << args.version_major
              << ",\"versionMinor\":" << args.version_minor
              << ",\"versionFix\":" << args.version_fix
              << ",\"diagnosticsAvailable\":" << json_bool(args.diagnostics_available)
              << ",\"hasCanvas\":" << json_bool(args.has_canvas)
              << "},\"plan\":{\"command\":\"" << about_menu_command_name(plan.command)
              << "\",\"action\":\"" << about_menu_action_name(plan.action)
              << "\",\"label\":\"" << json_escape(plan.label)
              << "\",\"closesRootPopup\":" << json_bool(plan.closes_root_popup)
              << ",\"requiresCanvas\":" << json_bool(plan.requires_canvas)
              << ",\"performanceIterations\":" << plan.performance_iterations
              << ",\"performanceUpdatesPerIteration\":" << plan.performance_updates_per_iteration
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_app_status_args(
    int argc,
    char** argv,
    PlanAppStatusArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--doc-name") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.document_name = argv[++i];
        } else if (key == "--unsaved") {
            args.unsaved = true;
        } else if (key == "--resolution" || key == "--resolution-index" || key == "--history-bytes"
            || key == "--encoded-frames") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--resolution") {
                args.resolution = static_cast<int>(value.value());
            } else if (key == "--resolution-index") {
                args.resolution_index = static_cast<int>(value.value());
            } else if (key == "--history-bytes") {
                args.history_bytes = value.value();
            } else {
                args.encoded_frames = value.value();
            }
        } else if (key == "--zoom") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.zoom = value.value();
        } else if (key == "--recording-running") {
            args.recording_running = true;
        } else if (key == "--encoder-available") {
            args.encoder_available = true;
        } else if (key == "--framebuffer-fetch") {
            args.framebuffer_fetch = true;
        } else if (key == "--float32") {
            args.float32_render_targets = true;
        } else if (key == "--float32-linear") {
            args.float32_linear_filtering = true;
        } else if (key == "--float16") {
            args.float16_render_targets = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_app_status(int argc, char** argv)
{
    PlanAppStatusArgs args;
    const auto status = parse_plan_app_status_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-app-status", status.message);
        return 2;
    }

    const auto resolution_from_index = pp::app::display_resolution_from_index(args.resolution_index);
    const auto resolution_index = pp::app::document_resolution_to_index(args.resolution);
    const auto resolution_label = pp::app::document_resolution_label(args.resolution);
    const auto recording_label = pp::app::make_recording_frame_label(
        args.recording_running,
        args.encoder_available,
        static_cast<int>(args.encoded_frames));
    const auto diagnostics = pp::app::plan_renderer_diagnostics({
        .framebuffer_fetch = args.framebuffer_fetch,
        .float32_render_targets = args.float32_render_targets,
        .float32_linear_filtering = args.float32_linear_filtering,
        .float16_render_targets = args.float16_render_targets,
    });

    std::cout << "{\"ok\":true,\"command\":\"plan-app-status\""
              << ",\"state\":{\"documentName\":\"" << json_escape(args.document_name)
              << "\",\"unsaved\":" << json_bool(args.unsaved)
              << ",\"resolution\":" << args.resolution
              << ",\"resolutionIndex\":" << args.resolution_index
              << ",\"zoom\":" << args.zoom
              << ",\"historyBytes\":" << args.history_bytes
              << ",\"recordingRunning\":" << json_bool(args.recording_running)
              << ",\"encoderAvailable\":" << json_bool(args.encoder_available)
              << ",\"encodedFrames\":" << args.encoded_frames
              << ",\"framebufferFetch\":" << json_bool(args.framebuffer_fetch)
              << ",\"float32\":" << json_bool(args.float32_render_targets)
              << ",\"float32Linear\":" << json_bool(args.float32_linear_filtering)
              << ",\"float16\":" << json_bool(args.float16_render_targets)
              << "},\"title\":\"" << json_escape(pp::app::make_document_title(
                     args.document_name,
                     args.unsaved,
                     args.resolution))
              << "\",\"dpi\":\"" << json_escape(pp::app::make_dpi_label(args.zoom))
              << "\",\"memory\":\"" << json_escape(pp::app::make_history_memory_label(args.history_bytes))
              << "\",\"recording\":{\"visible\":" << json_bool(recording_label.visible)
              << ",\"text\":\"" << json_escape(recording_label.text)
              << "\"},\"rendererDiagnostics\":{\"framebufferFetch\":{\"supported\":"
              << json_bool(diagnostics.framebuffer_fetch.supported)
              << ",\"label\":\"" << json_escape(std::string(diagnostics.framebuffer_fetch.label))
              << "\"},\"floatingPointTargets\":{\"supported\":"
              << json_bool(diagnostics.floating_point_targets.supported)
              << ",\"label\":\"" << json_escape(std::string(diagnostics.floating_point_targets.label))
              << "\"}},\"resolutionMap\":{\"fromIndexValid\":" << json_bool(static_cast<bool>(resolution_from_index))
              << ",\"fromIndex\":" << (resolution_from_index ? resolution_from_index.value() : 0)
              << ",\"toIndexValid\":" << json_bool(static_cast<bool>(resolution_index))
              << ",\"toIndex\":" << (resolution_index ? resolution_index.value() : 0)
              << ",\"labelValid\":" << json_bool(static_cast<bool>(resolution_label))
              << ",\"label\":\"" << json_escape(resolution_label ? std::string(resolution_label.value()) : std::string())
              << "\"}}\n";
    return 0;
}

pp::foundation::Status parse_plan_document_resize_args(
    int argc,
    char** argv,
    PlanDocumentResizeArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--current-resolution" || key == "--selected-resolution-index") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--current-resolution") {
                args.current_resolution = static_cast<int>(value.value());
            } else {
                args.selected_resolution_index = static_cast<int>(value.value());
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_document_resize(int argc, char** argv)
{
    PlanDocumentResizeArgs args;
    const auto status = parse_plan_document_resize_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-document-resize", status.message);
        return 2;
    }

    const auto state = pp::app::make_document_resize_dialog_state(args.current_resolution);
    const auto plan = pp::app::plan_document_resize(args.selected_resolution_index);
    if (!plan) {
        print_error("plan-document-resize", plan.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-document-resize\""
              << ",\"state\":{\"currentResolution\":" << state.current_resolution
              << ",\"currentResolutionText\":\"" << json_escape(state.current_resolution_text)
              << "\",\"currentResolutionIndex\":" << state.current_resolution_index
              << ",\"selectedResolutionIndex\":" << args.selected_resolution_index
              << "},\"plan\":{\"resolution\":" << plan.value().resolution
              << ",\"width\":" << plan.value().width
              << ",\"height\":" << plan.value().height
              << ",\"clearsHistory\":" << json_bool(plan.value().clears_history)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_canvas_clear_args(
    int argc,
    char** argv,
    PlanCanvasClearArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--r" || key == "--g" || key == "--b" || key == "--a") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--r") {
                args.r = value.value();
            } else if (key == "--g") {
                args.g = value.value();
            } else if (key == "--b") {
                args.b = value.value();
            } else {
                args.a = value.value();
            }
        } else if (key == "--no-canvas") {
            args.has_canvas = false;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_canvas_clear(int argc, char** argv)
{
    PlanCanvasClearArgs args;
    const auto status = parse_plan_canvas_clear_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-canvas-clear", status.message);
        return 2;
    }

    const auto plan = pp::app::plan_document_canvas_clear(
        args.has_canvas,
        args.r,
        args.g,
        args.b,
        args.a);
    if (!plan) {
        print_error("plan-canvas-clear", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-canvas-clear\""
              << ",\"state\":{\"hasCanvas\":" << json_bool(args.has_canvas)
              << ",\"r\":" << args.r
              << ",\"g\":" << args.g
              << ",\"b\":" << args.b
              << ",\"a\":" << args.a
              << "},\"plan\":{\"r\":" << value.r
              << ",\"g\":" << value.g
              << ",\"b\":" << value.b
              << ",\"a\":" << value.a
              << ",\"clearsCanvas\":" << json_bool(value.clears_canvas)
              << ",\"recordsUndo\":" << json_bool(value.records_undo)
              << ",\"marksUnsaved\":" << json_bool(value.marks_unsaved)
              << ",\"noOp\":" << json_bool(value.no_op)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_canvas_project_save_target_args(
    int argc,
    char** argv,
    PlanCanvasProjectSaveTargetArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--data-dir" || key == "--path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            if (key == "--data-dir") {
                args.data_directory = argv[++i];
            } else {
                args.target_path = argv[++i];
            }
        } else if (key == "--target-exists") {
            args.target_exists = true;
        } else if (key == "--remove-fails") {
            args.remove_fails = true;
        } else if (key == "--rename-fails") {
            args.rename_fails = true;
        } else if (key == "--encoder") {
            args.encoder_available = true;
        } else if (key == "--progress") {
            args.progress_visible = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_canvas_project_save_target(int argc, char** argv)
{
    PlanCanvasProjectSaveTargetArgs args;
    const auto status = parse_plan_canvas_project_save_target_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-canvas-project-save-target", status.message);
        return 2;
    }

    const auto plan = pp::app::plan_document_canvas_project_save_target(
        args.data_directory,
        args.target_path);
    if (!plan) {
        print_error("plan-canvas-project-save-target", plan.status().message);
        return 2;
    }

    const auto write_plan = pp::app::plan_document_canvas_project_save_write(
        plan.value(),
        args.target_exists);
    if (!write_plan) {
        print_error("plan-canvas-project-save-target", write_plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    const auto& write_value = write_plan.value();
    const bool target_remove_attempted = write_value.uses_temporary;
    const bool target_remove_succeeded = target_remove_attempted && !args.remove_fails;
    const bool temporary_rename_attempted = target_remove_succeeded;
    const bool temporary_rename_succeeded = temporary_rename_attempted && !args.rename_fails;
    const auto commit_plan = pp::app::plan_document_canvas_project_save_commit(
        pp::app::DocumentCanvasProjectSaveCommitInput {
            .used_temporary = write_value.uses_temporary,
            .target_remove_attempted = target_remove_attempted,
            .target_remove_succeeded = target_remove_succeeded,
            .temporary_rename_attempted = temporary_rename_attempted,
            .temporary_rename_succeeded = temporary_rename_succeeded,
        });
    const auto post_commit_plan = pp::app::plan_document_canvas_project_save_post_commit(
        pp::app::DocumentCanvasProjectSavePostCommitInput {
            .save_succeeded = commit_plan.saved,
            .timelapse_encoder_available = args.encoder_available,
            .progress_ui_visible = args.progress_visible,
        });
    std::cout << "{\"ok\":true,\"command\":\"plan-canvas-project-save-target\""
              << ",\"dataDirectory\":\"" << json_escape(args.data_directory)
              << "\",\"targetPath\":\"" << json_escape(value.target_path)
              << "\",\"fileName\":\"" << json_escape(value.file_name)
              << "\",\"temporaryPath\":\"" << json_escape(value.temporary_path)
              << "\",\"timelapsePath\":\"" << json_escape(value.timelapse_path)
              << "\",\"writePlan\":{\"action\":\""
              << document_canvas_project_save_write_action_name(write_value.action)
              << "\",\"targetExists\":" << json_bool(write_value.target_exists)
              << ",\"usesTemporary\":" << json_bool(write_value.uses_temporary)
              << ",\"writePath\":\"" << json_escape(write_value.write_path)
              << "\",\"fallbackDirectOnTemporaryOpenFailure\":"
              << json_bool(write_value.falls_back_to_direct_on_temporary_open_failure)
              << "},\"commitPlan\":{\"saved\":" << json_bool(commit_plan.saved)
              << ",\"usedTemporary\":" << json_bool(commit_plan.used_temporary)
              << ",\"targetRemoved\":" << json_bool(commit_plan.target_removed)
              << ",\"temporaryRenamed\":" << json_bool(commit_plan.temporary_renamed)
              << ",\"targetMayBeMissing\":" << json_bool(commit_plan.target_may_be_missing)
              << ",\"message\":\"" << json_escape(std::string(commit_plan.log_message))
              << "\"},\"postCommitPlan\":{\"marksDocumentClean\":"
              << json_bool(post_commit_plan.marks_document_clean)
              << ",\"marksNewDocumentCommitted\":"
              << json_bool(post_commit_plan.marks_new_document_committed)
              << ",\"savesTimelapseSidecar\":"
              << json_bool(post_commit_plan.saves_timelapse_sidecar)
              << ",\"flushesPlatformStorage\":"
              << json_bool(post_commit_plan.flushes_platform_storage)
              << ",\"dismissesProgressUi\":"
              << json_bool(post_commit_plan.dismisses_progress_ui)
              << ",\"updatesTitle\":" << json_bool(post_commit_plan.updates_title)
              << "}"
              << "}\n";
    return 0;
}

pp::foundation::Status parse_plan_canvas_document_snapshot_args(
    int argc,
    char** argv,
    PlanCanvasDocumentSnapshotArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--no-canvas") {
            args.has_canvas = false;
        } else if (key == "--width" || key == "--height" || key == "--layers" || key == "--frames"
            || key == "--frame-duration-ms" || key == "--current-layer" || key == "--current-frame"
            || key == "--hidden-layer" || key == "--alpha-locked-layer"
            || key == "--pending-face-payloads-per-layer" || key == "--captured-face-payloads-per-layer") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--width") {
                args.width = value.value();
            } else if (key == "--height") {
                args.height = value.value();
            } else if (key == "--layers") {
                args.layers = value.value();
            } else if (key == "--frames") {
                args.frames = value.value();
            } else if (key == "--frame-duration-ms") {
                args.frame_duration_ms = value.value();
            } else if (key == "--current-layer") {
                args.current_layer = value.value();
            } else if (key == "--current-frame") {
                args.current_frame = value.value();
            } else if (key == "--hidden-layer") {
                args.hidden_layer = value.value();
            } else if (key == "--alpha-locked-layer") {
                args.alpha_locked_layer = value.value();
            } else if (key == "--pending-face-payloads-per-layer") {
                args.pending_face_payloads_per_layer = value.value();
            } else {
                args.captured_face_payloads_per_layer = value.value();
            }
        } else if (key == "--opacity") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.opacity = value.value();
        } else if (key == "--blend-mode") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.blend_mode = value.value();
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_canvas_document_snapshot(int argc, char** argv)
{
    PlanCanvasDocumentSnapshotArgs args;
    const auto status = parse_plan_canvas_document_snapshot_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-canvas-document-snapshot", status.message);
        return 2;
    }

    std::vector<std::uint32_t> frame_durations(args.frames, args.frame_duration_ms);
    std::vector<std::string> layer_names;
    std::vector<std::vector<std::uint8_t>> payload_bytes;
    std::vector<std::vector<pp::app::DocumentCanvasFacePayloadInput>> captured_payloads;
    std::vector<pp::app::DocumentCanvasLayerSnapshotInput> layers;
    layer_names.reserve(args.layers);
    payload_bytes.reserve(static_cast<std::size_t>(args.layers) * args.captured_face_payloads_per_layer);
    captured_payloads.reserve(args.layers);
    layers.reserve(args.layers);
    for (std::uint32_t layer_index = 0; layer_index < args.layers; ++layer_index) {
        layer_names.push_back("Layer " + std::to_string(layer_index + 1U));
        captured_payloads.push_back({});
        auto& layer_payloads = captured_payloads.back();
        layer_payloads.reserve(args.captured_face_payloads_per_layer);
        for (std::uint32_t payload_index = 0; payload_index < args.captured_face_payloads_per_layer; ++payload_index) {
            const auto face_index = payload_index % pp::document::cube_face_count;
            payload_bytes.push_back(std::vector<std::uint8_t> {
                static_cast<std::uint8_t>((layer_index + 1U) & 0xFFU),
                static_cast<std::uint8_t>(face_index & 0xFFU),
                static_cast<std::uint8_t>((payload_index + 1U) & 0xFFU),
                255U,
            });
            layer_payloads.push_back(pp::app::DocumentCanvasFacePayloadInput {
                .frame_index = args.frames == 0U ? 0U : args.current_frame % args.frames,
                .face_index = face_index,
                .x = args.width == 0U ? 0U : payload_index % args.width,
                .y = args.height == 0U ? 0U : payload_index % args.height,
                .width = 1U,
                .height = 1U,
                .rgba8 = std::span<const std::uint8_t>(payload_bytes.back().data(), payload_bytes.back().size()),
            });
        }
        layers.push_back(pp::app::DocumentCanvasLayerSnapshotInput {
            .name = layer_names.back(),
            .visible = layer_index != args.hidden_layer,
            .alpha_locked = layer_index == args.alpha_locked_layer,
            .opacity = layer_index == args.current_layer ? args.opacity : 1.0F,
            .blend_mode = layer_index == args.current_layer ? args.blend_mode : 0,
            .frame_durations_ms = std::span<const std::uint32_t>(frame_durations),
            .pending_face_payloads = args.pending_face_payloads_per_layer,
            .captured_face_payloads = std::span<const pp::app::DocumentCanvasFacePayloadInput>(layer_payloads),
        });
    }

    const auto result = pp::app::plan_document_canvas_snapshot(pp::app::DocumentCanvasSnapshotInput {
        .has_canvas = args.has_canvas,
        .width = args.width,
        .height = args.height,
        .active_layer_index = args.current_layer,
        .active_frame_index = args.current_frame,
        .layers = std::span<const pp::app::DocumentCanvasLayerSnapshotInput>(layers),
    });
    if (!result) {
        print_error("plan-canvas-document-snapshot", result.status().message);
        return 2;
    }

    const auto& value = result.value();
    const auto& document = value.document;
    const auto& active_layer = document.layers()[document.active_layer_index()];
    const auto save_report = pp::app::make_document_canvas_save_snapshot_report(value);
    const auto save_writer_route = pp::app::plan_document_canvas_save_writer_route(save_report);
    bool ppi_export_ready = false;
    std::size_t ppi_export_bytes = 0;
    std::uint32_t ppi_export_dirty_faces = 0;
    bool renderer_upload_ready = false;
    std::size_t renderer_texture_count = 0;
    std::size_t renderer_transition_count = 0;
    std::uint64_t renderer_uploaded_bytes = 0;
    std::size_t renderer_face_payloads = 0;
    std::size_t renderer_composited_layer_faces = 0;
    std::size_t renderer_command_count = 0;
    std::size_t renderer_upload_command_count = 0;
    std::size_t renderer_transition_command_count = 0;
    bool face_png_export_ready = false;
    std::size_t face_png_export_faces = 0;
    std::uint64_t face_png_export_bytes = 0;
    std::size_t face_png_export_payloads = 0;
    bool depth_export_ready = false;
    std::uint32_t depth_export_width = 0;
    std::uint32_t depth_export_height = 0;
    std::size_t depth_export_merged_face_draws = 0;
    std::size_t depth_export_layer_depth_draws = 0;
    std::size_t depth_export_visited_layers = 0;
    std::size_t depth_export_visible_layers = 0;
    std::size_t depth_export_face_payloads = 0;
    bool depth_export_requires_renderer_readback = value.requires_renderer_payload_readback;
    if (save_writer_route.uses_document_ppi_writer) {
        const auto exported = pp::app::export_document_canvas_save_snapshot_to_ppi(value);
        if (!exported) {
            print_error("plan-canvas-document-snapshot", exported.status().message);
            return 2;
        }

        const auto decoded = pp::assets::decode_ppi_project_images(exported.value().bytes);
        if (!decoded) {
            print_error("plan-canvas-document-snapshot", decoded.status().message);
            return 2;
        }

        ppi_export_ready = true;
        ppi_export_bytes = exported.value().bytes.size();
        ppi_export_dirty_faces = decoded.value().project.body.summary.dirty_face_count;

        const auto readiness = pp::paint_renderer::prepare_document_frame_export_readiness(
            pp::paint_renderer::DocumentFrameCompositeRequest {
                .document = &document,
                .frame_index = document.active_frame_index(),
                .clear_color = {},
            });
        if (!readiness) {
            print_error("plan-canvas-document-snapshot", readiness.status().message);
            return 2;
        }

        renderer_upload_ready = true;
        renderer_texture_count = readiness.value().recorded_upload.upload.texture_count;
        renderer_transition_count = readiness.value().recorded_upload.upload.transition_count;
        renderer_uploaded_bytes = readiness.value().recorded_upload.upload.uploaded_bytes;
        renderer_face_payloads = readiness.value().recorded_upload.upload.composite.face_payload_count;
        renderer_composited_layer_faces =
            readiness.value().recorded_upload.upload.composite.composited_layer_face_count;
        renderer_command_count = readiness.value().recorded_upload.command_count;
        renderer_upload_command_count = readiness.value().recorded_upload.upload_command_count;
        renderer_transition_command_count = readiness.value().recorded_upload.transition_command_count;

        face_png_export_ready = true;
        face_png_export_faces = readiness.value().face_pngs.face_count;
        face_png_export_bytes = readiness.value().face_pngs.encoded_bytes;
        face_png_export_payloads = readiness.value().face_pngs.composite.face_payload_count;

        const auto depth_plan = pp::paint_renderer::plan_document_depth_export_render(
            pp::paint_renderer::DocumentDepthExportRenderPlanRequest {
                .document = &document,
                .frame_index = document.active_frame_index(),
            });
        if (!depth_plan) {
            print_error("plan-canvas-document-snapshot", depth_plan.status().message);
            return 2;
        }

        depth_export_ready = true;
        depth_export_width = depth_plan.value().output_extent.width;
        depth_export_height = depth_plan.value().output_extent.height;
        depth_export_merged_face_draws = depth_plan.value().merged_face_draw_count;
        depth_export_layer_depth_draws = depth_plan.value().layer_depth_draw_count;
        depth_export_visited_layers = depth_plan.value().visited_layer_count;
        depth_export_visible_layers = depth_plan.value().visible_layer_count;
        depth_export_face_payloads = depth_plan.value().face_payload_count;
        depth_export_requires_renderer_readback = depth_plan.value().requires_renderer_readback;
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-canvas-document-snapshot\""
              << ",\"state\":{\"hasCanvas\":" << json_bool(args.has_canvas)
              << ",\"width\":" << args.width
              << ",\"height\":" << args.height
              << ",\"layers\":" << args.layers
              << ",\"frames\":" << args.frames
              << ",\"currentLayer\":" << args.current_layer
              << ",\"currentFrame\":" << args.current_frame
              << "},\"snapshot\":{\"width\":" << document.width()
              << ",\"height\":" << document.height()
              << ",\"layers\":" << value.layer_count
              << ",\"frames\":" << value.frame_count
              << ",\"activeLayer\":" << document.active_layer_index()
              << ",\"activeFrame\":" << document.active_frame_index()
              << ",\"activeLayerName\":\"" << json_escape(active_layer.name)
              << "\",\"activeLayerOpacity\":" << active_layer.opacity
              << ",\"activeLayerBlend\":\"" << pp::paint::blend_mode_name(active_layer.blend_mode)
              << "\",\"activeLayerAlphaLocked\":" << json_bool(active_layer.alpha_locked)
              << ",\"pendingFacePayloads\":" << value.pending_face_payloads
              << ",\"capturedFacePayloads\":" << value.captured_face_payloads
              << ",\"metadataOnly\":" << json_bool(value.metadata_only)
              << ",\"requiresRendererPayloadReadback\":"
              << json_bool(value.requires_renderer_payload_readback)
              << ",\"documentFacePayloads\":" << document.face_pixel_payload_count()
              << ",\"saveReport\":{\"payloadComplete\":" << json_bool(save_report.payload_complete)
              << ",\"canExportPpi\":" << json_bool(save_report.can_export_ppi)
              << "},\"saveWriterRoute\":{\"action\":\""
              << document_canvas_save_writer_action_name(save_writer_route.action)
              << "\",\"usesDocumentPpiWriter\":" << json_bool(save_writer_route.uses_document_ppi_writer)
              << ",\"fallbackReason\":\""
              << json_escape(std::string(save_writer_route.fallback_reason))
              << "\""
              << "},\"ppiExport\":{\"ready\":" << json_bool(ppi_export_ready)
              << ",\"bytes\":" << ppi_export_bytes
              << ",\"dirtyFaces\":" << ppi_export_dirty_faces
              << "},\"rendererUpload\":{\"ready\":" << json_bool(renderer_upload_ready)
              << ",\"textures\":" << renderer_texture_count
              << ",\"bytes\":" << renderer_uploaded_bytes
              << ",\"transitions\":" << renderer_transition_count
              << ",\"facePayloads\":" << renderer_face_payloads
              << ",\"compositedLayerFaces\":" << renderer_composited_layer_faces
              << ",\"commands\":" << renderer_command_count
              << ",\"uploadCommands\":" << renderer_upload_command_count
              << ",\"transitionCommands\":" << renderer_transition_command_count
              << "},\"facePngExport\":{\"ready\":" << json_bool(face_png_export_ready)
              << ",\"faces\":" << face_png_export_faces
              << ",\"bytes\":" << face_png_export_bytes
              << ",\"facePayloads\":" << face_png_export_payloads
              << "},\"depthExport\":{\"ready\":" << json_bool(depth_export_ready)
              << ",\"width\":" << depth_export_width
              << ",\"height\":" << depth_export_height
              << ",\"mergedFaceDraws\":" << depth_export_merged_face_draws
              << ",\"layerDepthDraws\":" << depth_export_layer_depth_draws
              << ",\"visitedLayers\":" << depth_export_visited_layers
              << ",\"visibleLayers\":" << depth_export_visible_layers
              << ",\"facePayloads\":" << depth_export_face_payloads
              << ",\"requiresRendererReadback\":" << json_bool(depth_export_requires_renderer_readback)
              << "}"
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_image_import_args(
    int argc,
    char** argv,
    PlanImageImportArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--width" || key == "--height") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--width") {
                args.width = value.value();
            } else {
                args.height = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_image_import(int argc, char** argv)
{
    PlanImageImportArgs args;
    const auto status = parse_plan_image_import_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-image-import", status.message);
        return 2;
    }

    const auto plan = pp::app::plan_document_image_import(args.width, args.height);
    if (!plan) {
        print_error("plan-image-import", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-image-import\""
              << ",\"state\":{\"width\":" << args.width
              << ",\"height\":" << args.height
              << "},\"plan\":{\"width\":" << value.width
              << ",\"height\":" << value.height
              << ",\"action\":\"" << document_image_import_action_name(value.action)
              << "\",\"importsEquirectangular\":" << json_bool(value.imports_equirectangular)
              << ",\"entersTransformMode\":" << json_bool(value.enters_transform_mode)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_layer_rename_args(
    int argc,
    char** argv,
    PlanLayerRenameArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--old-name" || key == "--new-name") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            if (key == "--old-name") {
                args.old_name = argv[++i];
            } else {
                args.new_name = argv[++i];
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_layer_rename(int argc, char** argv)
{
    PlanLayerRenameArgs args;
    const auto status = parse_plan_layer_rename_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-layer-rename", status.message);
        return 2;
    }

    const auto plan = pp::app::plan_document_layer_rename(args.old_name, args.new_name);
    if (!plan) {
        print_error("plan-layer-rename", plan.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-layer-rename\""
              << ",\"state\":{\"oldName\":\"" << json_escape(args.old_name)
              << "\",\"newName\":\"" << json_escape(args.new_name)
              << "\"},\"plan\":{\"oldName\":\"" << json_escape(plan.value().old_name)
              << "\",\"newName\":\"" << json_escape(plan.value().new_name)
              << "\",\"action\":\"" << document_layer_rename_action_name(plan.value().action)
              << "\"}}\n";
    return 0;
}

pp::foundation::Status parse_plan_layer_menu_args(
    int argc,
    char** argv,
    PlanLayerMenuArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--command" || key == "--current-name" || key == "--lower-name") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            if (key == "--command") {
                args.command = argv[++i];
            } else if (key == "--current-name") {
                args.current_name = argv[++i];
            } else {
                args.lower_name = argv[++i];
            }
        } else if (key == "--current-index" || key == "--animation-duration") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--current-index") {
                args.current_index = value.value();
            } else {
                args.animation_duration = value.value();
            }
        } else if (key == "--no-current-layer") {
            args.has_current_layer = false;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_layer_menu(int argc, char** argv)
{
    PlanLayerMenuArgs args;
    const auto status = parse_plan_layer_menu_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-layer-menu", status.message);
        return 2;
    }

    const auto command = parse_document_layer_menu_command(args.command);
    if (!command) {
        print_error("plan-layer-menu", command.status().message);
        return 2;
    }

    const auto plan = pp::app::plan_document_layer_menu(
        command.value(),
        args.has_current_layer,
        args.current_index,
        args.animation_duration,
        args.current_name,
        args.lower_name);
    if (!plan) {
        print_error("plan-layer-menu", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-layer-menu\""
              << ",\"state\":{\"command\":\"" << json_escape(args.command)
              << "\",\"hasCurrentLayer\":" << json_bool(args.has_current_layer)
              << ",\"currentIndex\":" << args.current_index
              << ",\"animationDuration\":" << args.animation_duration
              << ",\"currentName\":\"" << json_escape(args.current_name)
              << "\",\"lowerName\":\"" << json_escape(args.lower_name)
              << "\"},\"plan\":{\"command\":\"" << document_layer_menu_command_name(value.command)
              << "\",\"action\":\"" << document_layer_menu_action_name(value.action)
              << "\",\"label\":\"" << json_escape(value.label)
              << "\",\"fromIndex\":" << value.from_index
              << ",\"toIndex\":" << value.to_index
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_layer_panel_view_args(
    int argc,
    char** argv,
    PlanLayerPanelViewArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--layer-count" || key == "--current-index" || key == "--hidden-index"
            || key == "--locked-index" || key == "--current-blend-mode") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--layer-count") {
                args.layer_count = value.value();
            } else if (key == "--current-index") {
                args.current_index = value.value();
            } else if (key == "--hidden-index") {
                args.hidden_index = value.value();
            } else if (key == "--locked-index") {
                args.locked_index = value.value();
            } else {
                args.current_blend_mode = value.value();
            }
        } else if (key == "--current-opacity") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.current_opacity = value.value();
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_layer_panel_view(int argc, char** argv)
{
    PlanLayerPanelViewArgs args;
    const auto status = parse_plan_layer_panel_view_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-layer-panel-view", status.message);
        return 2;
    }

    std::vector<pp::app::DocumentLayerPanelInput> layers;
    if (args.layer_count > 0) {
        layers.reserve(static_cast<std::size_t>(args.layer_count));
    }
    for (int i = 0; i < args.layer_count; ++i) {
        layers.push_back(pp::app::DocumentLayerPanelInput {
            .layer_index = i,
            .name = "Layer " + std::to_string(i),
            .opacity = i == args.current_index ? args.current_opacity : 1.0F,
            .visible = i != args.hidden_index,
            .alpha_locked = i == args.locked_index,
            .blend_mode = i == args.current_index ? args.current_blend_mode : 0,
        });
    }

    const auto view = pp::app::plan_document_layer_panel_view(layers, args.current_index);
    if (!view) {
        print_error("plan-layer-panel-view", view.status().message);
        return 2;
    }

    int visible_count = 0;
    int locked_count = 0;
    for (const auto& layer : view.value().layers) {
        if (layer.visible) {
            visible_count += 1;
        }
        if (layer.alpha_locked) {
            locked_count += 1;
        }
    }

    const auto current_layer = std::find_if(
        view.value().layers.begin(),
        view.value().layers.end(),
        [](const pp::app::DocumentLayerPanelLayerView& layer) { return layer.current; });
    if (current_layer == view.value().layers.end()) {
        print_error("plan-layer-panel-view", "layer panel view did not include the current layer");
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-layer-panel-view\""
              << ",\"state\":{\"layerCount\":" << args.layer_count
              << ",\"currentIndex\":" << args.current_index
              << ",\"hiddenIndex\":" << args.hidden_index
              << ",\"lockedIndex\":" << args.locked_index
              << ",\"currentOpacity\":" << args.current_opacity
              << ",\"currentBlendMode\":" << args.current_blend_mode
              << "},\"view\":{\"layers\":" << view.value().layers.size()
              << ",\"currentIndex\":" << view.value().current_index
              << ",\"currentName\":\"" << json_escape(current_layer->name)
              << "\",\"currentOpacity\":" << view.value().current_opacity
              << ",\"currentAlphaLocked\":" << json_bool(view.value().current_alpha_locked)
              << ",\"currentBlendMode\":" << view.value().current_blend_mode
              << ",\"visibleLayers\":" << visible_count
              << ",\"lockedLayers\":" << locked_count
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_layer_merge_args(
    int argc,
    char** argv,
    PlanLayerMergeArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--layer-count" || key == "--from-index" || key == "--to-index"
            || key == "--animation-duration") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--layer-count") {
                args.layer_count = value.value();
            } else if (key == "--from-index") {
                args.from_index = value.value();
            } else if (key == "--to-index") {
                args.to_index = value.value();
            } else {
                args.animation_duration = value.value();
            }
        } else if (key == "--no-history") {
            args.create_history = false;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_layer_merge(int argc, char** argv)
{
    PlanLayerMergeArgs args;
    const auto status = parse_plan_layer_merge_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-layer-merge", status.message);
        return 2;
    }

    const auto plan = pp::app::plan_document_layer_merge(
        args.layer_count,
        args.from_index,
        args.to_index,
        args.animation_duration,
        args.create_history);
    if (!plan) {
        print_error("plan-layer-merge", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-layer-merge\""
              << ",\"state\":{\"layerCount\":" << args.layer_count
              << ",\"fromIndex\":" << args.from_index
              << ",\"toIndex\":" << args.to_index
              << ",\"animationDuration\":" << args.animation_duration
              << ",\"createHistory\":" << json_bool(args.create_history)
              << "},\"plan\":{\"fromIndex\":" << value.from_index
              << ",\"toIndex\":" << value.to_index
              << ",\"createHistory\":" << json_bool(value.create_history)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_layer_operation_args(
    int argc,
    char** argv,
    PlanLayerOperationArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind" || key == "--name") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            if (key == "--kind") {
                args.kind = argv[++i];
            } else {
                args.name = argv[++i];
            }
        } else if (key == "--layer-count" || key == "--index" || key == "--from-index"
            || key == "--to-index" || key == "--source-index" || key == "--blend-mode") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--layer-count") {
                args.layer_count = static_cast<int>(value.value());
            } else if (key == "--index") {
                args.index = static_cast<int>(value.value());
            } else if (key == "--from-index") {
                args.from_index = static_cast<int>(value.value());
            } else if (key == "--to-index") {
                args.to_index = static_cast<int>(value.value());
            } else if (key == "--source-index") {
                args.source_index = static_cast<int>(value.value());
            } else {
                args.blend_mode = static_cast<int>(value.value());
            }
        } else if (key == "--opacity") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.opacity = value.value();
        } else if (key == "--enabled") {
            args.flag = true;
        } else if (key == "--disabled") {
            args.flag = false;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

pp::foundation::Result<pp::app::DocumentLayerOperationPlan> make_layer_operation_plan(
    const PlanLayerOperationArgs& args)
{
    if (args.kind == "add") {
        return pp::app::plan_document_layer_add(args.layer_count, args.index, args.name);
    }
    if (args.kind == "duplicate") {
        return pp::app::plan_document_layer_duplicate(args.layer_count, args.source_index);
    }
    if (args.kind == "select") {
        return pp::app::plan_document_layer_select(args.layer_count, args.index);
    }
    if (args.kind == "reorder") {
        return pp::app::plan_document_layer_reorder(args.layer_count, args.from_index, args.to_index);
    }
    if (args.kind == "remove") {
        return pp::app::plan_document_layer_remove(args.layer_count, args.index);
    }
    if (args.kind == "opacity") {
        return pp::app::plan_document_layer_opacity(args.layer_count, args.index, args.opacity);
    }
    if (args.kind == "visibility") {
        return pp::app::plan_document_layer_visibility(args.layer_count, args.index, args.flag);
    }
    if (args.kind == "alpha-lock") {
        return pp::app::plan_document_layer_alpha_lock(args.layer_count, args.index, args.flag);
    }
    if (args.kind == "blend-mode") {
        return pp::app::plan_document_layer_blend_mode(args.layer_count, args.index, args.blend_mode);
    }
    if (args.kind == "highlight") {
        return pp::app::plan_document_layer_highlight(args.layer_count, args.index, args.flag);
    }

    return pp::foundation::Result<pp::app::DocumentLayerOperationPlan>::failure(
        pp::foundation::Status::invalid_argument("unknown layer operation kind"));
}

int plan_layer_operation(int argc, char** argv)
{
    PlanLayerOperationArgs args;
    const auto status = parse_plan_layer_operation_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-layer-operation", status.message);
        return 2;
    }

    const auto plan = make_layer_operation_plan(args);
    if (!plan) {
        print_error("plan-layer-operation", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-layer-operation\""
              << ",\"state\":{\"kind\":\"" << json_escape(args.kind)
              << "\",\"layerCount\":" << args.layer_count
              << ",\"index\":" << args.index
              << ",\"fromIndex\":" << args.from_index
              << ",\"toIndex\":" << args.to_index
              << ",\"sourceIndex\":" << args.source_index
              << ",\"name\":\"" << json_escape(args.name)
              << "\",\"opacity\":" << args.opacity
              << ",\"flag\":" << json_bool(args.flag)
              << ",\"blendMode\":" << args.blend_mode
              << "},\"plan\":{\"operation\":\"" << document_layer_operation_name(value.operation)
              << "\",\"index\":" << value.index
              << ",\"fromIndex\":" << value.from_index
              << ",\"toIndex\":" << value.to_index
              << ",\"insertIndex\":" << value.insert_index
              << ",\"sourceIndex\":" << value.source_index
              << ",\"name\":\"" << json_escape(value.name)
              << "\",\"opacity\":" << value.opacity
              << ",\"flag\":" << json_bool(value.flag)
              << ",\"blendMode\":" << value.blend_mode
              << ",\"mutatesDocument\":" << json_bool(value.mutates_document)
              << ",\"marksUnsaved\":" << json_bool(value.marks_unsaved)
              << ",\"reloadsAnimationLayers\":" << json_bool(value.reloads_animation_layers)
              << ",\"updatesTitle\":" << json_bool(value.updates_title)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_animation_operation_args(
    int argc,
    char** argv,
    PlanAnimationOperationArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.kind = argv[++i];
        } else if (key == "--playing") {
            args.playback_active = true;
        } else if (key == "--frame-count" || key == "--total-duration" || key == "--current-frame"
            || key == "--selected-frame" || key == "--current-duration" || key == "--delta"
            || key == "--offset" || key == "--onion-size" || key == "--layer-index"
            || key == "--layer-id") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--frame-count") {
                args.frame_count = value.value();
            } else if (key == "--total-duration") {
                args.total_duration = value.value();
            } else if (key == "--current-frame") {
                args.current_frame = value.value();
            } else if (key == "--selected-frame") {
                args.selected_frame = value.value();
            } else if (key == "--current-duration") {
                args.current_duration = value.value();
            } else if (key == "--delta") {
                args.delta = value.value();
            } else if (key == "--offset") {
                args.offset = value.value();
            } else if (key == "--onion-size") {
                args.onion_size = value.value();
            } else if (key == "--layer-index") {
                args.layer_index = value.value();
            } else {
                if (value.value() < 0) {
                    return pp::foundation::Status::out_of_range("animation layer id must not be negative");
                }
                args.layer_id = static_cast<std::uint32_t>(value.value());
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

pp::foundation::Result<pp::app::DocumentAnimationOperationPlan> make_animation_operation_plan(
    const PlanAnimationOperationArgs& args)
{
    if (args.kind == "add") {
        return pp::app::plan_animation_add_frame(args.frame_count, args.current_frame);
    }
    if (args.kind == "duplicate") {
        return pp::app::plan_animation_duplicate_frame(args.frame_count, args.selected_frame);
    }
    if (args.kind == "remove") {
        return pp::app::plan_animation_remove_frame(args.frame_count, args.selected_frame);
    }
    if (args.kind == "duration") {
        return pp::app::plan_animation_adjust_duration(
            args.frame_count,
            args.selected_frame,
            args.current_duration,
            args.delta);
    }
    if (args.kind == "move") {
        return pp::app::plan_animation_move_frame(args.frame_count, args.selected_frame, args.offset);
    }
    if (args.kind == "select") {
        return pp::app::plan_animation_select_frame(
            args.frame_count,
            args.layer_index,
            args.layer_id,
            args.selected_frame);
    }
    if (args.kind == "goto") {
        return pp::app::plan_animation_goto_frame(args.total_duration, args.current_frame);
    }
    if (args.kind == "next") {
        return pp::app::plan_animation_step_frame(args.total_duration, args.current_frame, 1);
    }
    if (args.kind == "prev") {
        return pp::app::plan_animation_step_frame(args.total_duration, args.current_frame, -1);
    }
    if (args.kind == "playback") {
        return pp::app::plan_animation_playback_step(args.total_duration, args.current_frame, args.offset);
    }
    if (args.kind == "toggle-playback" || args.kind == "play-toggle") {
        return pp::app::plan_animation_playback_toggle(args.playback_active);
    }
    if (args.kind == "onion") {
        return pp::app::plan_animation_onion_size(args.onion_size);
    }

    return pp::foundation::Result<pp::app::DocumentAnimationOperationPlan>::failure(
        pp::foundation::Status::invalid_argument("unknown animation operation kind"));
}

int plan_animation_operation(int argc, char** argv)
{
    PlanAnimationOperationArgs args;
    const auto status = parse_plan_animation_operation_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-animation-operation", status.message);
        return 2;
    }

    const auto plan = make_animation_operation_plan(args);
    if (!plan) {
        print_error("plan-animation-operation", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-animation-operation\""
              << ",\"state\":{\"kind\":\"" << json_escape(args.kind)
              << "\",\"frameCount\":" << args.frame_count
              << ",\"totalDuration\":" << args.total_duration
              << ",\"currentFrame\":" << args.current_frame
              << ",\"selectedFrame\":" << args.selected_frame
              << ",\"layerIndex\":" << args.layer_index
              << ",\"layerId\":" << args.layer_id
              << ",\"currentDuration\":" << args.current_duration
              << ",\"delta\":" << args.delta
              << ",\"offset\":" << args.offset
              << ",\"onionSize\":" << args.onion_size
              << ",\"playbackActive\":" << json_bool(args.playback_active)
              << "},\"plan\":{\"operation\":\"" << document_animation_operation_name(value.operation)
              << "\",\"frameCount\":" << value.frame_count
              << ",\"currentFrame\":" << value.current_frame
              << ",\"selectedFrame\":" << value.selected_frame
              << ",\"targetFrame\":" << value.target_frame
              << ",\"layerIndex\":" << value.layer_index
              << ",\"layerId\":" << value.layer_id
              << ",\"frameDuration\":" << value.frame_duration
              << ",\"durationDelta\":" << value.duration_delta
              << ",\"moveOffset\":" << value.move_offset
              << ",\"onionSize\":" << value.onion_size
              << ",\"playbackIdleMs\":" << value.playback_idle_ms
              << ",\"requiresSelectedFrame\":" << json_bool(value.requires_selected_frame)
              << ",\"mutatesDocument\":" << json_bool(value.mutates_document)
              << ",\"reloadsAnimationLayers\":" << json_bool(value.reloads_animation_layers)
              << ",\"updatesCanvasAnimation\":" << json_bool(value.updates_canvas_animation)
              << ",\"marksUnsaved\":" << json_bool(value.marks_unsaved)
              << ",\"playbackWasActive\":" << json_bool(value.playback_was_active)
              << ",\"playbackActive\":" << json_bool(value.playback_active)
              << ",\"resetsPlaybackTimer\":" << json_bool(value.resets_playback_timer)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_animation_panel_action_args(
    int argc,
    char** argv,
    PlanAnimationPanelActionArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--action") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.action = argv[++i];
        } else if (key == "--playing") {
            args.playback_active = true;
        } else if (key == "--total-duration" || key == "--current-frame" || key == "--target-frame") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--total-duration") {
                args.total_duration = value.value();
            } else if (key == "--current-frame") {
                args.current_frame = value.value();
            } else {
                args.target_frame = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_animation_panel_action(int argc, char** argv)
{
    PlanAnimationPanelActionArgs args;
    const auto status = parse_plan_animation_panel_action_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-animation-panel-action", status.message);
        return 2;
    }

    const auto action = parse_document_animation_panel_action(args.action);
    if (!action) {
        print_error("plan-animation-panel-action", action.status().message);
        return 2;
    }

    const pp::app::DocumentAnimationPanelState state {
        .total_duration = args.total_duration,
        .current_frame = args.current_frame,
        .playback_active = args.playback_active,
    };
    const auto plan = pp::app::plan_animation_panel_action(action.value(), state, args.target_frame);
    if (!plan) {
        print_error("plan-animation-panel-action", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-animation-panel-action\""
              << ",\"state\":{\"action\":\"" << json_escape(args.action)
              << "\",\"totalDuration\":" << args.total_duration
              << ",\"currentFrame\":" << args.current_frame
              << ",\"targetFrame\":" << args.target_frame
              << ",\"playbackActive\":" << json_bool(args.playback_active)
              << "},\"plan\":{\"action\":\"" << document_animation_panel_action_name(action.value())
              << "\",\"operation\":\"" << document_animation_operation_name(value.operation)
              << "\",\"frameCount\":" << value.frame_count
              << ",\"currentFrame\":" << value.current_frame
              << ",\"selectedFrame\":" << value.selected_frame
              << ",\"targetFrame\":" << value.target_frame
              << ",\"layerIndex\":" << value.layer_index
              << ",\"layerId\":" << value.layer_id
              << ",\"frameDuration\":" << value.frame_duration
              << ",\"durationDelta\":" << value.duration_delta
              << ",\"moveOffset\":" << value.move_offset
              << ",\"onionSize\":" << value.onion_size
              << ",\"playbackIdleMs\":" << value.playback_idle_ms
              << ",\"requiresSelectedFrame\":" << json_bool(value.requires_selected_frame)
              << ",\"mutatesDocument\":" << json_bool(value.mutates_document)
              << ",\"reloadsAnimationLayers\":" << json_bool(value.reloads_animation_layers)
              << ",\"updatesCanvasAnimation\":" << json_bool(value.updates_canvas_animation)
              << ",\"marksUnsaved\":" << json_bool(value.marks_unsaved)
              << ",\"playbackWasActive\":" << json_bool(value.playback_was_active)
              << ",\"playbackActive\":" << json_bool(value.playback_active)
              << ",\"resetsPlaybackTimer\":" << json_bool(value.resets_playback_timer)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_animation_panel_view_args(
    int argc,
    char** argv,
    PlanAnimationPanelViewArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--layer-count" || key == "--frame-count" || key == "--frame-duration"
            || key == "--total-duration" || key == "--current-layer" || key == "--current-frame"
            || key == "--selected-layer-id" || key == "--selected-frame" || key == "--onion-size"
            || key == "--hidden-layer") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--layer-count") {
                args.layer_count = value.value();
            } else if (key == "--frame-count") {
                args.frame_count = value.value();
            } else if (key == "--frame-duration") {
                args.frame_duration = value.value();
            } else if (key == "--total-duration") {
                args.total_duration = value.value();
            } else if (key == "--current-layer") {
                args.current_layer = value.value();
            } else if (key == "--current-frame") {
                args.current_frame = value.value();
            } else if (key == "--selected-layer-id") {
                if (value.value() < 0) {
                    return pp::foundation::Status::out_of_range("selected animation layer id must not be negative");
                }
                args.selected_layer_id = static_cast<std::uint32_t>(value.value());
            } else if (key == "--selected-frame") {
                args.selected_frame = value.value();
            } else if (key == "--onion-size") {
                args.onion_size = value.value();
            } else {
                args.hidden_layer = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_animation_panel_view(int argc, char** argv)
{
    PlanAnimationPanelViewArgs args;
    const auto status = parse_plan_animation_panel_view_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-animation-panel-view", status.message);
        return 2;
    }

    std::vector<pp::app::DocumentAnimationLayerInput> layers;
    if (args.layer_count > 0) {
        layers.reserve(static_cast<std::size_t>(args.layer_count));
    }
    for (int i = 0; i < args.layer_count; ++i) {
        pp::app::DocumentAnimationLayerInput layer;
        layer.layer_index = i;
        layer.layer_id = static_cast<std::uint32_t>((i + 1) * 10);
        layer.name = "Layer " + std::to_string(i);
        layer.visible = i != args.hidden_layer;
        if (args.frame_count > 0) {
            layer.frame_durations.assign(static_cast<std::size_t>(args.frame_count), args.frame_duration);
        }
        layers.push_back(std::move(layer));
    }

    const auto view = pp::app::plan_animation_panel_view(
        layers,
        args.total_duration,
        args.current_layer,
        args.current_frame,
        args.selected_layer_id,
        args.selected_frame,
        args.onion_size);
    if (!view) {
        print_error("plan-animation-panel-view", view.status().message);
        return 2;
    }

    const auto& value = view.value();
    int selected_count = 0;
    int visible_count = 0;
    for (const auto& layer : value.layers) {
        if (layer.visible) {
            visible_count += 1;
        }
        for (const auto& frame : layer.frames) {
            if (frame.selected) {
                selected_count += 1;
            }
        }
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-animation-panel-view\""
              << ",\"state\":{\"layerCount\":" << args.layer_count
              << ",\"frameCount\":" << args.frame_count
              << ",\"frameDuration\":" << args.frame_duration
              << ",\"totalDuration\":" << args.total_duration
              << ",\"currentLayer\":" << args.current_layer
              << ",\"currentFrame\":" << args.current_frame
              << ",\"selectedLayerId\":" << args.selected_layer_id
              << ",\"selectedFrame\":" << args.selected_frame
              << ",\"onionSize\":" << args.onion_size
              << ",\"hiddenLayer\":" << args.hidden_layer
              << "},\"view\":{\"totalDuration\":" << value.total_duration
              << ",\"currentFrame\":" << value.current_frame
              << ",\"onionSize\":" << value.onion_size
              << ",\"layers\":" << value.layers.size()
              << ",\"visibleLayers\":" << visible_count
              << ",\"selectedFrames\":" << selected_count
              << ",\"hasSelectedFrame\":" << json_bool(value.has_selected_frame)
              << ",\"currentLayerId\":" << value.layers[static_cast<std::size_t>(args.current_layer)].layer_id
              << ",\"firstLayerName\":\"" << json_escape(value.layers.front().name)
              << "\",\"firstLayerFrames\":" << value.layers.front().frames.size()
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_animation_timeline_scrub_args(
    int argc,
    char** argv,
    PlanAnimationTimelineScrubArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--total-duration") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.total_duration = value.value();
        } else if (key == "--cursor-x" || key == "--frame-width") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--cursor-x") {
                args.cursor_x = value.value();
            } else {
                args.frame_width = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_animation_timeline_scrub(int argc, char** argv)
{
    PlanAnimationTimelineScrubArgs args;
    const auto status = parse_plan_animation_timeline_scrub_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-animation-timeline-scrub", status.message);
        return 2;
    }

    const auto plan = pp::app::plan_animation_timeline_scrub(
        args.total_duration,
        args.cursor_x,
        args.frame_width);
    if (!plan) {
        print_error("plan-animation-timeline-scrub", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-animation-timeline-scrub\""
              << ",\"state\":{\"totalDuration\":" << args.total_duration
              << ",\"cursorX\":" << args.cursor_x
              << ",\"frameWidth\":" << args.frame_width
              << "},\"plan\":{\"totalDuration\":" << value.total_duration
              << ",\"cursorX\":" << value.cursor_x
              << ",\"frameWidth\":" << value.frame_width
              << ",\"targetFrame\":" << value.target_frame
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_brush_operation_args(
    int argc,
    char** argv,
    PlanBrushOperationArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind" || key == "--path" || key == "--thumb") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            if (key == "--kind") {
                args.kind = argv[++i];
            } else if (key == "--path") {
                args.path = argv[++i];
            } else {
                args.thumbnail_path = argv[++i];
            }
        } else if (key == "--r" || key == "--g" || key == "--b" || key == "--a") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--r") {
                args.r = value.value();
            } else if (key == "--g") {
                args.g = value.value();
            } else if (key == "--b") {
                args.b = value.value();
            } else {
                args.a = value.value();
            }
        } else if (key == "--no-brush") {
            args.has_brush = false;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

pp::foundation::Result<pp::app::BrushUiPlan> make_brush_operation_plan(
    const PlanBrushOperationArgs& args)
{
    if (args.kind == "color") {
        return pp::app::plan_brush_ui_color(args.r, args.g, args.b, args.a);
    }
    if (args.kind == "tip") {
        return pp::app::plan_brush_ui_texture(
            pp::app::BrushUiTextureSlot::tip,
            args.path,
            args.thumbnail_path);
    }
    if (args.kind == "pattern") {
        return pp::app::plan_brush_ui_texture(
            pp::app::BrushUiTextureSlot::pattern,
            args.path,
            args.thumbnail_path);
    }
    if (args.kind == "dual") {
        return pp::app::plan_brush_ui_texture(
            pp::app::BrushUiTextureSlot::dual,
            args.path,
            args.thumbnail_path);
    }
    if (args.kind == "preset") {
        return pp::app::plan_brush_ui_preset_replace(args.has_brush);
    }
    if (args.kind == "settings") {
        return pp::foundation::Result<pp::app::BrushUiPlan>::success(
            pp::app::plan_brush_ui_stroke_settings_changed());
    }

    return pp::foundation::Result<pp::app::BrushUiPlan>::failure(
        pp::foundation::Status::invalid_argument("unknown brush operation kind"));
}

int plan_brush_operation(int argc, char** argv)
{
    PlanBrushOperationArgs args;
    const auto status = parse_plan_brush_operation_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-brush-operation", status.message);
        return 2;
    }

    const auto plan = make_brush_operation_plan(args);
    if (!plan) {
        print_error("plan-brush-operation", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-brush-operation\""
              << ",\"state\":{\"kind\":\"" << json_escape(args.kind)
              << "\",\"path\":\"" << json_escape(args.path)
              << "\",\"thumb\":\"" << json_escape(args.thumbnail_path)
              << "\",\"r\":" << args.r
              << ",\"g\":" << args.g
              << ",\"b\":" << args.b
              << ",\"a\":" << args.a
              << ",\"hasBrush\":" << json_bool(args.has_brush)
              << "},\"plan\":{\"operation\":\"" << brush_ui_operation_name(value.operation)
              << "\",\"textureSlot\":\"" << brush_ui_texture_slot_name(value.texture_slot)
              << "\",\"path\":\"" << json_escape(value.path)
              << "\",\"thumb\":\"" << json_escape(value.thumbnail_path)
              << "\",\"r\":" << value.r
              << ",\"g\":" << value.g
              << ",\"b\":" << value.b
              << ",\"a\":" << value.a
              << ",\"mutatesBrush\":" << json_bool(value.mutates_brush)
              << ",\"preservesExistingColor\":" << json_bool(value.preserves_existing_color)
              << ",\"loadsBrushResources\":" << json_bool(value.loads_brush_resources)
              << ",\"updateColorUi\":" << json_bool(value.update_color_ui)
              << ",\"updateBrushUi\":" << json_bool(value.update_brush_ui)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_brush_refresh_args(
    int argc,
    char** argv,
    PlanBrushRefreshArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--tip-flow" || key == "--tip-size" || key == "--r" || key == "--g" || key == "--b" || key == "--a") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--tip-flow") {
                args.tip_flow = value.value();
            } else if (key == "--tip-size") {
                args.tip_size = value.value();
            } else if (key == "--r") {
                args.r = value.value();
            } else if (key == "--g") {
                args.g = value.value();
            } else if (key == "--b") {
                args.b = value.value();
            } else {
                args.a = value.value();
            }
        } else if (key == "--color") {
            args.update_color = true;
        } else if (key == "--no-color") {
            args.update_color = false;
        } else if (key == "--brush") {
            args.update_brush = true;
        } else if (key == "--no-brush-update") {
            args.update_brush = false;
        } else if (key == "--no-brush") {
            args.has_brush = false;
        } else if (key == "--floating-picker") {
            args.floating_picker = true;
        } else if (key == "--floating-color") {
            args.floating_color = true;
        } else if (key == "--bad-float") {
            args.bad_float = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_brush_refresh(int argc, char** argv)
{
    PlanBrushRefreshArgs args;
    const auto status = parse_plan_brush_refresh_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-brush-refresh", status.message);
        return 2;
    }

    const auto view = pp::app::plan_brush_ui_refresh(pp::app::BrushUiRefreshInput {
        .update_color = args.update_color,
        .update_brush = args.update_brush,
        .has_current_brush = args.has_brush,
        .has_floating_picker = args.floating_picker,
        .has_floating_color_panel = args.floating_color,
        .tip_flow = args.bad_float ? std::nanf("") : args.tip_flow,
        .tip_size = args.tip_size,
        .r = args.r,
        .g = args.g,
        .b = args.b,
        .a = args.a,
    });
    if (!view) {
        print_error("plan-brush-refresh", view.status().message);
        return 2;
    }

    const auto& value = view.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-brush-refresh\""
              << ",\"state\":{\"updateColor\":" << json_bool(args.update_color)
              << ",\"updateBrush\":" << json_bool(args.update_brush)
              << ",\"hasBrush\":" << json_bool(args.has_brush)
              << ",\"floatingPicker\":" << json_bool(args.floating_picker)
              << ",\"floatingColor\":" << json_bool(args.floating_color)
              << ",\"tipFlow\":" << args.tip_flow
              << ",\"tipSize\":" << args.tip_size
              << ",\"r\":" << args.r
              << ",\"g\":" << args.g
              << ",\"b\":" << args.b
              << ",\"a\":" << args.a
              << "},\"view\":{\"updatesStrokeControls\":" << json_bool(value.updates_stroke_controls)
              << ",\"updatesQuickFlow\":" << json_bool(value.updates_quick_flow)
              << ",\"updatesQuickSize\":" << json_bool(value.updates_quick_size)
              << ",\"updatesQuickBrushPreview\":" << json_bool(value.updates_quick_brush_preview)
              << ",\"updatesQuickColor\":" << json_bool(value.updates_quick_color)
              << ",\"updatesFloatingPicker\":" << json_bool(value.updates_floating_picker)
              << ",\"updatesFloatingColorPanel\":" << json_bool(value.updates_floating_color_panel)
              << ",\"noOp\":" << json_bool(value.no_op)
              << ",\"tipFlow\":" << value.tip_flow
              << ",\"tipSize\":" << value.tip_size
              << ",\"r\":" << value.r
              << ",\"g\":" << value.g
              << ",\"b\":" << value.b
              << ",\"a\":" << value.a
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_brush_texture_list_args(
    int argc,
    char** argv,
    PlanBrushTextureListArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind" || key == "--dir" || key == "--data-path" || key == "--source") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            if (key == "--kind") {
                args.kind = argv[++i];
            } else if (key == "--dir") {
                args.directory_name = argv[++i];
            } else if (key == "--data-path") {
                args.data_path = argv[++i];
            } else {
                args.source_path = argv[++i];
            }
        } else if (key == "--item-count" || key == "--current-index" || key == "--offset") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--item-count") {
                args.item_count = value.value();
            } else if (key == "--current-index") {
                args.current_index = value.value();
            } else {
                args.offset = value.value();
            }
        } else if (key == "--user-texture") {
            args.current_is_user_texture = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

pp::foundation::Result<pp::app::BrushTextureListPlan> make_brush_texture_list_plan(
    const PlanBrushTextureListArgs& args)
{
    if (args.kind == "add") {
        return pp::app::plan_brush_texture_list_add(args.directory_name, args.data_path, args.source_path);
    }
    if (args.kind == "remove") {
        return pp::app::plan_brush_texture_list_remove(
            args.item_count,
            args.current_index,
            args.current_is_user_texture);
    }
    if (args.kind == "move" || args.kind == "up" || args.kind == "down") {
        const int offset = args.kind == "up" ? -1 : (args.kind == "down" ? 1 : args.offset);
        return pp::app::plan_brush_texture_list_move(args.item_count, args.current_index, offset);
    }

    return pp::foundation::Result<pp::app::BrushTextureListPlan>::failure(
        pp::foundation::Status::invalid_argument("unknown brush texture list operation kind"));
}

int plan_brush_texture_list(int argc, char** argv)
{
    PlanBrushTextureListArgs args;
    const auto status = parse_plan_brush_texture_list_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-brush-texture-list", status.message);
        return 2;
    }

    const auto plan = make_brush_texture_list_plan(args);
    if (!plan) {
        print_error("plan-brush-texture-list", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-brush-texture-list\""
              << ",\"state\":{\"kind\":\"" << json_escape(args.kind)
              << "\",\"dir\":\"" << json_escape(args.directory_name)
              << "\",\"dataPath\":\"" << json_escape(args.data_path)
              << "\",\"source\":\"" << json_escape(args.source_path)
              << "\",\"itemCount\":" << args.item_count
              << ",\"currentIndex\":" << args.current_index
              << ",\"offset\":" << args.offset
              << ",\"currentIsUserTexture\":" << json_bool(args.current_is_user_texture)
              << "},\"plan\":{\"operation\":\"" << brush_texture_list_operation_name(value.operation)
              << "\",\"itemCount\":" << value.item_count
              << ",\"currentIndex\":" << value.current_index
              << ",\"targetIndex\":" << value.target_index
              << ",\"moveOffset\":" << value.move_offset
              << ",\"source\":\"" << json_escape(value.source_path)
              << "\",\"path\":\"" << json_escape(value.high_path)
              << "\",\"thumb\":\"" << json_escape(value.thumbnail_path)
              << "\",\"brushName\":\"" << json_escape(value.brush_name)
              << "\",\"userTexture\":" << json_bool(value.user_texture)
              << ",\"deletesTextureFiles\":" << json_bool(value.deletes_texture_files)
              << ",\"savesList\":" << json_bool(value.saves_list)
              << ",\"notifiesSelection\":" << json_bool(value.notifies_selection)
              << ",\"convertsBrushAlpha\":" << json_bool(value.converts_brush_alpha)
              << ",\"noOp\":" << json_bool(value.no_op)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_brush_preset_list_args(
    int argc,
    char** argv,
    PlanBrushPresetListArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.kind = argv[++i];
        } else if (key == "--item-count" || key == "--current-index" || key == "--offset") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--item-count") {
                args.item_count = value.value();
            } else if (key == "--current-index") {
                args.current_index = value.value();
            } else {
                args.offset = value.value();
            }
        } else if (key == "--no-current-brush") {
            args.has_current_brush = false;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

pp::foundation::Result<pp::app::BrushPresetListPlan> make_brush_preset_list_plan(
    const PlanBrushPresetListArgs& args)
{
    if (args.kind == "add") {
        return pp::app::plan_brush_preset_list_add(args.item_count, args.has_current_brush);
    }
    if (args.kind == "remove") {
        return pp::app::plan_brush_preset_list_remove(args.item_count, args.current_index);
    }
    if (args.kind == "move" || args.kind == "up" || args.kind == "down") {
        const int offset = args.kind == "up" ? -1 : (args.kind == "down" ? 1 : args.offset);
        return pp::app::plan_brush_preset_list_move(args.item_count, args.current_index, offset);
    }
    if (args.kind == "select") {
        return pp::app::plan_brush_preset_list_select(args.item_count, args.current_index);
    }
    if (args.kind == "clear") {
        return pp::app::plan_brush_preset_list_clear(args.item_count);
    }

    return pp::foundation::Result<pp::app::BrushPresetListPlan>::failure(
        pp::foundation::Status::invalid_argument("unknown brush preset list operation kind"));
}

int plan_brush_preset_list(int argc, char** argv)
{
    PlanBrushPresetListArgs args;
    const auto status = parse_plan_brush_preset_list_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-brush-preset-list", status.message);
        return 2;
    }

    const auto plan = make_brush_preset_list_plan(args);
    if (!plan) {
        print_error("plan-brush-preset-list", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-brush-preset-list\""
              << ",\"state\":{\"kind\":\"" << json_escape(args.kind)
              << "\",\"itemCount\":" << args.item_count
              << ",\"currentIndex\":" << args.current_index
              << ",\"offset\":" << args.offset
              << ",\"hasCurrentBrush\":" << json_bool(args.has_current_brush)
              << "},\"plan\":{\"operation\":\"" << brush_preset_list_operation_name(value.operation)
              << "\",\"itemCount\":" << value.item_count
              << ",\"currentIndex\":" << value.current_index
              << ",\"targetIndex\":" << value.target_index
              << ",\"moveOffset\":" << value.move_offset
              << ",\"savesList\":" << json_bool(value.saves_list)
              << ",\"updatesEmptyNotification\":" << json_bool(value.updates_empty_notification)
              << ",\"selectsTarget\":" << json_bool(value.selects_target)
              << ",\"clearsSelection\":" << json_bool(value.clears_selection)
              << ",\"notifiesBrushChanged\":" << json_bool(value.notifies_brush_changed)
              << ",\"noOp\":" << json_bool(value.no_op)
              << "}}\n";
    return 0;
}

pp::foundation::Result<pp::app::BrushStrokeFloatSetting> parse_brush_stroke_float_setting(
    std::string_view setting)
{
    static constexpr std::array<std::pair<std::string_view, pp::app::BrushStrokeFloatSetting>, 32> settings{ {
        { "tip-size", pp::app::BrushStrokeFloatSetting::tip_size },
        { "tip-spacing", pp::app::BrushStrokeFloatSetting::tip_spacing },
        { "tip-flow", pp::app::BrushStrokeFloatSetting::tip_flow },
        { "tip-opacity", pp::app::BrushStrokeFloatSetting::tip_opacity },
        { "tip-angle", pp::app::BrushStrokeFloatSetting::tip_angle },
        { "tip-angle-smooth", pp::app::BrushStrokeFloatSetting::tip_angle_smooth },
        { "tip-mix", pp::app::BrushStrokeFloatSetting::tip_mix },
        { "tip-wet", pp::app::BrushStrokeFloatSetting::tip_wet },
        { "tip-noise", pp::app::BrushStrokeFloatSetting::tip_noise },
        { "tip-hue", pp::app::BrushStrokeFloatSetting::tip_hue },
        { "tip-saturation", pp::app::BrushStrokeFloatSetting::tip_saturation },
        { "tip-sat", pp::app::BrushStrokeFloatSetting::tip_saturation },
        { "tip-value", pp::app::BrushStrokeFloatSetting::tip_value },
        { "tip-val", pp::app::BrushStrokeFloatSetting::tip_value },
        { "jitter-scale", pp::app::BrushStrokeFloatSetting::jitter_scale },
        { "jitter-angle", pp::app::BrushStrokeFloatSetting::jitter_angle },
        { "jitter-scatter", pp::app::BrushStrokeFloatSetting::jitter_scatter },
        { "jitter-flow", pp::app::BrushStrokeFloatSetting::jitter_flow },
        { "jitter-opacity", pp::app::BrushStrokeFloatSetting::jitter_opacity },
        { "jitter-hue", pp::app::BrushStrokeFloatSetting::jitter_hue },
        { "jitter-saturation", pp::app::BrushStrokeFloatSetting::jitter_saturation },
        { "jitter-sat", pp::app::BrushStrokeFloatSetting::jitter_saturation },
        { "jitter-value", pp::app::BrushStrokeFloatSetting::jitter_value },
        { "jitter-val", pp::app::BrushStrokeFloatSetting::jitter_value },
        { "jitter-aspect", pp::app::BrushStrokeFloatSetting::jitter_aspect },
        { "dual-size", pp::app::BrushStrokeFloatSetting::dual_size },
        { "dual-spacing", pp::app::BrushStrokeFloatSetting::dual_spacing },
        { "dual-scatter", pp::app::BrushStrokeFloatSetting::dual_scatter },
        { "tip-aspect", pp::app::BrushStrokeFloatSetting::tip_aspect },
        { "dual-opacity", pp::app::BrushStrokeFloatSetting::dual_opacity },
        { "dual-flow", pp::app::BrushStrokeFloatSetting::dual_flow },
        { "dual-rotate", pp::app::BrushStrokeFloatSetting::dual_rotate },
    } };
    for (const auto& entry : settings) {
        if (setting == entry.first) {
            return pp::foundation::Result<pp::app::BrushStrokeFloatSetting>::success(entry.second);
        }
    }
    if (setting == "pattern-scale") {
        return pp::foundation::Result<pp::app::BrushStrokeFloatSetting>::success(
            pp::app::BrushStrokeFloatSetting::pattern_scale);
    }
    if (setting == "pattern-brightness") {
        return pp::foundation::Result<pp::app::BrushStrokeFloatSetting>::success(
            pp::app::BrushStrokeFloatSetting::pattern_brightness);
    }
    if (setting == "pattern-contrast") {
        return pp::foundation::Result<pp::app::BrushStrokeFloatSetting>::success(
            pp::app::BrushStrokeFloatSetting::pattern_contrast);
    }
    if (setting == "pattern-depth") {
        return pp::foundation::Result<pp::app::BrushStrokeFloatSetting>::success(
            pp::app::BrushStrokeFloatSetting::pattern_depth);
    }

    return pp::foundation::Result<pp::app::BrushStrokeFloatSetting>::failure(
        pp::foundation::Status::invalid_argument("unknown brush stroke float setting"));
}

pp::foundation::Result<pp::app::BrushStrokeBoolSetting> parse_brush_stroke_bool_setting(
    std::string_view setting)
{
    static constexpr std::array<std::pair<std::string_view, pp::app::BrushStrokeBoolSetting>, 25> settings{ {
        { "tip-angle-init", pp::app::BrushStrokeBoolSetting::tip_angle_init },
        { "tip-angle-follow", pp::app::BrushStrokeBoolSetting::tip_angle_follow },
        { "tip-flow-pressure", pp::app::BrushStrokeBoolSetting::tip_flow_pressure },
        { "tip-opacity-pressure", pp::app::BrushStrokeBoolSetting::tip_opacity_pressure },
        { "tip-size-pressure", pp::app::BrushStrokeBoolSetting::tip_size_pressure },
        { "jitter-scatter-both-axis", pp::app::BrushStrokeBoolSetting::jitter_scatter_both_axis },
        { "jitter-scatter-bothaxis", pp::app::BrushStrokeBoolSetting::jitter_scatter_both_axis },
        { "jitter-aspect-both-axis", pp::app::BrushStrokeBoolSetting::jitter_aspect_both_axis },
        { "jitter-aspect-bothaxis", pp::app::BrushStrokeBoolSetting::jitter_aspect_both_axis },
        { "jitter-hsv-each-sample", pp::app::BrushStrokeBoolSetting::jitter_hsv_each_sample },
        { "jitter-hsv-eachsample", pp::app::BrushStrokeBoolSetting::jitter_hsv_each_sample },
        { "tip-invert", pp::app::BrushStrokeBoolSetting::tip_invert },
        { "tip-flip-x", pp::app::BrushStrokeBoolSetting::tip_flip_x },
        { "tip-flipx", pp::app::BrushStrokeBoolSetting::tip_flip_x },
        { "tip-flip-y", pp::app::BrushStrokeBoolSetting::tip_flip_y },
        { "tip-flipy", pp::app::BrushStrokeBoolSetting::tip_flip_y },
        { "pattern-enabled", pp::app::BrushStrokeBoolSetting::pattern_enabled },
        { "dual-enabled", pp::app::BrushStrokeBoolSetting::dual_enabled },
        { "dual-scatter-both-axis", pp::app::BrushStrokeBoolSetting::dual_scatter_both_axis },
        { "dual-scatter-bothaxis", pp::app::BrushStrokeBoolSetting::dual_scatter_both_axis },
        { "dual-invert", pp::app::BrushStrokeBoolSetting::dual_invert },
        { "dual-flip-x", pp::app::BrushStrokeBoolSetting::dual_flip_x },
        { "dual-flipx", pp::app::BrushStrokeBoolSetting::dual_flip_x },
        { "dual-flip-y", pp::app::BrushStrokeBoolSetting::dual_flip_y },
        { "dual-flipy", pp::app::BrushStrokeBoolSetting::dual_flip_y },
    } };
    for (const auto& entry : settings) {
        if (setting == entry.first) {
            return pp::foundation::Result<pp::app::BrushStrokeBoolSetting>::success(entry.second);
        }
    }
    if (setting == "dual-random-flip" || setting == "dual-randflip") {
        return pp::foundation::Result<pp::app::BrushStrokeBoolSetting>::success(
            pp::app::BrushStrokeBoolSetting::dual_random_flip);
    }
    if (setting == "tip-random-flip-x" || setting == "tip-randflipx") {
        return pp::foundation::Result<pp::app::BrushStrokeBoolSetting>::success(
            pp::app::BrushStrokeBoolSetting::tip_random_flip_x);
    }
    if (setting == "tip-random-flip-y" || setting == "tip-randflipy") {
        return pp::foundation::Result<pp::app::BrushStrokeBoolSetting>::success(
            pp::app::BrushStrokeBoolSetting::tip_random_flip_y);
    }
    if (setting == "pattern-each-sample" || setting == "pattern-eachsample") {
        return pp::foundation::Result<pp::app::BrushStrokeBoolSetting>::success(
            pp::app::BrushStrokeBoolSetting::pattern_each_sample);
    }
    if (setting == "pattern-invert") {
        return pp::foundation::Result<pp::app::BrushStrokeBoolSetting>::success(
            pp::app::BrushStrokeBoolSetting::pattern_invert);
    }
    if (setting == "pattern-flip-x" || setting == "pattern-flipx") {
        return pp::foundation::Result<pp::app::BrushStrokeBoolSetting>::success(
            pp::app::BrushStrokeBoolSetting::pattern_flip_x);
    }
    if (setting == "pattern-flip-y" || setting == "pattern-flipy") {
        return pp::foundation::Result<pp::app::BrushStrokeBoolSetting>::success(
            pp::app::BrushStrokeBoolSetting::pattern_flip_y);
    }
    if (setting == "pattern-random-offset" || setting == "pattern-rand-offset") {
        return pp::foundation::Result<pp::app::BrushStrokeBoolSetting>::success(
            pp::app::BrushStrokeBoolSetting::pattern_random_offset);
    }

    return pp::foundation::Result<pp::app::BrushStrokeBoolSetting>::failure(
        pp::foundation::Status::invalid_argument("unknown brush stroke bool setting"));
}

pp::foundation::Result<pp::app::BrushStrokeBlendSetting> parse_brush_stroke_blend_setting(
    std::string_view setting)
{
    if (setting == "tip" || setting == "brush") {
        return pp::foundation::Result<pp::app::BrushStrokeBlendSetting>::success(
            pp::app::BrushStrokeBlendSetting::tip);
    }
    if (setting == "dual") {
        return pp::foundation::Result<pp::app::BrushStrokeBlendSetting>::success(
            pp::app::BrushStrokeBlendSetting::dual);
    }
    if (setting == "pattern") {
        return pp::foundation::Result<pp::app::BrushStrokeBlendSetting>::success(
            pp::app::BrushStrokeBlendSetting::pattern);
    }

    return pp::foundation::Result<pp::app::BrushStrokeBlendSetting>::failure(
        pp::foundation::Status::invalid_argument("unknown brush stroke blend setting"));
}

pp::foundation::Status parse_plan_brush_stroke_control_args(
    int argc,
    char** argv,
    PlanBrushStrokeControlArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind" || key == "--setting") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            if (key == "--kind") {
                args.kind = argv[++i];
            } else {
                args.setting = argv[++i];
            }
        } else if (key == "--value") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.value = value.value();
        } else if (key == "--blend-mode") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.blend_mode = value.value();
        } else if (key == "--enabled") {
            args.enabled = true;
        } else if (key == "--disabled") {
            args.enabled = false;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

pp::foundation::Result<pp::app::BrushStrokeControlPlan> make_brush_stroke_control_plan(
    const PlanBrushStrokeControlArgs& args)
{
    if (args.kind == "float" || args.kind == "slider") {
        const auto setting = parse_brush_stroke_float_setting(args.setting);
        if (!setting) {
            return pp::foundation::Result<pp::app::BrushStrokeControlPlan>::failure(setting.status());
        }
        return pp::app::plan_brush_stroke_float_setting(setting.value(), args.value);
    }
    if (args.kind == "bool" || args.kind == "toggle" || args.kind == "checkbox") {
        const auto setting = parse_brush_stroke_bool_setting(args.setting);
        if (!setting) {
            return pp::foundation::Result<pp::app::BrushStrokeControlPlan>::failure(setting.status());
        }
        return pp::foundation::Result<pp::app::BrushStrokeControlPlan>::success(
            pp::app::plan_brush_stroke_bool_setting(setting.value(), args.enabled));
    }
    if (args.kind == "blend" || args.kind == "blend-mode") {
        const auto setting = parse_brush_stroke_blend_setting(args.setting);
        if (!setting) {
            return pp::foundation::Result<pp::app::BrushStrokeControlPlan>::failure(setting.status());
        }
        return pp::app::plan_brush_stroke_blend_mode(setting.value(), args.blend_mode);
    }
    if (args.kind == "tip-aspect-reset") {
        return pp::foundation::Result<pp::app::BrushStrokeControlPlan>::success(
            pp::app::plan_brush_tip_aspect_reset());
    }
    if (args.kind == "default-reset" || args.kind == "reset") {
        return pp::foundation::Result<pp::app::BrushStrokeControlPlan>::success(
            pp::app::plan_brush_default_settings_reset());
    }

    return pp::foundation::Result<pp::app::BrushStrokeControlPlan>::failure(
        pp::foundation::Status::invalid_argument("unknown brush stroke control kind"));
}

int plan_brush_stroke_control(int argc, char** argv)
{
    PlanBrushStrokeControlArgs args;
    const auto status = parse_plan_brush_stroke_control_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-brush-stroke-control", status.message);
        return 2;
    }

    const auto plan = make_brush_stroke_control_plan(args);
    if (!plan) {
        print_error("plan-brush-stroke-control", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-brush-stroke-control\""
              << ",\"state\":{\"kind\":\"" << json_escape(args.kind)
              << "\",\"setting\":\"" << json_escape(args.setting)
              << "\",\"value\":" << args.value
              << ",\"enabled\":" << json_bool(args.enabled)
              << ",\"blendMode\":" << args.blend_mode
              << "},\"plan\":{\"operation\":\"" << brush_stroke_control_operation_name(value.operation)
              << "\",\"floatSetting\":\"" << brush_stroke_float_setting_name(value.float_setting)
              << "\",\"boolSetting\":\"" << brush_stroke_bool_setting_name(value.bool_setting)
              << "\",\"blendSetting\":\"" << brush_stroke_blend_setting_name(value.blend_setting)
              << "\",\"floatValue\":" << value.float_value
              << ",\"boolValue\":" << json_bool(value.bool_value)
              << ",\"blendMode\":" << value.blend_mode
              << ",\"mutatesBrush\":" << json_bool(value.mutates_brush)
              << ",\"updatesControls\":" << json_bool(value.updates_controls)
              << ",\"refreshesPreview\":" << json_bool(value.refreshes_preview)
              << ",\"notifiesStrokeChange\":" << json_bool(value.notifies_stroke_change)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_brush_stroke_panel_view_args(
    int argc,
    char** argv,
    PlanBrushStrokePanelViewArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--tip-size" || key == "--jitter-scatter") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--tip-size") {
                args.tip_size = value.value();
            } else {
                args.jitter_scatter = value.value();
            }
        } else if (key == "--tip-blend-mode" || key == "--pattern-blend-mode") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--tip-blend-mode") {
                args.tip_blend_mode = value.value();
            } else {
                args.pattern_blend_mode = value.value();
            }
        } else if (key == "--tip-thumb" || key == "--dual-thumb" || key == "--pattern-thumb") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            if (key == "--tip-thumb") {
                args.tip_thumbnail_path = argv[++i];
            } else if (key == "--dual-thumb") {
                args.dual_thumbnail_path = argv[++i];
            } else {
                args.pattern_thumbnail_path = argv[++i];
            }
        } else if (key == "--dual-enabled") {
            args.dual_enabled = true;
        } else if (key == "--dual-disabled") {
            args.dual_enabled = false;
        } else if (key == "--bad-float") {
            args.bad_float = true;
        } else if (key == "--bad-blend") {
            args.bad_blend = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_brush_stroke_panel_view(int argc, char** argv)
{
    PlanBrushStrokePanelViewArgs args;
    const auto status = parse_plan_brush_stroke_panel_view_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-brush-stroke-panel-view", status.message);
        return 2;
    }

    pp::app::BrushStrokePanelInput input;
    input.float_values.push_back(pp::app::BrushStrokeFloatValue {
        .setting = pp::app::BrushStrokeFloatSetting::tip_size,
        .value = args.bad_float ? std::nanf("") : args.tip_size,
    });
    input.float_values.push_back(pp::app::BrushStrokeFloatValue {
        .setting = pp::app::BrushStrokeFloatSetting::jitter_scatter,
        .value = args.jitter_scatter,
    });
    input.bool_values.push_back(pp::app::BrushStrokeBoolValue {
        .setting = pp::app::BrushStrokeBoolSetting::dual_enabled,
        .value = args.dual_enabled,
    });
    input.blend_values.push_back(pp::app::BrushStrokeBlendValue {
        .setting = pp::app::BrushStrokeBlendSetting::tip,
        .blend_mode = args.tip_blend_mode,
    });
    input.blend_values.push_back(pp::app::BrushStrokeBlendValue {
        .setting = pp::app::BrushStrokeBlendSetting::pattern,
        .blend_mode = args.bad_blend ? 64 : args.pattern_blend_mode,
    });
    input.tip_thumbnail_path = args.tip_thumbnail_path;
    input.dual_thumbnail_path = args.dual_thumbnail_path;
    input.pattern_thumbnail_path = args.pattern_thumbnail_path;

    const auto view = pp::app::plan_brush_stroke_panel_view(std::move(input));
    if (!view) {
        print_error("plan-brush-stroke-panel-view", view.status().message);
        return 2;
    }

    float tip_size = 0.0F;
    float jitter_scatter = 0.0F;
    bool dual_enabled = false;
    int tip_blend_mode = 0;
    int pattern_blend_mode = 0;
    for (const auto& value : view.value().float_values) {
        if (value.setting == pp::app::BrushStrokeFloatSetting::tip_size) {
            tip_size = value.value;
        } else if (value.setting == pp::app::BrushStrokeFloatSetting::jitter_scatter) {
            jitter_scatter = value.value;
        }
    }
    for (const auto& value : view.value().bool_values) {
        if (value.setting == pp::app::BrushStrokeBoolSetting::dual_enabled) {
            dual_enabled = value.value;
        }
    }
    for (const auto& value : view.value().blend_values) {
        if (value.setting == pp::app::BrushStrokeBlendSetting::tip) {
            tip_blend_mode = value.blend_mode;
        } else if (value.setting == pp::app::BrushStrokeBlendSetting::pattern) {
            pattern_blend_mode = value.blend_mode;
        }
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-brush-stroke-panel-view\""
              << ",\"state\":{\"tipSize\":" << args.tip_size
              << ",\"jitterScatter\":" << args.jitter_scatter
              << ",\"dualEnabled\":" << json_bool(args.dual_enabled)
              << ",\"tipBlendMode\":" << args.tip_blend_mode
              << ",\"patternBlendMode\":" << args.pattern_blend_mode
              << "},\"view\":{\"floatValues\":" << view.value().float_values.size()
              << ",\"boolValues\":" << view.value().bool_values.size()
              << ",\"blendValues\":" << view.value().blend_values.size()
              << ",\"tipSize\":" << tip_size
              << ",\"jitterScatter\":" << jitter_scatter
              << ",\"dualEnabled\":" << json_bool(dual_enabled)
              << ",\"tipBlendMode\":" << tip_blend_mode
              << ",\"patternBlendMode\":" << pattern_blend_mode
              << ",\"tipThumb\":\"" << json_escape(view.value().tip_thumbnail_path)
              << "\",\"dualThumb\":\"" << json_escape(view.value().dual_thumbnail_path)
              << "\",\"patternThumb\":\"" << json_escape(view.value().pattern_thumbnail_path)
              << "\",\"updatesPreview\":" << json_bool(view.value().updates_preview)
              << ",\"updatesThumbnails\":" << json_bool(view.value().updates_thumbnails)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_paint_feedback_args(
    int argc,
    char** argv,
    PlanPaintFeedbackArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--width" || key == "--height") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (value.value() <= 0) {
                return pp::foundation::Status::invalid_argument("paint feedback extent must be greater than zero");
            }
            if (key == "--width") {
                args.width = value.value();
            } else {
                args.height = value.value();
            }
        } else if (key == "--simple") {
            args.complex_blend = false;
        } else if (key == "--complex") {
            args.complex_blend = true;
        } else if (key == "--framebuffer-fetch") {
            args.framebuffer_fetch = true;
        } else if (key == "--explicit-transitions") {
            args.explicit_texture_transitions = true;
        } else if (key == "--texture-copy") {
            args.texture_copy = true;
        } else if (key == "--blit") {
            args.render_target_blit = true;
        } else if (key == "--render-only") {
            args.render_only_target = true;
        } else if (key == "--depth") {
            args.depth_target = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_paint_feedback(int argc, char** argv)
{
    PlanPaintFeedbackArgs args;
    const auto status = parse_plan_paint_feedback_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-paint-feedback", status.message);
        return 2;
    }

    pp::renderer::TextureUsage usage = pp::renderer::TextureUsage::render_target;
    if (!args.render_only_target) {
        usage |= pp::renderer::TextureUsage::sampled;
        usage |= pp::renderer::TextureUsage::copy_source;
        usage |= pp::renderer::TextureUsage::copy_destination;
    }

    const pp::renderer::RenderDeviceFeatures features {
        .framebuffer_fetch = args.framebuffer_fetch,
        .explicit_texture_transitions = args.explicit_texture_transitions,
        .texture_copy = args.texture_copy,
        .render_target_blit = args.render_target_blit,
    };
    const pp::renderer::TextureDesc target {
        .extent = pp::renderer::Extent2D {
            .width = static_cast<std::uint32_t>(args.width),
            .height = static_cast<std::uint32_t>(args.height),
        },
        .format = args.depth_target
            ? pp::renderer::TextureFormat::depth24_stencil8
            : pp::renderer::TextureFormat::rgba8,
        .usage = usage,
        .debug_name = "paint-feedback-target",
    };

    const auto plan = pp::renderer::plan_paint_feedback(features, target, args.complex_blend);
    if (!plan) {
        print_error("plan-paint-feedback", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-paint-feedback\""
              << ",\"state\":{\"width\":" << args.width
              << ",\"height\":" << args.height
              << ",\"complexBlend\":" << json_bool(args.complex_blend)
              << ",\"framebufferFetch\":" << json_bool(args.framebuffer_fetch)
              << ",\"explicitTransitions\":" << json_bool(args.explicit_texture_transitions)
              << ",\"textureCopy\":" << json_bool(args.texture_copy)
              << ",\"blit\":" << json_bool(args.render_target_blit)
              << ",\"renderOnlyTarget\":" << json_bool(args.render_only_target)
              << ",\"depthTarget\":" << json_bool(args.depth_target)
              << "},\"plan\":{\"path\":\"" << pp::renderer::paint_feedback_path_name(value.path)
              << "\",\"targetFormat\":\"" << pp::renderer::texture_format_name(value.target_desc.format)
              << "\",\"targetBytes\":" << value.target_bytes
              << ",\"complexBlend\":" << json_bool(value.complex_blend)
              << ",\"readsDestinationColor\":" << json_bool(value.reads_destination_color)
              << ",\"requiresAuxiliaryTexture\":" << json_bool(value.requires_auxiliary_texture)
              << ",\"requiresTextureCopy\":" << json_bool(value.requires_texture_copy)
              << ",\"requiresRenderTargetBlit\":" << json_bool(value.requires_render_target_blit)
              << ",\"requiresExplicitTransition\":" << json_bool(value.requires_explicit_transition)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_stroke_composite_args(
    int argc,
    char** argv,
    PlanStrokeCompositeArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--width" || key == "--height" || key == "--layer-blend" || key == "--stroke-blend") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--width" || key == "--height") {
                if (value.value() <= 0) {
                    return pp::foundation::Status::invalid_argument("stroke composite extent must be greater than zero");
                }
                if (key == "--width") {
                    args.width = value.value();
                } else {
                    args.height = value.value();
                }
            } else if (key == "--layer-blend") {
                args.layer_blend_mode = value.value();
            } else {
                args.stroke_blend_mode = value.value();
            }
        } else if (key == "--dual-blend") {
            args.dual_brush_blend = true;
        } else if (key == "--pattern-blend") {
            args.pattern_blend = true;
        } else if (key == "--framebuffer-fetch") {
            args.framebuffer_fetch = true;
        } else if (key == "--explicit-transitions") {
            args.explicit_texture_transitions = true;
        } else if (key == "--texture-copy") {
            args.texture_copy = true;
        } else if (key == "--blit") {
            args.render_target_blit = true;
        } else if (key == "--render-only") {
            args.render_only_target = true;
        } else if (key == "--depth") {
            args.depth_target = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.layer_blend_mode < 0 || args.layer_blend_mode > 4) {
        return pp::foundation::Status::out_of_range("layer blend mode must be in the range [0, 4]");
    }
    if (args.stroke_blend_mode < 0 || args.stroke_blend_mode > 10) {
        return pp::foundation::Status::out_of_range("stroke blend mode must be in the range [0, 10]");
    }

    return pp::foundation::Status::success();
}

int plan_stroke_composite(int argc, char** argv)
{
    PlanStrokeCompositeArgs args;
    const auto status = parse_plan_stroke_composite_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-stroke-composite", status.message);
        return 2;
    }

    pp::renderer::TextureUsage usage = pp::renderer::TextureUsage::render_target;
    if (!args.render_only_target) {
        usage |= pp::renderer::TextureUsage::sampled;
        usage |= pp::renderer::TextureUsage::copy_source;
        usage |= pp::renderer::TextureUsage::copy_destination;
    }

    const pp::paint_renderer::StrokeCompositeRequest request {
        .extent = pp::renderer::Extent2D {
            .width = static_cast<std::uint32_t>(args.width),
            .height = static_cast<std::uint32_t>(args.height),
        },
        .target_format = args.depth_target
            ? pp::renderer::TextureFormat::depth24_stencil8
            : pp::renderer::TextureFormat::rgba8,
        .target_usage = usage,
        .layer_blend_mode = static_cast<pp::paint::BlendMode>(args.layer_blend_mode),
        .stroke_blend_mode = static_cast<pp::paint::StrokeBlendMode>(args.stroke_blend_mode),
        .dual_brush_blend = args.dual_brush_blend,
        .pattern_blend = args.pattern_blend,
    };
    const pp::renderer::RenderDeviceFeatures features {
        .framebuffer_fetch = args.framebuffer_fetch,
        .explicit_texture_transitions = args.explicit_texture_transitions,
        .texture_copy = args.texture_copy,
        .render_target_blit = args.render_target_blit,
    };
    const auto plan = pp::paint_renderer::plan_stroke_composite(features, request);
    if (!plan) {
        print_error("plan-stroke-composite", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-stroke-composite\""
              << ",\"state\":{\"width\":" << args.width
              << ",\"height\":" << args.height
              << ",\"layerBlend\":\"" << pp::paint::blend_mode_name(request.layer_blend_mode)
              << "\",\"strokeBlend\":\"" << pp::paint::stroke_blend_mode_name(request.stroke_blend_mode)
              << "\",\"dualBrushBlend\":" << json_bool(args.dual_brush_blend)
              << ",\"patternBlend\":" << json_bool(args.pattern_blend)
              << ",\"framebufferFetch\":" << json_bool(args.framebuffer_fetch)
              << ",\"explicitTransitions\":" << json_bool(args.explicit_texture_transitions)
              << ",\"textureCopy\":" << json_bool(args.texture_copy)
              << ",\"blit\":" << json_bool(args.render_target_blit)
              << ",\"renderOnlyTarget\":" << json_bool(args.render_only_target)
              << ",\"depthTarget\":" << json_bool(args.depth_target)
              << "},\"plan\":{\"path\":\"" << pp::paint_renderer::stroke_composite_path_name(value.path)
              << "\",\"feedbackPath\":\"" << pp::renderer::paint_feedback_path_name(value.feedback.path)
              << "\",\"targetBytes\":" << value.target_bytes
              << ",\"auxiliaryBytes\":" << value.auxiliary_bytes
              << ",\"estimatedWorkingBytes\":" << value.estimated_working_bytes
              << ",\"complexBlend\":" << json_bool(value.complex_blend)
              << ",\"readsDestinationColor\":" << json_bool(value.reads_destination_color)
              << ",\"requiresAuxiliaryTexture\":" << json_bool(value.requires_auxiliary_texture)
              << ",\"requiresTextureCopy\":" << json_bool(value.requires_texture_copy)
              << ",\"requiresRenderTargetBlit\":" << json_bool(value.requires_render_target_blit)
              << ",\"requiresExplicitTransition\":" << json_bool(value.requires_explicit_transition)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_canvas_tool_args(
    int argc,
    char** argv,
    PlanCanvasToolArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.kind = argv[++i];
        } else if (key == "--current-mode-draw") {
            args.current_mode_draw = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

pp::foundation::Result<pp::app::CanvasToolPlan> make_canvas_tool_plan(const PlanCanvasToolArgs& args)
{
    if (args.kind == "pick") {
        return pp::foundation::Result<pp::app::CanvasToolPlan>::success(
            pp::app::plan_canvas_tool_pick_toggle(args.current_mode_draw));
    }
    if (args.kind == "touch-lock") {
        return pp::foundation::Result<pp::app::CanvasToolPlan>::success(
            pp::app::plan_canvas_tool_touch_lock_toggle());
    }
    if (args.kind == "draw") {
        return pp::foundation::Result<pp::app::CanvasToolPlan>::success(
            pp::app::plan_canvas_tool_select(pp::app::CanvasToolMode::draw));
    }
    if (args.kind == "erase") {
        return pp::foundation::Result<pp::app::CanvasToolPlan>::success(
            pp::app::plan_canvas_tool_select(pp::app::CanvasToolMode::erase));
    }
    if (args.kind == "line") {
        return pp::foundation::Result<pp::app::CanvasToolPlan>::success(
            pp::app::plan_canvas_tool_select(pp::app::CanvasToolMode::line));
    }
    if (args.kind == "camera") {
        return pp::foundation::Result<pp::app::CanvasToolPlan>::success(
            pp::app::plan_canvas_tool_select(pp::app::CanvasToolMode::camera));
    }
    if (args.kind == "grid") {
        return pp::foundation::Result<pp::app::CanvasToolPlan>::success(
            pp::app::plan_canvas_tool_select(pp::app::CanvasToolMode::grid));
    }
    if (args.kind == "copy") {
        return pp::foundation::Result<pp::app::CanvasToolPlan>::success(
            pp::app::plan_canvas_tool_select(pp::app::CanvasToolMode::copy));
    }
    if (args.kind == "cut") {
        return pp::foundation::Result<pp::app::CanvasToolPlan>::success(
            pp::app::plan_canvas_tool_select(pp::app::CanvasToolMode::cut));
    }
    if (args.kind == "fill") {
        return pp::foundation::Result<pp::app::CanvasToolPlan>::success(
            pp::app::plan_canvas_tool_select(pp::app::CanvasToolMode::fill));
    }
    if (args.kind == "mask-free") {
        return pp::foundation::Result<pp::app::CanvasToolPlan>::success(
            pp::app::plan_canvas_tool_select(pp::app::CanvasToolMode::mask_free));
    }
    if (args.kind == "mask-line") {
        return pp::foundation::Result<pp::app::CanvasToolPlan>::success(
            pp::app::plan_canvas_tool_select(pp::app::CanvasToolMode::mask_line));
    }
    if (args.kind == "bucket") {
        return pp::foundation::Result<pp::app::CanvasToolPlan>::success(
            pp::app::plan_canvas_tool_select(pp::app::CanvasToolMode::flood_fill));
    }

    return pp::foundation::Result<pp::app::CanvasToolPlan>::failure(
        pp::foundation::Status::invalid_argument("unknown canvas tool kind"));
}

pp::foundation::Result<pp::app::CanvasToolMode> parse_canvas_tool_mode(std::string_view mode)
{
    if (mode == "draw") {
        return pp::foundation::Result<pp::app::CanvasToolMode>::success(pp::app::CanvasToolMode::draw);
    }
    if (mode == "erase") {
        return pp::foundation::Result<pp::app::CanvasToolMode>::success(pp::app::CanvasToolMode::erase);
    }
    if (mode == "line") {
        return pp::foundation::Result<pp::app::CanvasToolMode>::success(pp::app::CanvasToolMode::line);
    }
    if (mode == "camera") {
        return pp::foundation::Result<pp::app::CanvasToolMode>::success(pp::app::CanvasToolMode::camera);
    }
    if (mode == "grid") {
        return pp::foundation::Result<pp::app::CanvasToolMode>::success(pp::app::CanvasToolMode::grid);
    }
    if (mode == "copy") {
        return pp::foundation::Result<pp::app::CanvasToolMode>::success(pp::app::CanvasToolMode::copy);
    }
    if (mode == "cut") {
        return pp::foundation::Result<pp::app::CanvasToolMode>::success(pp::app::CanvasToolMode::cut);
    }
    if (mode == "fill") {
        return pp::foundation::Result<pp::app::CanvasToolMode>::success(pp::app::CanvasToolMode::fill);
    }
    if (mode == "mask-free") {
        return pp::foundation::Result<pp::app::CanvasToolMode>::success(pp::app::CanvasToolMode::mask_free);
    }
    if (mode == "mask-line") {
        return pp::foundation::Result<pp::app::CanvasToolMode>::success(pp::app::CanvasToolMode::mask_line);
    }
    if (mode == "bucket") {
        return pp::foundation::Result<pp::app::CanvasToolMode>::success(pp::app::CanvasToolMode::flood_fill);
    }

    return pp::foundation::Result<pp::app::CanvasToolMode>::failure(
        pp::foundation::Status::invalid_argument("unknown canvas tool mode"));
}

pp::foundation::Result<pp::app::CanvasCursorVisibilityMode> parse_canvas_cursor_visibility_mode(
    std::string_view mode)
{
    if (mode == "never") {
        return pp::foundation::Result<pp::app::CanvasCursorVisibilityMode>::success(
            pp::app::CanvasCursorVisibilityMode::never);
    }
    if (mode == "small-brush") {
        return pp::foundation::Result<pp::app::CanvasCursorVisibilityMode>::success(
            pp::app::CanvasCursorVisibilityMode::small_brush);
    }
    if (mode == "not-painting") {
        return pp::foundation::Result<pp::app::CanvasCursorVisibilityMode>::success(
            pp::app::CanvasCursorVisibilityMode::not_painting);
    }
    if (mode == "always") {
        return pp::foundation::Result<pp::app::CanvasCursorVisibilityMode>::success(
            pp::app::CanvasCursorVisibilityMode::always);
    }

    return pp::foundation::Result<pp::app::CanvasCursorVisibilityMode>::failure(
        pp::foundation::Status::invalid_argument("unknown canvas cursor visibility mode"));
}

int plan_canvas_tool(int argc, char** argv)
{
    PlanCanvasToolArgs args;
    const auto status = parse_plan_canvas_tool_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-canvas-tool", status.message);
        return 2;
    }

    const auto plan = make_canvas_tool_plan(args);
    if (!plan) {
        print_error("plan-canvas-tool", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-canvas-tool\""
              << ",\"state\":{\"kind\":\"" << json_escape(args.kind)
              << "\",\"currentModeDraw\":" << json_bool(args.current_mode_draw)
              << "},\"plan\":{\"operation\":\"" << canvas_tool_operation_name(value.operation)
              << "\",\"mode\":\"" << canvas_tool_mode_name(value.mode)
              << "\",\"transformAction\":\"" << canvas_tool_transform_action_name(value.transform_action)
              << "\",\"selectsToolbarButton\":" << json_bool(value.selects_toolbar_button)
              << ",\"updatesCanvasMode\":" << json_bool(value.updates_canvas_mode)
              << ",\"togglesPicking\":" << json_bool(value.toggles_picking)
              << ",\"togglesTouchLock\":" << json_bool(value.toggles_touch_lock)
              << ",\"requiresDrawMode\":" << json_bool(value.requires_draw_mode)
              << ",\"noOp\":" << json_bool(value.no_op)
              << "}}\n";
    return 0;
}

int plan_canvas_tool_toolbar(int argc, char** argv)
{
    if (argc > 2) {
        print_error("plan-canvas-tool-toolbar", "unknown option");
        return 2;
    }

    const auto toolbar = pp::app::plan_canvas_tool_toolbar();
    std::cout << "{\"ok\":true,\"command\":\"plan-canvas-tool-toolbar\""
              << ",\"defaultMode\":\"" << canvas_tool_mode_name(toolbar.default_mode)
              << "\",\"bindingCount\":" << toolbar.bindings.size()
              << ",\"bindings\":[";
    for (std::size_t i = 0; i < toolbar.bindings.size(); ++i) {
        const auto& binding = toolbar.bindings[i];
        if (i > 0) {
            std::cout << ",";
        }
        std::cout << "{\"id\":\"" << json_escape(binding.button_id)
                  << "\",\"action\":\"" << canvas_tool_toolbar_action_name(binding.action)
                  << "\",\"mode\":\"" << canvas_tool_mode_name(binding.mode)
                  << "\",\"customButton\":" << json_bool(binding.custom_button)
                  << ",\"defaultOnInit\":" << json_bool(binding.applies_default_on_init)
                  << "}";
    }
    std::cout << "]}\n";
    return 0;
}

pp::foundation::Result<pp::app::CanvasHotkeyEvent> parse_canvas_hotkey_event(std::string_view event)
{
    if (event == "key-down") {
        return pp::foundation::Result<pp::app::CanvasHotkeyEvent>::success(
            pp::app::CanvasHotkeyEvent::key_down);
    }
    if (event == "key-up") {
        return pp::foundation::Result<pp::app::CanvasHotkeyEvent>::success(
            pp::app::CanvasHotkeyEvent::key_up);
    }
    if (event == "touch-tap") {
        return pp::foundation::Result<pp::app::CanvasHotkeyEvent>::success(
            pp::app::CanvasHotkeyEvent::touch_tap);
    }

    return pp::foundation::Result<pp::app::CanvasHotkeyEvent>::failure(
        pp::foundation::Status::invalid_argument("unknown canvas hotkey event"));
}

pp::foundation::Result<pp::app::CanvasHotkeyKey> parse_canvas_hotkey_key(std::string_view key)
{
    if (key == "other") {
        return pp::foundation::Result<pp::app::CanvasHotkeyKey>::success(
            pp::app::CanvasHotkeyKey::other);
    }
    if (key == "android-back") {
        return pp::foundation::Result<pp::app::CanvasHotkeyKey>::success(
            pp::app::CanvasHotkeyKey::android_back);
    }
    if (key == "alt") {
        return pp::foundation::Result<pp::app::CanvasHotkeyKey>::success(
            pp::app::CanvasHotkeyKey::alt);
    }
    if (key == "e") {
        return pp::foundation::Result<pp::app::CanvasHotkeyKey>::success(pp::app::CanvasHotkeyKey::e);
    }
    if (key == "s") {
        return pp::foundation::Result<pp::app::CanvasHotkeyKey>::success(pp::app::CanvasHotkeyKey::s);
    }
    if (key == "tab") {
        return pp::foundation::Result<pp::app::CanvasHotkeyKey>::success(pp::app::CanvasHotkeyKey::tab);
    }
    if (key == "z") {
        return pp::foundation::Result<pp::app::CanvasHotkeyKey>::success(pp::app::CanvasHotkeyKey::z);
    }
    if (key == "bracket-left") {
        return pp::foundation::Result<pp::app::CanvasHotkeyKey>::success(
            pp::app::CanvasHotkeyKey::bracket_left);
    }
    if (key == "bracket-right") {
        return pp::foundation::Result<pp::app::CanvasHotkeyKey>::success(
            pp::app::CanvasHotkeyKey::bracket_right);
    }

    return pp::foundation::Result<pp::app::CanvasHotkeyKey>::failure(
        pp::foundation::Status::invalid_argument("unknown canvas hotkey key"));
}

pp::foundation::Status parse_plan_canvas_hotkey_args(
    int argc,
    char** argv,
    PlanCanvasHotkeyArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--event" || key == "--key") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            if (key == "--event") {
                args.event = argv[++i];
            } else {
                args.key = argv[++i];
            }
        } else if (key == "--undo-count" || key == "--redo-count" || key == "--touch-fingers") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--undo-count") {
                args.undo_count = value.value();
            } else if (key == "--redo-count") {
                args.redo_count = value.value();
            } else {
                args.touch_finger_count = value.value();
            }
        } else if (key == "--ctrl") {
            args.ctrl_down = true;
        } else if (key == "--shift") {
            args.shift_down = true;
        } else if (key == "--mouse-focus") {
            args.mouse_focused = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_canvas_hotkey(int argc, char** argv)
{
    PlanCanvasHotkeyArgs args;
    const auto status = parse_plan_canvas_hotkey_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-canvas-hotkey", status.message);
        return 2;
    }

    const auto event = parse_canvas_hotkey_event(args.event);
    if (!event) {
        print_error("plan-canvas-hotkey", event.status().message);
        return 2;
    }
    const auto key = parse_canvas_hotkey_key(args.key);
    if (!key) {
        print_error("plan-canvas-hotkey", key.status().message);
        return 2;
    }

    pp::app::CanvasHotkeyState state;
    state.ctrl_down = args.ctrl_down;
    state.shift_down = args.shift_down;
    state.mouse_focused = args.mouse_focused;
    state.undo_count = args.undo_count;
    state.redo_count = args.redo_count;
    state.touch_finger_count = args.touch_finger_count;

    const auto plan = pp::app::plan_canvas_hotkey(event.value(), key.value(), state);
    if (!plan) {
        print_error("plan-canvas-hotkey", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-canvas-hotkey\""
              << ",\"state\":{\"event\":\"" << json_escape(args.event)
              << "\",\"key\":\"" << json_escape(args.key)
              << "\",\"ctrl\":" << json_bool(args.ctrl_down)
              << ",\"shift\":" << json_bool(args.shift_down)
              << ",\"mouseFocus\":" << json_bool(args.mouse_focused)
              << ",\"undoCount\":" << args.undo_count
              << ",\"redoCount\":" << args.redo_count
              << ",\"touchFingers\":" << args.touch_finger_count
              << "},\"plan\":{\"event\":\"" << canvas_hotkey_event_name(value.event)
              << "\",\"key\":\"" << canvas_hotkey_key_name(value.key)
              << "\",\"action\":\"" << canvas_hotkey_action_name(value.action)
              << "\",\"toolMode\":\"" << canvas_tool_mode_name(value.tool.mode)
              << "\",\"historyOperation\":\"" << history_ui_operation_name(value.history.operation)
              << "\",\"historyNoOp\":" << json_bool(value.history.no_op)
              << ",\"saveIntent\":\"" << document_save_intent_name(value.save_intent)
              << "\",\"brushSizeDelta\":" << value.brush_size_delta
              << ",\"noOp\":" << json_bool(value.no_op)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_canvas_tool_state_args(
    int argc,
    char** argv,
    PlanCanvasToolStateArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--mode") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.mode = argv[++i];
        } else if (key == "--picking") {
            args.picking = true;
        } else if (key == "--touch-lock") {
            args.touch_lock = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_canvas_tool_state(int argc, char** argv)
{
    PlanCanvasToolStateArgs args;
    const auto status = parse_plan_canvas_tool_state_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-canvas-tool-state", status.message);
        return 2;
    }

    const auto mode = parse_canvas_tool_mode(args.mode);
    if (!mode) {
        print_error("plan-canvas-tool-state", mode.status().message);
        return 2;
    }

    const auto state = pp::app::plan_canvas_tool_button_state(
        mode.value(),
        args.picking,
        args.touch_lock);
    std::cout << "{\"ok\":true,\"command\":\"plan-canvas-tool-state\""
              << ",\"state\":{\"mode\":\"" << json_escape(args.mode)
              << "\",\"picking\":" << json_bool(args.picking)
              << ",\"touchLock\":" << json_bool(args.touch_lock)
              << "},\"toolbar\":{\"mode\":\"" << canvas_tool_mode_name(state.mode)
              << "\",\"pickActive\":" << json_bool(state.pick_active)
              << ",\"touchLockActive\":" << json_bool(state.touch_lock_active)
              << ",\"penActive\":" << json_bool(state.pen_active)
              << ",\"eraseActive\":" << json_bool(state.erase_active)
              << ",\"lineActive\":" << json_bool(state.line_active)
              << ",\"cameraActive\":" << json_bool(state.camera_active)
              << ",\"gridActive\":" << json_bool(state.grid_active)
              << ",\"copyActive\":" << json_bool(state.copy_active)
              << ",\"cutActive\":" << json_bool(state.cut_active)
              << ",\"fillActive\":" << json_bool(state.fill_active)
              << ",\"maskFreeActive\":" << json_bool(state.mask_free_active)
              << ",\"maskLineActive\":" << json_bool(state.mask_line_active)
              << ",\"bucketActive\":" << json_bool(state.flood_fill_active)
              << "}}\n";
    return 0;
}

int plan_canvas_camera_reset(int argc, char** argv)
{
    if (argc > 2) {
        print_error("plan-canvas-camera-reset", "unknown option");
        return 2;
    }

    const auto state = pp::app::plan_canvas_camera_reset();
    std::cout << "{\"ok\":true,\"command\":\"plan-canvas-camera-reset\""
              << ",\"rotation\":[";
    for (std::size_t index = 0; index < state.rotation.size(); ++index) {
        if (index != 0U) {
            std::cout << ",";
        }
        std::cout << state.rotation[index];
    }
    std::cout << "],\"position\":[" << state.position[0] << "," << state.position[1] << "," << state.position[2]
              << "],\"fieldOfViewDegrees\":" << state.field_of_view_degrees
              << ",\"pan\":[" << state.pan[0] << "," << state.pan[1] << "]}\n";
    return 0;
}

int plan_canvas_view_density(int argc, char** argv)
{
    float density = 1.0F;
    bool bad_float = false;
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--density") {
            if (i + 1 >= argc) {
                print_error("plan-canvas-view-density", "missing value for option");
                return 2;
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                print_error("plan-canvas-view-density", value.status().message);
                return 2;
            }
            density = value.value();
        } else if (key == "--bad-float") {
            bad_float = true;
        } else {
            print_error("plan-canvas-view-density", "unknown option");
            return 2;
        }
    }

    const auto plan = pp::app::plan_canvas_view_density(bad_float ? std::nanf("") : density);
    if (!plan) {
        print_error("plan-canvas-view-density", plan.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-canvas-view-density\""
              << ",\"density\":" << plan.value().density
              << ",\"recreatesBuffers\":" << json_bool(plan.value().recreates_buffers)
              << "}\n";
    return 0;
}

int plan_canvas_view_cursor_mode(int argc, char** argv)
{
    int mode = 0;
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--mode") {
            if (i + 1 >= argc) {
                print_error("plan-canvas-view-cursor-mode", "missing value for option");
                return 2;
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                print_error("plan-canvas-view-cursor-mode", value.status().message);
                return 2;
            }
            mode = value.value();
        } else {
            print_error("plan-canvas-view-cursor-mode", "unknown option");
            return 2;
        }
    }

    const auto plan = pp::app::plan_canvas_view_cursor_mode(mode);
    if (!plan) {
        print_error("plan-canvas-view-cursor-mode", plan.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-canvas-view-cursor-mode\""
              << ",\"mode\":" << static_cast<int>(plan.value().mode)
              << "}\n";
    return 0;
}

pp::foundation::Status parse_plan_canvas_cursor_args(
    int argc,
    char** argv,
    PlanCanvasCursorArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--mode" || key == "--visibility") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            if (key == "--mode") {
                args.mode = argv[++i];
            } else {
                args.visibility = argv[++i];
            }
        } else if (key == "--brush-size") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            args.brush_size = value.value();
        } else if (key == "--no-brush") {
            args.has_brush = false;
        } else if (key == "--drawing") {
            args.drawing = true;
        } else if (key == "--alt") {
            args.alt = true;
        } else if (key == "--resizing") {
            args.resizing = true;
        } else if (key == "--picking") {
            args.picking = true;
        } else if (key == "--bad-size") {
            args.bad_size = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_canvas_cursor(int argc, char** argv)
{
    PlanCanvasCursorArgs args;
    const auto status = parse_plan_canvas_cursor_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-canvas-cursor", status.message);
        return 2;
    }

    const auto mode = parse_canvas_tool_mode(args.mode);
    if (!mode) {
        print_error("plan-canvas-cursor", mode.status().message);
        return 2;
    }
    const auto visibility = parse_canvas_cursor_visibility_mode(args.visibility);
    if (!visibility) {
        print_error("plan-canvas-cursor", visibility.status().message);
        return 2;
    }

    const auto plan = pp::app::plan_canvas_cursor_visibility(pp::app::CanvasCursorVisibilityInput {
        .mode = mode.value(),
        .visibility_mode = visibility.value(),
        .has_current_brush = args.has_brush,
        .brush_tip_size = args.bad_size ? std::nanf("") : args.brush_size,
        .pen_is_drawing = args.drawing,
        .alt_down = args.alt,
        .pen_is_resizing = args.resizing,
        .pen_is_picking = args.picking,
    });
    if (!plan) {
        print_error("plan-canvas-cursor", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-canvas-cursor\""
              << ",\"state\":{\"mode\":\"" << canvas_tool_mode_name(mode.value())
              << "\",\"visibility\":\"" << canvas_cursor_visibility_mode_name(visibility.value())
              << "\",\"hasBrush\":" << json_bool(args.has_brush)
              << ",\"brushSize\":" << args.brush_size
              << ",\"drawing\":" << json_bool(args.drawing)
              << ",\"alt\":" << json_bool(args.alt)
              << ",\"resizing\":" << json_bool(args.resizing)
              << ",\"picking\":" << json_bool(args.picking)
              << "},\"plan\":{\"visible\":" << json_bool(value.visible)
              << ",\"paintMode\":" << json_bool(value.paint_mode)
              << ",\"usesBrushSize\":" << json_bool(value.uses_brush_size)
              << ",\"usesPenState\":" << json_bool(value.uses_pen_state)
              << ",\"forcedVisibleByModifierOrTool\":" << json_bool(value.forced_visible_by_modifier_or_tool)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_grid_operation_args(
    int argc,
    char** argv,
    PlanGridOperationArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind" || key == "--path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            if (key == "--kind") {
                args.kind = argv[++i];
            } else {
                args.path = argv[++i];
            }
        } else if (key == "--texture-resolution" || key == "--samples") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--texture-resolution") {
                args.texture_resolution = value.value();
            } else {
                args.sample_count = value.value();
            }
        } else if (key == "--no-heightmap") {
            args.has_heightmap = false;
        } else if (key == "--no-canvas") {
            args.has_canvas = false;
        } else if (key == "--float32") {
            args.supports_float32 = true;
        } else if (key == "--float16") {
            args.supports_float16 = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

pp::foundation::Result<pp::app::GridUiPlan> make_grid_operation_plan(const PlanGridOperationArgs& args)
{
    if (args.kind == "pick") {
        return pp::foundation::Result<pp::app::GridUiPlan>::success(pp::app::plan_grid_heightmap_pick());
    }
    if (args.kind == "load") {
        return pp::app::plan_grid_heightmap_load(args.path);
    }
    if (args.kind == "reload") {
        return pp::app::plan_grid_heightmap_reload(args.path);
    }
    if (args.kind == "clear") {
        return pp::foundation::Result<pp::app::GridUiPlan>::success(
            pp::app::plan_grid_heightmap_clear(args.has_heightmap));
    }
    if (args.kind == "render") {
        return pp::app::plan_grid_lightmap_render(
            args.has_heightmap,
            args.supports_float32,
            args.supports_float16,
            args.texture_resolution,
            args.sample_count);
    }
    if (args.kind == "commit") {
        return pp::foundation::Result<pp::app::GridUiPlan>::success(
            pp::app::plan_grid_heightmap_commit(args.has_canvas));
    }

    return pp::foundation::Result<pp::app::GridUiPlan>::failure(
        pp::foundation::Status::invalid_argument("unknown grid operation kind"));
}

int plan_grid_operation(int argc, char** argv)
{
    PlanGridOperationArgs args;
    const auto status = parse_plan_grid_operation_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-grid-operation", status.message);
        return 2;
    }

    const auto plan = make_grid_operation_plan(args);
    if (!plan) {
        print_error("plan-grid-operation", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-grid-operation\""
              << ",\"state\":{\"kind\":\"" << json_escape(args.kind)
              << "\",\"path\":\"" << json_escape(args.path)
              << "\",\"hasHeightmap\":" << json_bool(args.has_heightmap)
              << ",\"hasCanvas\":" << json_bool(args.has_canvas)
              << ",\"float32\":" << json_bool(args.supports_float32)
              << ",\"float16\":" << json_bool(args.supports_float16)
              << ",\"textureResolution\":" << args.texture_resolution
              << ",\"samples\":" << args.sample_count
              << "},\"plan\":{\"operation\":\"" << grid_ui_operation_name(value.operation)
              << "\",\"path\":\"" << json_escape(value.path)
              << "\",\"textureResolution\":" << value.texture_resolution
              << ",\"sampleCount\":" << value.sample_count
              << ",\"opensPicker\":" << json_bool(value.opens_picker)
              << ",\"loadsHeightmap\":" << json_bool(value.loads_heightmap)
              << ",\"clearsHeightmap\":" << json_bool(value.clears_heightmap)
              << ",\"rendersLightmap\":" << json_bool(value.renders_lightmap)
              << ",\"commitsHeightmap\":" << json_bool(value.commits_heightmap)
              << ",\"updatesPreview\":" << json_bool(value.updates_preview)
              << ",\"updatesGroundOpacity\":" << json_bool(value.updates_ground_opacity)
              << ",\"updatesShadingMode\":" << json_bool(value.updates_shading_mode)
              << ",\"showsUnsupportedMessage\":" << json_bool(value.shows_unsupported_message)
              << ",\"showsProgress\":" << json_bool(value.shows_progress)
              << ",\"mutatesGridState\":" << json_bool(value.mutates_grid_state)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_history_operation_args(
    int argc,
    char** argv,
    PlanHistoryOperationArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.kind = argv[++i];
        } else if (key == "--undo-count" || key == "--redo-count" || key == "--memory-bytes") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--undo-count") {
                args.undo_count = value.value();
            } else if (key == "--redo-count") {
                args.redo_count = value.value();
            } else {
                args.memory_bytes = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

pp::foundation::Result<pp::app::HistoryUiPlan> make_history_operation_plan(
    const PlanHistoryOperationArgs& args)
{
    if (args.kind == "undo") {
        return pp::app::plan_history_undo(args.undo_count);
    }
    if (args.kind == "redo") {
        return pp::app::plan_history_redo(args.redo_count);
    }
    if (args.kind == "clear") {
        return pp::app::plan_history_clear(args.undo_count, args.redo_count, args.memory_bytes);
    }

    return pp::foundation::Result<pp::app::HistoryUiPlan>::failure(
        pp::foundation::Status::invalid_argument("unknown history operation kind"));
}

int plan_history_operation(int argc, char** argv)
{
    PlanHistoryOperationArgs args;
    const auto status = parse_plan_history_operation_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-history-operation", status.message);
        return 2;
    }

    const auto plan = make_history_operation_plan(args);
    if (!plan) {
        print_error("plan-history-operation", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-history-operation\""
              << ",\"state\":{\"kind\":\"" << json_escape(args.kind)
              << "\",\"undoCount\":" << args.undo_count
              << ",\"redoCount\":" << args.redo_count
              << ",\"memoryBytes\":" << args.memory_bytes
              << "},\"plan\":{\"operation\":\"" << history_ui_operation_name(value.operation)
              << "\",\"undoCount\":" << value.undo_count
              << ",\"redoCount\":" << value.redo_count
              << ",\"memoryBytes\":" << value.memory_bytes
              << ",\"invokesUndo\":" << json_bool(value.invokes_undo)
              << ",\"invokesRedo\":" << json_bool(value.invokes_redo)
              << ",\"clearsHistory\":" << json_bool(value.clears_history)
              << ",\"updatesMemoryLabel\":" << json_bool(value.updates_memory_label)
              << ",\"updatesTitle\":" << json_bool(value.updates_title)
              << ",\"noOp\":" << json_bool(value.no_op)
              << "}}\n";
    return 0;
}

pp::foundation::Result<pp::app::MainToolbarCommand> parse_main_toolbar_command(std::string_view command)
{
    if (command == "open") {
        return pp::foundation::Result<pp::app::MainToolbarCommand>::success(
            pp::app::MainToolbarCommand::open_document);
    }
    if (command == "save") {
        return pp::foundation::Result<pp::app::MainToolbarCommand>::success(
            pp::app::MainToolbarCommand::save_document);
    }
    if (command == "undo") {
        return pp::foundation::Result<pp::app::MainToolbarCommand>::success(
            pp::app::MainToolbarCommand::undo);
    }
    if (command == "redo") {
        return pp::foundation::Result<pp::app::MainToolbarCommand>::success(
            pp::app::MainToolbarCommand::redo);
    }
    if (command == "clear-history") {
        return pp::foundation::Result<pp::app::MainToolbarCommand>::success(
            pp::app::MainToolbarCommand::clear_history);
    }
    if (command == "clear-canvas") {
        return pp::foundation::Result<pp::app::MainToolbarCommand>::success(
            pp::app::MainToolbarCommand::clear_canvas);
    }
    if (command == "message-box") {
        return pp::foundation::Result<pp::app::MainToolbarCommand>::success(
            pp::app::MainToolbarCommand::show_message_box);
    }
    if (command == "settings") {
        return pp::foundation::Result<pp::app::MainToolbarCommand>::success(
            pp::app::MainToolbarCommand::show_settings);
    }

    return pp::foundation::Result<pp::app::MainToolbarCommand>::failure(
        pp::foundation::Status::invalid_argument("unknown main toolbar command"));
}

pp::foundation::Status parse_plan_main_toolbar_args(
    int argc,
    char** argv,
    PlanMainToolbarArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--command") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.command = argv[++i];
        } else if (key == "--undo-count" || key == "--redo-count" || key == "--memory-bytes") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--undo-count") {
                args.undo_count = value.value();
            } else if (key == "--redo-count") {
                args.redo_count = value.value();
            } else {
                args.memory_bytes = value.value();
            }
        } else if (key == "--no-canvas") {
            args.has_canvas = false;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_main_toolbar(int argc, char** argv)
{
    PlanMainToolbarArgs args;
    const auto status = parse_plan_main_toolbar_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-main-toolbar", status.message);
        return 2;
    }

    const auto command = parse_main_toolbar_command(args.command);
    if (!command) {
        print_error("plan-main-toolbar", command.status().message);
        return 2;
    }

    const auto plan = pp::app::plan_main_toolbar_command(
        command.value(),
        args.undo_count,
        args.redo_count,
        args.memory_bytes,
        args.has_canvas);
    if (!plan) {
        print_error("plan-main-toolbar", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-main-toolbar\""
              << ",\"state\":{\"command\":\"" << json_escape(args.command)
              << "\",\"undoCount\":" << args.undo_count
              << ",\"redoCount\":" << args.redo_count
              << ",\"memoryBytes\":" << args.memory_bytes
              << ",\"hasCanvas\":" << json_bool(args.has_canvas)
              << "},\"plan\":{\"command\":\"" << main_toolbar_command_name(value.command)
              << "\",\"action\":\"" << main_toolbar_action_name(value.action)
              << "\",\"label\":\"" << json_escape(value.label)
              << "\",\"requiresCanvas\":" << json_bool(value.requires_canvas)
              << ",\"updatesMemoryLabel\":" << json_bool(value.updates_memory_label)
              << ",\"updatesTitle\":" << json_bool(value.updates_title)
              << ",\"recordsUndo\":" << json_bool(value.records_undo)
              << ",\"marksUnsaved\":" << json_bool(value.marks_unsaved)
              << ",\"noOp\":" << json_bool(value.no_op);
    if (value.command == pp::app::MainToolbarCommand::show_message_box) {
        const auto dialog = pp::app::plan_main_toolbar_message_dialog();
        std::cout << ",\"messageDialog\":{\"title\":\"" << json_escape(dialog.title)
                  << "\",\"message\":\"" << json_escape(dialog.message)
                  << "\",\"okCaption\":\"" << json_escape(dialog.ok_caption)
                  << "\",\"cancelCaption\":\"" << json_escape(dialog.cancel_caption)
                  << "\",\"showCancel\":" << json_bool(dialog.show_cancel)
                  << "}";
    }
    std::cout << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_quick_operation_args(
    int argc,
    char** argv,
    PlanQuickOperationArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--kind") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.kind = argv[++i];
        } else if (key == "--current-index" || key == "--slot-index" || key == "--brush-index"
            || key == "--color-index" || key == "--slot-count") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_i32_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--current-index") {
                args.current_index = value.value();
            } else if (key == "--slot-index") {
                args.slot_index = value.value();
            } else if (key == "--brush-index") {
                args.brush_index = value.value();
            } else if (key == "--color-index") {
                args.color_index = value.value();
            } else {
                args.slot_count = value.value();
            }
        } else if (key == "--fire-event") {
            args.fire_event = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

pp::foundation::Result<pp::app::QuickUiPlan> make_quick_operation_plan(
    const PlanQuickOperationArgs& args)
{
    if (args.kind == "brush") {
        return pp::app::plan_quick_slot_click(
            pp::app::QuickUiSlotKind::brush,
            args.current_index,
            args.slot_index,
            args.slot_count);
    }
    if (args.kind == "color") {
        return pp::app::plan_quick_slot_click(
            pp::app::QuickUiSlotKind::color,
            args.current_index,
            args.slot_index,
            args.slot_count);
    }
    if (args.kind == "restore") {
        return pp::app::plan_quick_state_restore(
            args.brush_index,
            args.color_index,
            args.slot_count,
            args.fire_event);
    }
    if (args.kind == "reset") {
        return pp::app::plan_quick_state_reset(args.slot_count, args.fire_event);
    }

    return pp::foundation::Result<pp::app::QuickUiPlan>::failure(
        pp::foundation::Status::invalid_argument("unknown quick operation kind"));
}

int plan_quick_operation(int argc, char** argv)
{
    PlanQuickOperationArgs args;
    const auto status = parse_plan_quick_operation_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-quick-operation", status.message);
        return 2;
    }

    const auto plan = make_quick_operation_plan(args);
    if (!plan) {
        print_error("plan-quick-operation", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-quick-operation\""
              << ",\"state\":{\"kind\":\"" << json_escape(args.kind)
              << "\",\"currentIndex\":" << args.current_index
              << ",\"slotIndex\":" << args.slot_index
              << ",\"brushIndex\":" << args.brush_index
              << ",\"colorIndex\":" << args.color_index
              << ",\"slotCount\":" << args.slot_count
              << ",\"fireEvent\":" << json_bool(args.fire_event)
              << "},\"plan\":{\"operation\":\"" << quick_ui_operation_name(value.operation)
              << "\",\"slotKind\":\"" << quick_ui_slot_kind_name(value.slot_kind)
              << "\",\"slotIndex\":" << value.slot_index
              << ",\"previousIndex\":" << value.previous_index
              << ",\"brushIndex\":" << value.brush_index
              << ",\"colorIndex\":" << value.color_index
              << ",\"slotCount\":" << value.slot_count
              << ",\"fireEvent\":" << json_bool(value.fire_event)
              << ",\"updatesSelection\":" << json_bool(value.updates_selection)
              << ",\"opensBrushPopup\":" << json_bool(value.opens_brush_popup)
              << ",\"opensColorPicker\":" << json_bool(value.opens_color_picker)
              << ",\"invokesChangeCallback\":" << json_bool(value.invokes_change_callback)
              << ",\"restoresSlots\":" << json_bool(value.restores_slots)
              << ",\"resetsSlots\":" << json_bool(value.resets_slots)
              << ",\"redrawsBrushPreviews\":" << json_bool(value.redraws_brush_previews)
              << ",\"mutatesQuickState\":" << json_bool(value.mutates_quick_state)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_quick_slider_preview_args(
    int argc,
    char** argv,
    PlanQuickSliderPreviewArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--slider-x" || key == "--slider-y" || key == "--slider-height" || key == "--zoom") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const auto value = parse_float_arg(argv[++i]);
            if (!value) {
                return value.status();
            }
            if (key == "--slider-x") {
                args.slider_x = value.value();
            } else if (key == "--slider-y") {
                args.slider_y = value.value();
            } else if (key == "--slider-height") {
                args.slider_height = value.value();
            } else {
                args.zoom = value.value();
            }
        } else if (key == "--rtl") {
            args.rtl = true;
        } else if (key == "--pen-mode") {
            args.pen_mode = true;
        } else if (key == "--no-pen-mode") {
            args.pen_mode = false;
        } else if (key == "--line-mode") {
            args.line_mode = true;
        } else if (key == "--no-line-mode") {
            args.line_mode = false;
        } else if (key == "--bad-float") {
            args.bad_float = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_quick_slider_preview(int argc, char** argv)
{
    PlanQuickSliderPreviewArgs args;
    const auto status = parse_plan_quick_slider_preview_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-quick-slider-preview", status.message);
        return 2;
    }

    const auto plan = pp::app::plan_quick_slider_preview(pp::app::QuickSliderPreviewInput {
        .ui_rtl = args.rtl,
        .slider_x = args.bad_float ? std::nanf("") : args.slider_x,
        .slider_y = args.slider_y,
        .slider_height = args.slider_height,
        .zoom = args.zoom,
        .has_pen_mode = args.pen_mode,
        .has_line_mode = args.line_mode,
    });
    if (!plan) {
        print_error("plan-quick-slider-preview", plan.status().message);
        return 2;
    }

    const auto& value = plan.value();
    std::cout << "{\"ok\":true,\"command\":\"plan-quick-slider-preview\""
              << ",\"state\":{\"rtl\":" << json_bool(args.rtl)
              << ",\"sliderX\":" << args.slider_x
              << ",\"sliderY\":" << args.slider_y
              << ",\"sliderHeight\":" << args.slider_height
              << ",\"zoom\":" << args.zoom
              << ",\"penMode\":" << json_bool(args.pen_mode)
              << ",\"lineMode\":" << json_bool(args.line_mode)
              << "},\"plan\":{\"cursorX\":" << value.cursor_x
              << ",\"cursorY\":" << value.cursor_y
              << ",\"updatesPenMode\":" << json_bool(value.updates_pen_mode)
              << ",\"updatesLineMode\":" << json_bool(value.updates_line_mode)
              << ",\"drawsTip\":" << json_bool(value.draws_tip)
              << ",\"disablesPenOutline\":" << json_bool(value.disables_pen_outline)
              << ",\"redrawsBrushPreview\":" << json_bool(value.redraws_brush_preview)
              << ",\"invokesChangeCallback\":" << json_bool(value.invokes_change_callback)
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_plan_share_file_args(
    int argc,
    char** argv,
    PlanShareFileArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.path = argv[++i];
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_share_file(int argc, char** argv)
{
    PlanShareFileArgs args;
    const auto status = parse_plan_share_file_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-share-file", status.message);
        return 2;
    }

    const auto decision = pp::app::plan_document_share(args.path);
    std::cout << "{\"ok\":true,\"command\":\"plan-share-file\""
              << ",\"state\":{\"path\":\"" << json_escape(args.path)
              << "\"},\"decision\":\"" << document_share_action_name(decision)
              << "\"}\n";
    return 0;
}

pp::foundation::Status parse_plan_picked_path_args(
    int argc,
    char** argv,
    PlanPickedPathArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.path = argv[++i];
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_picked_path(int argc, char** argv)
{
    PlanPickedPathArgs args;
    const auto status = parse_plan_picked_path_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-picked-path", status.message);
        return 2;
    }

    const auto decision = pp::app::plan_picked_path(args.path);
    std::cout << "{\"ok\":true,\"command\":\"plan-picked-path\""
              << ",\"state\":{\"path\":\"" << json_escape(args.path)
              << "\"},\"decision\":\"" << picked_path_action_name(decision)
              << "\"}\n";
    return 0;
}

pp::foundation::Status parse_plan_display_file_args(
    int argc,
    char** argv,
    PlanDisplayFileArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.path = argv[++i];
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_display_file(int argc, char** argv)
{
    PlanDisplayFileArgs args;
    const auto status = parse_plan_display_file_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-display-file", status.message);
        return 2;
    }

    const auto decision = pp::app::plan_display_file(args.path);
    std::cout << "{\"ok\":true,\"command\":\"plan-display-file\""
              << ",\"state\":{\"path\":\"" << json_escape(args.path)
              << "\"},\"decision\":\"" << display_file_action_name(decision)
              << "\"}\n";
    return 0;
}

pp::foundation::Status parse_plan_keyboard_visibility_args(
    int argc,
    char** argv,
    PlanKeyboardVisibilityArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--visible") {
            args.visible = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_keyboard_visibility(int argc, char** argv)
{
    PlanKeyboardVisibilityArgs args;
    const auto status = parse_plan_keyboard_visibility_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-keyboard-visibility", status.message);
        return 2;
    }

    const auto decision = pp::app::plan_virtual_keyboard(args.visible);
    std::cout << "{\"ok\":true,\"command\":\"plan-keyboard-visibility\""
              << ",\"state\":{\"visible\":" << json_bool(args.visible)
              << "},\"decision\":\"" << virtual_keyboard_action_name(decision)
              << "\"}\n";
    return 0;
}

pp::foundation::Status parse_plan_cursor_visibility_args(
    int argc,
    char** argv,
    PlanCursorVisibilityArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--visible") {
            args.visible = true;
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_cursor_visibility(int argc, char** argv)
{
    PlanCursorVisibilityArgs args;
    const auto status = parse_plan_cursor_visibility_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-cursor-visibility", status.message);
        return 2;
    }

    const auto decision = pp::app::plan_cursor_visibility(args.visible);
    std::cout << "{\"ok\":true,\"command\":\"plan-cursor-visibility\""
              << ",\"state\":{\"visible\":" << json_bool(args.visible)
              << "},\"decision\":\"" << cursor_visibility_action_name(decision)
              << "\"}\n";
    return 0;
}

int plan_clipboard_read(int, char**)
{
    const auto decision = pp::app::plan_clipboard_read();
    std::cout << "{\"ok\":true,\"command\":\"plan-clipboard-read\""
              << ",\"decision\":\"" << clipboard_read_action_name(decision)
              << "\"}\n";
    return 0;
}

pp::foundation::Status parse_plan_clipboard_write_args(
    int argc,
    char** argv,
    PlanClipboardWriteArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--text") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            args.text = argv[++i];
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int plan_clipboard_write(int argc, char** argv)
{
    PlanClipboardWriteArgs args;
    const auto status = parse_plan_clipboard_write_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-clipboard-write", status.message);
        return 2;
    }

    const auto decision = pp::app::plan_clipboard_write(args.text);
    std::cout << "{\"ok\":true,\"command\":\"plan-clipboard-write\""
              << ",\"state\":{\"text\":\"" << json_escape(args.text)
              << "\"},\"decision\":\"" << clipboard_write_action_name(decision)
              << "\"}\n";
    return 0;
}

pp::foundation::Status parse_plan_export_target_args(
    int argc,
    char** argv,
    PlanExportTargetArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        auto read_value = [&](std::string& output) -> pp::foundation::Status {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            output = argv[++i];
            return pp::foundation::Status::success();
        };

        if (key == "--kind") {
            const auto status = read_value(args.kind);
            if (!status.ok()) {
                return status;
            }
        } else if (key == "--work-dir") {
            const auto status = read_value(args.work_directory);
            if (!status.ok()) {
                return status;
            }
        } else if (key == "--directory") {
            const auto status = read_value(args.directory);
            if (!status.ok()) {
                return status;
            }
        } else if (key == "--doc-name") {
            const auto status = read_value(args.document_name);
            if (!status.ok()) {
                return status;
            }
        } else if (key == "--extension") {
            const auto status = read_value(args.extension);
            if (!status.ok()) {
                return status;
            }
        } else if (key == "--suffix") {
            const auto status = read_value(args.suffix);
            if (!status.ok()) {
                return status;
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.kind.empty()) {
        return pp::foundation::Status::invalid_argument("kind must not be empty");
    }

    if (args.document_name.empty()) {
        return pp::foundation::Status::invalid_argument("document name must not be empty");
    }

    if ((args.kind == "file" || args.kind == "collection" || args.kind == "cube-faces")
        && args.work_directory.empty()) {
        return pp::foundation::Status::invalid_argument("work directory must not be empty");
    }

    if (args.kind == "stem" && args.directory.empty()) {
        return pp::foundation::Status::invalid_argument("directory must not be empty");
    }

    if (args.kind == "file" && args.extension.empty()) {
        return pp::foundation::Status::invalid_argument("extension must not be empty");
    }

    if ((args.kind == "collection" || args.kind == "name") && args.suffix.empty()) {
        return pp::foundation::Status::invalid_argument("suffix must not be empty");
    }

    if (args.kind != "file" && args.kind != "collection" && args.kind != "stem"
        && args.kind != "cube-faces" && args.kind != "name") {
        return pp::foundation::Status::invalid_argument("unknown export target kind");
    }

    return pp::foundation::Status::success();
}

int plan_export_target(int argc, char** argv)
{
    PlanExportTargetArgs args;
    const auto status = parse_plan_export_target_args(argc, argv, args);
    if (!status.ok()) {
        print_error("plan-export-target", status.message);
        return 2;
    }

    if (args.kind == "file") {
        const auto target = pp::app::make_document_export_file_target(
            args.work_directory,
            args.document_name,
            args.extension);
        if (!target) {
            print_error("plan-export-target", target.status().message);
            return 2;
        }

        std::cout << "{\"ok\":true,\"command\":\"plan-export-target\""
                  << ",\"kind\":\"file\",\"target\":{\"path\":\"" << json_escape(target.value().path)
                  << "\",\"suggestedName\":\"" << json_escape(target.value().suggested_name)
                  << "\"}}\n";
        return 0;
    }

    if (args.kind == "collection") {
        const auto target = pp::app::make_document_export_collection_target(
            args.work_directory,
            args.document_name,
            args.suffix);
        if (!target) {
            print_error("plan-export-target", target.status().message);
            return 2;
        }

        std::cout << "{\"ok\":true,\"command\":\"plan-export-target\""
                  << ",\"kind\":\"collection\",\"target\":{\"directory\":\"" << json_escape(target.value().directory)
                  << "\",\"stemPath\":\"" << json_escape(target.value().stem_path)
                  << "\"}}\n";
        return 0;
    }

    if (args.kind == "stem") {
        const auto target = pp::app::make_document_export_stem_target(args.directory, args.document_name);
        if (!target) {
            print_error("plan-export-target", target.status().message);
            return 2;
        }

        std::cout << "{\"ok\":true,\"command\":\"plan-export-target\""
                  << ",\"kind\":\"stem\",\"target\":{\"stemPath\":\"" << json_escape(target.value().stem_path)
                  << "\"}}\n";
        return 0;
    }

    if (args.kind == "cube-faces") {
        const auto target = pp::app::make_document_cube_face_export_target(
            args.work_directory,
            args.document_name);
        if (!target) {
            print_error("plan-export-target", target.status().message);
            return 2;
        }

        std::cout << "{\"ok\":true,\"command\":\"plan-export-target\""
                  << ",\"kind\":\"cube-faces\",\"target\":{\"faceCount\":" << target.value().face_count
                  << ",\"faces\":[";
        for (std::size_t face_index = 0; face_index < target.value().face_count; ++face_index) {
            if (face_index != 0U) {
                std::cout << ",";
            }
            const auto& face = target.value().faces[face_index];
            std::cout << "{\"name\":\"" << json_escape(face.face_name)
                      << "\",\"path\":\"" << json_escape(face.path)
                      << "\"}";
        }
        std::cout << "]}}\n";
        return 0;
    }

    const auto target = pp::app::make_document_export_suggested_name(args.document_name, args.suffix);
    if (!target) {
        print_error("plan-export-target", target.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"plan-export-target\""
              << ",\"kind\":\"name\",\"target\":{\"suggestedName\":\"" << json_escape(target.value().name)
              << "\"}}\n";
    return 0;
}

pp::foundation::Status parse_simulate_app_session_args(
    int argc,
    char** argv,
    SimulateAppSessionArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--new-document") {
            args.new_document = true;
        } else if (key == "--no-canvas") {
            args.has_canvas = false;
        } else if (key == "--unsaved") {
            args.unsaved = true;
        } else if (key == "--close-prompt-open") {
            args.close_prompt_open = true;
        } else if (key == "--save-intent") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }
            const std::string_view value(argv[++i]);
            if (value == "save") {
                args.save_intent = pp::app::DocumentSaveIntent::save;
            } else if (value == "save-as") {
                args.save_intent = pp::app::DocumentSaveIntent::save_as;
            } else if (value == "save-version") {
                args.save_intent = pp::app::DocumentSaveIntent::save_version;
            } else if (value == "save-dirty-version") {
                args.save_intent = pp::app::DocumentSaveIntent::save_dirty_version;
            } else {
                return pp::foundation::Status::invalid_argument("unknown save intent");
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    return pp::foundation::Status::success();
}

int simulate_app_session(int argc, char** argv)
{
    SimulateAppSessionArgs args;
    const auto status = parse_simulate_app_session_args(argc, argv, args);
    if (!status.ok()) {
        print_error("simulate-app-session", status.message);
        return 2;
    }

    const auto open_decision = pp::app::plan_project_open(args.unsaved);
    const auto close_decision = pp::app::plan_close_request(args.unsaved, args.close_prompt_open);
    const auto save_decision = pp::app::plan_document_save(
        args.new_document,
        args.unsaved,
        args.save_intent);
    const auto workflow_decision = pp::app::plan_document_workflow(args.has_canvas, args.unsaved);
    std::cout << "{\"ok\":true,\"command\":\"simulate-app-session\""
              << ",\"state\":{\"hasCanvas\":" << json_bool(args.has_canvas)
              << ",\"newDocument\":" << json_bool(args.new_document)
              << ",\"unsaved\":" << json_bool(args.unsaved)
              << ",\"closePromptOpen\":" << json_bool(args.close_prompt_open)
              << "},\"decisions\":{\"projectOpen\":\""
              << project_open_decision_name(open_decision)
              << "\",\"closeRequest\":\""
              << close_request_decision_name(close_decision)
              << "\",\"saveIntent\":\""
              << document_save_intent_name(args.save_intent)
              << "\",\"saveRequest\":\""
              << document_save_decision_name(save_decision)
              << "\",\"workflowStart\":\""
              << document_workflow_decision_name(workflow_decision)
              << "\"}}\n";
    return 0;
}

int inspect_project(int argc, char** argv)
{
    InspectProjectArgs args;
    const auto status = parse_inspect_project_args(argc, argv, args);
    if (!status.ok()) {
        print_error("inspect-project", status.message);
        return 2;
    }

    std::ifstream stream(args.path, std::ios::binary);
    if (!stream) {
        print_error("inspect-project", "project file could not be opened");
        return 2;
    }

    const std::vector<char> chars {
        std::istreambuf_iterator<char>(stream),
        std::istreambuf_iterator<char>()
    };
    const auto* data = reinterpret_cast<const std::byte*>(chars.data());
    const auto project = pp::assets::parse_ppi_project_index(std::span<const std::byte>(data, chars.size()));
    if (!project) {
        print_error("inspect-project", project.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"inspect-project\""
              << ",\"documentVersion\":\"" << project.value().layout.header.document_version.major
              << "." << project.value().layout.header.document_version.minor << "\""
              << ",\"softwareVersion\":\"" << project.value().layout.header.software_version.major
              << "." << project.value().layout.header.software_version.minor
              << "." << project.value().layout.header.software_version.fix
              << "." << project.value().layout.header.software_version.build << "\""
              << ",\"thumbnail\":{\"width\":" << project.value().layout.header.thumbnail.width
              << ",\"height\":" << project.value().layout.header.thumbnail.height
              << ",\"components\":" << project.value().layout.header.thumbnail.components
              << ",\"bytes\":" << project.value().layout.thumbnail_bytes
              << "},\"body\":{\"offset\":" << project.value().layout.body_offset
              << ",\"bytes\":" << project.value().layout.body_bytes
              << ",\"width\":" << project.value().body.summary.width
              << ",\"height\":" << project.value().body.summary.height
              << ",\"layers\":" << project.value().body.summary.layer_count
              << ",\"frames\":" << project.value().body.summary.declared_frame_count
              << ",\"dirtyFaces\":" << project.value().body.summary.dirty_face_count
              << ",\"rgbaFacePayloads\":" << project.value().body.summary.rgba_face_payload_count
              << ",\"compressedBytes\":" << project.value().body.summary.compressed_face_bytes
              << ",\"infoBytes\":" << project.value().body.summary.info_bytes
              << "},\"layers\":[";
    for (std::size_t layer_index = 0; layer_index < project.value().body.layers.size(); ++layer_index) {
        const auto& layer = project.value().body.layers[layer_index];
        if (layer_index != 0U) {
            std::cout << ",";
        }
        std::cout << "{\"index\":" << layer_index
                  << ",\"storedOrder\":" << layer.stored_order
                  << ",\"name\":\"" << json_escape(layer.name) << "\""
                  << ",\"opacity\":" << layer.opacity
                  << ",\"blendMode\":" << layer.blend_mode
                  << ",\"alphaLocked\":" << (layer.alpha_locked ? "true" : "false")
                  << ",\"visible\":" << (layer.visible ? "true" : "false")
                  << ",\"frames\":[";
        for (std::size_t frame_index = 0; frame_index < layer.frames.size(); ++frame_index) {
            const auto& frame = layer.frames[frame_index];
            if (frame_index != 0U) {
                std::cout << ",";
            }
            std::cout << "{\"index\":" << frame_index
                      << ",\"durationMs\":" << frame.duration_ms
                      << ",\"dirtyFaces\":[";
            bool first_face = true;
            for (std::size_t face_index = 0; face_index < frame.faces.size(); ++face_index) {
                const auto& face = frame.faces[face_index];
                if (!face.has_data) {
                    continue;
                }
                if (!first_face) {
                    std::cout << ",";
                }
                first_face = false;
                std::cout << "{\"face\":" << face_index
                          << ",\"box\":[" << face.x0 << "," << face.y0 << "," << face.x1 << "," << face.y1 << "]"
                          << ",\"bodyPayloadOffset\":" << face.body_payload_offset
                          << ",\"bytes\":" << face.payload_bytes
                          << ",\"png\":{\"width\":" << face.png_width
                          << ",\"height\":" << face.png_height
                          << "}}";
            }
            std::cout << "]}";
        }
        std::cout << "]}";
    }
    std::cout << "]}\n";
    return 0;
}

int load_project(int argc, char** argv)
{
    InspectProjectArgs args;
    const auto status = parse_inspect_project_args(argc, argv, args);
    if (!status.ok()) {
        print_error("load-project", status.message);
        return 2;
    }

    std::ifstream stream(args.path, std::ios::binary);
    if (!stream) {
        print_error("load-project", "project file could not be opened");
        return 2;
    }

    const std::string chars {
        std::istreambuf_iterator<char>(stream),
        std::istreambuf_iterator<char>()
    };
    const auto* data = reinterpret_cast<const std::byte*>(chars.data());
    const auto project = pp::assets::decode_ppi_project_images(std::span<const std::byte>(data, chars.size()));
    if (!project) {
        print_error("load-project", project.status().message);
        return 2;
    }

    const auto document_result = pp::document::import_ppi_project_document(project.value());
    if (!document_result) {
        print_error("load-project", document_result.status().message);
        return 2;
    }

    const auto& document = document_result.value();
    std::cout << "{\"ok\":true,\"command\":\"load-project\""
              << ",\"source\":\"ppi\""
              << ",\"pixelDataLoaded\":" << (document.face_pixel_payload_count() > 0U ? "true" : "false")
              << ",\"facePayloads\":" << document.face_pixel_payload_count()
              << ",\"document\":{\"width\":" << document.width()
              << ",\"height\":" << document.height()
              << ",\"layers\":" << document.layers().size()
              << ",\"frames\":" << document.frames().size()
              << ",\"animationDurationMs\":" << document.animation_duration_ms()
              << ",\"layerNames\":[";
    for (std::size_t layer_index = 0; layer_index < document.layers().size(); ++layer_index) {
        if (layer_index != 0U) {
            std::cout << ",";
        }
        std::cout << "\"" << json_escape(document.layers()[layer_index].name) << "\"";
    }
    std::cout << "],\"layerFrameCounts\":[";
    for (std::size_t layer_index = 0; layer_index < document.layers().size(); ++layer_index) {
        if (layer_index != 0U) {
            std::cout << ",";
        }
        std::cout << document.layers()[layer_index].frames.size();
    }
    std::cout << "],\"layerDurationsMs\":[";
    for (std::size_t layer_index = 0; layer_index < document.layers().size(); ++layer_index) {
        if (layer_index != 0U) {
            std::cout << ",";
        }
        const auto duration = document.layer_animation_duration_ms(layer_index);
        std::cout << (duration ? duration.value() : 0U);
    }
    std::cout << "],\"layerOpacities\":[";
    for (std::size_t layer_index = 0; layer_index < document.layers().size(); ++layer_index) {
        if (layer_index != 0U) {
            std::cout << ",";
        }
        std::cout << document.layers()[layer_index].opacity;
    }
    std::cout << "],\"layerBlendModes\":[";
    for (std::size_t layer_index = 0; layer_index < document.layers().size(); ++layer_index) {
        if (layer_index != 0U) {
            std::cout << ",";
        }
        std::cout << "\"" << pp::paint::blend_mode_name(document.layers()[layer_index].blend_mode) << "\"";
    }
    std::cout << "],\"layerAlphaLocked\":[";
    for (std::size_t layer_index = 0; layer_index < document.layers().size(); ++layer_index) {
        if (layer_index != 0U) {
            std::cout << ",";
        }
        std::cout << (document.layers()[layer_index].alpha_locked ? "true" : "false");
    }
    std::cout << "],\"layerVisible\":[";
    for (std::size_t layer_index = 0; layer_index < document.layers().size(); ++layer_index) {
        if (layer_index != 0U) {
            std::cout << ",";
        }
        std::cout << (document.layers()[layer_index].visible ? "true" : "false");
    }
    std::cout << "]}}\n";
    return 0;
}

pp::foundation::Status parse_simulate_stroke_args(int argc, char** argv, SimulateStrokeArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--x1" || key == "--y1" || key == "--x2" || key == "--y2" || key == "--spacing") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }

            if (key == "--x1") {
                args.x1 = value.value();
            } else if (key == "--y1") {
                args.y1 = value.value();
            } else if (key == "--x2") {
                args.x2 = value.value();
            } else if (key == "--y2") {
                args.y2 = value.value();
            } else {
                args.spacing = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.spacing == 0) {
        return pp::foundation::Status::invalid_argument("stroke spacing must be greater than zero");
    }

    return pp::foundation::Status::success();
}

int simulate_stroke(int argc, char** argv)
{
    SimulateStrokeArgs args;
    const auto status = parse_simulate_stroke_args(argc, argv, args);
    if (!status.ok()) {
        print_error("simulate-stroke", status.message);
        return 2;
    }

    const pp::paint::StrokePoint points[] {
        pp::paint::StrokePoint {
            .x = static_cast<float>(args.x1),
            .y = static_cast<float>(args.y1),
            .pressure = 1.0F,
        },
        pp::paint::StrokePoint {
            .x = static_cast<float>(args.x2),
            .y = static_cast<float>(args.y2),
            .pressure = 1.0F,
        },
    };
    const auto samples = pp::paint::sample_stroke(
        points,
        pp::paint::StrokeSamplingConfig {
            .spacing = static_cast<float>(args.spacing),
        });
    if (!samples) {
        print_error("simulate-stroke", samples.status().message);
        return 2;
    }

    const auto& first = samples.value().front();
    const auto& last = samples.value().back();
    std::cout << "{\"ok\":true,\"command\":\"simulate-stroke\""
              << ",\"samples\":" << samples.value().size()
              << ",\"first\":{\"x\":" << first.x << ",\"y\":" << first.y << "}"
              << ",\"last\":{\"x\":" << last.x << ",\"y\":" << last.y
              << ",\"distance\":" << last.distance << "}}\n";
    return 0;
}

pp::foundation::Status parse_simulate_stroke_script_args(int argc, char** argv, SimulateStrokeScriptArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            args.path = argv[++i];
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.path.empty()) {
        return pp::foundation::Status::invalid_argument("path must not be empty");
    }

    return pp::foundation::Status::success();
}

int simulate_stroke_script(int argc, char** argv)
{
    SimulateStrokeScriptArgs args;
    const auto status = parse_simulate_stroke_script_args(argc, argv, args);
    if (!status.ok()) {
        print_error("simulate-stroke-script", status.message);
        return 2;
    }

    std::ifstream stream(args.path, std::ios::binary);
    if (!stream) {
        print_error("simulate-stroke-script", "stroke script file could not be opened");
        return 2;
    }

    const std::string text {
        std::istreambuf_iterator<char>(stream),
        std::istreambuf_iterator<char>()
    };
    const auto script = pp::paint::parse_stroke_script(text);
    if (!script) {
        print_error("simulate-stroke-script", script.status().message);
        return 2;
    }

    std::size_t total_samples = 0;
    float total_distance = 0.0F;
    for (const auto& stroke : script.value().strokes) {
        const pp::paint::StrokePoint points[] { stroke.start, stroke.end };
        const auto samples = pp::paint::sample_stroke(
            points,
            pp::paint::StrokeSamplingConfig {
                .spacing = stroke.spacing,
            });
        if (!samples) {
            print_error("simulate-stroke-script", samples.status().message);
            return 2;
        }

        total_samples += samples.value().size();
        total_distance += samples.value().back().distance;
    }

    std::cout << "{\"ok\":true,\"command\":\"simulate-stroke-script\""
              << ",\"strokes\":" << script.value().strokes.size()
              << ",\"samples\":" << total_samples
              << ",\"distance\":" << total_distance << "}\n";
    return 0;
}

int simulate_blend(int argc, char**)
{
    if (argc > 2) {
        print_error("simulate-blend", "unknown option");
        return 2;
    }

    const auto normal = pp::paint::blend_pixels(
        pp::paint::Rgba { .r = 0.2F, .g = 0.4F, .b = 0.6F, .a = 0.5F },
        pp::paint::Rgba { .r = 0.8F, .g = 0.2F, .b = 0.1F, .a = 0.25F },
        pp::paint::BlendMode::normal);
    const auto multiply = pp::paint::blend_pixels(
        pp::paint::Rgba { .r = 0.25F, .g = 0.5F, .b = 0.75F, .a = 1.0F },
        pp::paint::Rgba { .r = 0.5F, .g = 0.5F, .b = 0.5F, .a = 1.0F },
        pp::paint::BlendMode::multiply);
    const auto stroke_normal = pp::paint::blend_stroke_alpha(
        0.2F,
        0.8F,
        0.25F,
        pp::paint::StrokeBlendMode::normal);
    const auto stroke_linear_height = pp::paint::blend_stroke_alpha(
        0.5F,
        0.25F,
        0.16F,
        pp::paint::StrokeBlendMode::linear_height);
    const auto stroke_height = pp::paint::blend_stroke_alpha(
        0.5F,
        0.25F,
        0.16F,
        pp::paint::StrokeBlendMode::height);
    const auto stroke_unknown = pp::paint::blend_stroke_alpha(
        0.2F,
        0.2F,
        0.5F,
        static_cast<pp::paint::StrokeBlendMode>(255));

    std::cout << "{\"ok\":true,\"command\":\"simulate-blend\""
              << ",\"finalBlendModes\":5"
              << ",\"strokeBlendModes\":11"
              << ",\"normal\":{\"r\":" << normal.r
              << ",\"g\":" << normal.g
              << ",\"b\":" << normal.b
              << ",\"a\":" << normal.a
              << "}"
              << ",\"multiply\":{\"r\":" << multiply.r
              << ",\"g\":" << multiply.g
              << ",\"b\":" << multiply.b
              << ",\"a\":" << multiply.a
              << "}"
              << ",\"stroke\":{\"normal\":" << stroke_normal
              << ",\"linearHeight\":" << stroke_linear_height
              << ",\"height\":" << stroke_height
              << ",\"unknown\":" << stroke_unknown
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_apply_stroke_script_args(int argc, char** argv, ApplyStrokeScriptArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--path" || key == "--output") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            if (key == "--path") {
                args.path = argv[++i];
            } else {
                args.output_path = argv[++i];
            }
        } else if (key == "--width" || key == "--height") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }

            if (key == "--width") {
                args.width = value.value();
            } else {
                args.height = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.path.empty() || args.output_path.empty()) {
        return pp::foundation::Status::invalid_argument("path and output must not be empty");
    }

    if (args.width < 8 || args.height < 8 || args.width > 4096 || args.height > 4096) {
        return pp::foundation::Status::out_of_range("width and height must be between 8 and 4096");
    }

    return pp::foundation::Status::success();
}

std::uint8_t pressure_to_alpha(float pressure) noexcept
{
    const auto normalized = std::clamp(pressure, 0.0F, 1.0F);
    const auto alpha = static_cast<int>(std::lround(normalized * 255.0F));
    return static_cast<std::uint8_t>(std::clamp(alpha, 1, 255));
}

std::uint32_t clamp_sample_coordinate(float value, std::uint32_t limit) noexcept
{
    if (limit == 0U) {
        return 0;
    }

    const auto rounded = static_cast<int>(std::lround(value));
    const auto clamped = std::clamp(rounded, 0, static_cast<int>(limit - 1U));
    return static_cast<std::uint32_t>(clamped);
}

int apply_stroke_script(int argc, char** argv)
{
    ApplyStrokeScriptArgs args;
    const auto status = parse_apply_stroke_script_args(argc, argv, args);
    if (!status.ok()) {
        print_error("apply-stroke-script", status.message);
        return 2;
    }

    std::ifstream script_stream(args.path, std::ios::binary);
    if (!script_stream) {
        print_error("apply-stroke-script", "stroke script file could not be opened");
        return 2;
    }

    const std::string text {
        std::istreambuf_iterator<char>(script_stream),
        std::istreambuf_iterator<char>()
    };
    const auto script = pp::paint::parse_stroke_script(text);
    if (!script) {
        print_error("apply-stroke-script", script.status().message);
        return 2;
    }

    struct AppliedPoint {
        std::uint32_t x = 0;
        std::uint32_t y = 0;
        std::uint32_t stroke_index = 0;
        float pressure = 1.0F;
    };

    std::vector<AppliedPoint> applied_points;
    std::vector<std::size_t> samples_per_stroke;
    std::size_t total_samples = 0;
    float total_distance = 0.0F;
    std::uint32_t x0 = args.width;
    std::uint32_t y0 = args.height;
    std::uint32_t x1 = 0;
    std::uint32_t y1 = 0;

    for (std::size_t stroke_index = 0; stroke_index < script.value().strokes.size(); ++stroke_index) {
        const auto& stroke = script.value().strokes[stroke_index];
        const pp::paint::StrokePoint points[] { stroke.start, stroke.end };
        const auto samples = pp::paint::sample_stroke(
            points,
            pp::paint::StrokeSamplingConfig {
                .spacing = stroke.spacing,
            });
        if (!samples) {
            print_error("apply-stroke-script", samples.status().message);
            return 2;
        }

        samples_per_stroke.push_back(samples.value().size());
        total_samples += samples.value().size();
        total_distance += samples.value().back().distance;
        for (const auto& sample : samples.value()) {
            const auto x = clamp_sample_coordinate(sample.x, args.width);
            const auto y = clamp_sample_coordinate(sample.y, args.height);
            x0 = std::min(x0, x);
            y0 = std::min(y0, y);
            x1 = std::max(x1, x);
            y1 = std::max(y1, y);
            applied_points.push_back(AppliedPoint {
                .x = x,
                .y = y,
                .stroke_index = static_cast<std::uint32_t>(stroke_index),
                .pressure = sample.pressure,
            });
        }
    }

    if (applied_points.empty()) {
        print_error("apply-stroke-script", "stroke script produced no samples");
        return 2;
    }

    const auto payload_width = x1 - x0 + 1U;
    const auto payload_height = y1 - y0 + 1U;
    std::vector<std::uint8_t> rgba8(
        static_cast<std::size_t>(payload_width) * payload_height * pp::document::rgba8_components,
        0);
    for (std::size_t point_index = 0; point_index < applied_points.size(); ++point_index) {
        const auto& point = applied_points[point_index];
        const auto local_x = point.x - x0;
        const auto local_y = point.y - y0;
        const auto pixel_index = (static_cast<std::size_t>(local_y) * payload_width + local_x)
            * pp::document::rgba8_components;
        rgba8[pixel_index + 0U] = static_cast<std::uint8_t>(64U + ((point.stroke_index * 53U) % 192U));
        rgba8[pixel_index + 1U] = static_cast<std::uint8_t>((point_index * 31U) % 256U);
        rgba8[pixel_index + 2U] = static_cast<std::uint8_t>(255U - ((point.stroke_index * 29U) % 192U));
        rgba8[pixel_index + 3U] = pressure_to_alpha(point.pressure);
    }

    const auto document_result = pp::document::CanvasDocument::create(
        pp::document::DocumentConfig {
            .width = args.width,
            .height = args.height,
            .layer_count = 1,
        });
    if (!document_result) {
        print_error("apply-stroke-script", document_result.status().message);
        return 2;
    }

    auto document = document_result.value();
    auto edit_status = document.rename_layer(0, "Stroke Script");
    if (!edit_status.ok()) {
        print_error("apply-stroke-script", edit_status.message);
        return 2;
    }

    edit_status = document.set_layer_frame_face_pixels(
        0,
        0,
        pp::document::LayerFacePixels {
            .face_index = 0,
            .x = x0,
            .y = y0,
            .width = payload_width,
            .height = payload_height,
            .rgba8 = std::move(rgba8),
        });
    if (!edit_status.ok()) {
        print_error("apply-stroke-script", edit_status.message);
        return 2;
    }

    const auto exported = pp::document::export_ppi_project_document(document);
    if (!exported) {
        print_error("apply-stroke-script", exported.status().message);
        return 2;
    }

    std::ofstream output_stream(args.output_path, std::ios::binary);
    if (!output_stream) {
        print_error("apply-stroke-script", "project file could not be opened for writing");
        return 2;
    }

    const auto& bytes = exported.value();
    output_stream.write(reinterpret_cast<const char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()));
    if (!output_stream) {
        print_error("apply-stroke-script", "project file could not be written");
        return 2;
    }

    const auto decoded = pp::assets::decode_ppi_project_images(bytes);
    if (!decoded) {
        print_error("apply-stroke-script", decoded.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"apply-stroke-script\""
              << ",\"path\":\"" << json_escape(args.path) << "\""
              << ",\"output\":\"" << json_escape(args.output_path) << "\""
              << ",\"strokes\":" << script.value().strokes.size()
              << ",\"samples\":" << total_samples
              << ",\"distance\":" << total_distance
              << ",\"samplesPerStroke\":[";
    for (std::size_t stroke_index = 0; stroke_index < samples_per_stroke.size(); ++stroke_index) {
        if (stroke_index != 0U) {
            std::cout << ",";
        }
        std::cout << samples_per_stroke[stroke_index];
    }
    std::cout << "],\"document\":{\"width\":" << document.width()
              << ",\"height\":" << document.height()
              << ",\"layers\":" << document.layers().size()
              << ",\"frames\":" << document.frames().size()
              << ",\"facePayloads\":" << document.face_pixel_payload_count()
              << "},\"payload\":{\"face\":0"
              << ",\"box\":[" << x0 << "," << y0 << "," << (x1 + 1U) << "," << (y1 + 1U) << "]"
              << ",\"width\":" << payload_width
              << ",\"height\":" << payload_height
              << ",\"bytes\":" << document.layers()[0].frames[0].face_pixels[0].rgba8.size()
              << "},\"export\":{\"bytes\":" << bytes.size()
              << ",\"dirtyFaces\":" << decoded.value().project.body.summary.dirty_face_count
              << ",\"rgbaFacePayloads\":" << decoded.value().project.body.summary.rgba_face_payload_count
              << ",\"compressedBytes\":" << decoded.value().project.body.summary.compressed_face_bytes
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_simulate_document_edits_args(
    int argc,
    char** argv,
    SimulateDocumentEditsArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--width" || key == "--height") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }

            if (key == "--width") {
                args.width = value.value();
            } else {
                args.height = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.width == 0 || args.height == 0) {
        return pp::foundation::Status::invalid_argument("width and height must be greater than zero");
    }

    const auto render_target_size = pp::renderer::texture_byte_size(pp::renderer::TextureDesc {
        .extent = pp::renderer::Extent2D { .width = args.width, .height = args.height },
        .format = pp::renderer::TextureFormat::rgba8,
        .usage = pp::renderer::TextureUsage::render_target | pp::renderer::TextureUsage::sampled | pp::renderer::TextureUsage::upload_destination | pp::renderer::TextureUsage::readback_source | pp::renderer::TextureUsage::copy_source | pp::renderer::TextureUsage::copy_destination,
        .debug_name = "record-render-texture",
    });
    if (!render_target_size) {
        return render_target_size.status();
    }

    return pp::foundation::Status::success();
}

int simulate_document_edits(int argc, char** argv)
{
    SimulateDocumentEditsArgs args;
    const auto status = parse_simulate_document_edits_args(argc, argv, args);
    if (!status.ok()) {
        print_error("simulate-document-edits", status.message);
        return 2;
    }

    const auto document_result = pp::document::CanvasDocument::create(
        pp::document::DocumentConfig {
            .width = args.width,
            .height = args.height,
            .layer_count = 1,
        });
    if (!document_result) {
        print_error("simulate-document-edits", document_result.status().message);
        return 2;
    }

    auto document = document_result.value();
    auto edit_status = document.set_frame_duration(0, 100);
    if (!edit_status.ok()) {
        print_error("simulate-document-edits", edit_status.message);
        return 2;
    }

    const auto layer_result = document.add_layer("Paint");
    if (!layer_result) {
        print_error("simulate-document-edits", layer_result.status().message);
        return 2;
    }

    const std::size_t paint_layer = layer_result.value();
    edit_status = document.rename_layer(paint_layer, "Ink");
    if (!edit_status.ok()) {
        print_error("simulate-document-edits", edit_status.message);
        return 2;
    }
    edit_status = document.set_layer_visible(paint_layer, false);
    if (!edit_status.ok()) {
        print_error("simulate-document-edits", edit_status.message);
        return 2;
    }
    edit_status = document.set_layer_alpha_locked(paint_layer, true);
    if (!edit_status.ok()) {
        print_error("simulate-document-edits", edit_status.message);
        return 2;
    }
    edit_status = document.set_layer_opacity(paint_layer, 0.625F);
    if (!edit_status.ok()) {
        print_error("simulate-document-edits", edit_status.message);
        return 2;
    }
    edit_status = document.set_layer_blend_mode(paint_layer, pp::paint::BlendMode::overlay);
    if (!edit_status.ok()) {
        print_error("simulate-document-edits", edit_status.message);
        return 2;
    }
    edit_status = document.set_active_layer(paint_layer);
    if (!edit_status.ok()) {
        print_error("simulate-document-edits", edit_status.message);
        return 2;
    }

    const auto duplicated_frame = document.duplicate_frame(0);
    if (!duplicated_frame) {
        print_error("simulate-document-edits", duplicated_frame.status().message);
        return 2;
    }
    edit_status = document.set_frame_duration(duplicated_frame.value(), 333);
    if (!edit_status.ok()) {
        print_error("simulate-document-edits", edit_status.message);
        return 2;
    }

    const auto added_frame = document.add_frame(250);
    if (!added_frame) {
        print_error("simulate-document-edits", added_frame.status().message);
        return 2;
    }
    edit_status = document.move_frame(added_frame.value(), 0);
    if (!edit_status.ok()) {
        print_error("simulate-document-edits", edit_status.message);
        return 2;
    }
    edit_status = document.move_layer(paint_layer, 0);
    if (!edit_status.ok()) {
        print_error("simulate-document-edits", edit_status.message);
        return 2;
    }

    edit_status = document.set_layer_frame_face_pixels(
        0,
        0,
        pp::document::LayerFacePixels {
            .face_index = 2,
            .x = 1,
            .y = 2,
            .width = 1,
            .height = 1,
            .rgba8 = { 255, 0, 0, 255 },
        });
    if (!edit_status.ok()) {
        print_error("simulate-document-edits", edit_status.message);
        return 2;
    }

    edit_status = document.set_selection_mask(pp::document::SelectionMask {
        .face_index = 4,
        .x = 3,
        .y = 5,
        .width = 2,
        .height = 2,
        .alpha8 = { 0, 64, 128, 255 },
    });
    if (!edit_status.ok()) {
        print_error("simulate-document-edits", edit_status.message);
        return 2;
    }

    const auto& active_layer = document.layers()[document.active_layer_index()];
    const auto& selection_mask = document.selection_masks()[0];
    std::cout << "{\"ok\":true,\"command\":\"simulate-document-edits\""
              << ",\"document\":{\"width\":" << document.width()
              << ",\"height\":" << document.height()
              << ",\"layers\":" << document.layers().size()
              << ",\"frames\":" << document.frames().size()
              << ",\"activeLayer\":" << document.active_layer_index()
              << ",\"activeFrame\":" << document.active_frame_index()
              << ",\"animationDurationMs\":" << document.animation_duration_ms()
              << ",\"facePayloads\":" << document.face_pixel_payload_count()
              << ",\"selectionMasks\":" << document.selection_mask_payload_count()
              << "},\"activeLayer\":{\"name\":\"" << json_escape(active_layer.name)
              << "\",\"visible\":" << (active_layer.visible ? "true" : "false")
              << ",\"alphaLocked\":" << (active_layer.alpha_locked ? "true" : "false")
              << ",\"opacity\":" << active_layer.opacity
              << ",\"blendMode\":\"" << pp::paint::blend_mode_name(active_layer.blend_mode)
              << "\",\"frames\":" << active_layer.frames.size()
              << "},\"frames\":[";
    for (std::size_t frame_index = 0; frame_index < document.frames().size(); ++frame_index) {
        if (frame_index != 0U) {
            std::cout << ",";
        }
        std::cout << document.frames()[frame_index].duration_ms;
    }
    std::cout << "],\"activeLayerFrameDurations\":[";
    for (std::size_t frame_index = 0; frame_index < active_layer.frames.size(); ++frame_index) {
        if (frame_index != 0U) {
            std::cout << ",";
        }
        std::cout << active_layer.frames[frame_index].duration_ms;
    }
    std::cout << "],\"selectionMask\":{\"face\":" << selection_mask.face_index
              << ",\"x\":" << selection_mask.x
              << ",\"y\":" << selection_mask.y
              << ",\"width\":" << selection_mask.width
              << ",\"height\":" << selection_mask.height
              << ",\"bytes\":" << selection_mask.alpha8.size()
              << ",\"maxAlpha\":" << static_cast<int>(selection_mask.alpha8.back())
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_simulate_image_import_args(
    int argc,
    char** argv,
    SimulateImageImportArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--width" || key == "--height") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }

            if (key == "--width") {
                args.width = value.value();
            } else {
                args.height = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.width == 0 || args.height == 0) {
        return pp::foundation::Status::invalid_argument("width and height must be greater than zero");
    }

    return pp::foundation::Status::success();
}

int simulate_image_import(int argc, char** argv)
{
    SimulateImageImportArgs args;
    const auto status = parse_simulate_image_import_args(argc, argv, args);
    if (!status.ok()) {
        print_error("simulate-image-import", status.message);
        return 2;
    }

    const auto image_result = pp::assets::decode_png_rgba8(transparent_png_1x1_bytes());
    if (!image_result) {
        print_error("simulate-image-import", image_result.status().message);
        return 2;
    }

    const auto document_result = pp::document::CanvasDocument::create(
        pp::document::DocumentConfig {
            .width = args.width,
            .height = args.height,
            .layer_count = 1,
        });
    if (!document_result) {
        print_error("simulate-image-import", document_result.status().message);
        return 2;
    }

    const auto& image = image_result.value();
    auto document = document_result.value();
    const auto import_status = document.set_layer_frame_face_pixels(
        0,
        0,
        pp::document::LayerFacePixels {
            .face_index = 0,
            .x = 0,
            .y = 0,
            .width = image.width,
            .height = image.height,
            .rgba8 = image.pixels,
        });
    if (!import_status.ok()) {
        print_error("simulate-image-import", import_status.message);
        return 2;
    }

    const auto& payload = document.layers()[0].frames[0].face_pixels[0];
    std::cout << "{\"ok\":true,\"command\":\"simulate-image-import\""
              << ",\"image\":{\"format\":\"png\",\"width\":" << image.width
              << ",\"height\":" << image.height
              << ",\"bytes\":" << image.pixels.size()
              << ",\"alpha\":" << static_cast<int>(image.pixels[3])
              << "},\"document\":{\"width\":" << document.width()
              << ",\"height\":" << document.height()
              << ",\"layers\":" << document.layers().size()
              << ",\"frames\":" << document.frames().size()
              << ",\"facePayloads\":" << document.face_pixel_payload_count()
              << "},\"payload\":{\"face\":" << payload.face_index
              << ",\"x\":" << payload.x
              << ",\"y\":" << payload.y
              << ",\"width\":" << payload.width
              << ",\"height\":" << payload.height
              << ",\"bytes\":" << payload.rgba8.size()
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_simulate_document_export_args(
    int argc,
    char** argv,
    SimulateDocumentExportArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--width" || key == "--height") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }

            if (key == "--width") {
                args.width = value.value();
            } else {
                args.height = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.width == 0 || args.height == 0) {
        return pp::foundation::Status::invalid_argument("width and height must be greater than zero");
    }

    if (args.width < 8 || args.height < 8) {
        return pp::foundation::Status::out_of_range("width and height must be at least 8 for export simulation");
    }

    return pp::foundation::Status::success();
}

int simulate_document_export(int argc, char** argv)
{
    SimulateDocumentExportArgs args;
    const auto status = parse_simulate_document_export_args(argc, argv, args);
    if (!status.ok()) {
        print_error("simulate-document-export", status.message);
        return 2;
    }

    const auto document_result = create_export_sample_document(args.width, args.height);
    if (!document_result) {
        print_error("simulate-document-export", document_result.status().message);
        return 2;
    }

    const auto exported = pp::document::export_ppi_project_document(document_result.value());
    if (!exported) {
        print_error("simulate-document-export", exported.status().message);
        return 2;
    }

    const auto decoded = pp::assets::decode_ppi_project_images(exported.value());
    if (!decoded) {
        print_error("simulate-document-export", decoded.status().message);
        return 2;
    }

    const auto imported = pp::document::import_ppi_project_document(decoded.value());
    if (!imported) {
        print_error("simulate-document-export", imported.status().message);
        return 2;
    }

    const auto& source = document_result.value();
    const auto& roundtrip = imported.value();
    std::cout << "{\"ok\":true,\"command\":\"simulate-document-export\""
              << ",\"source\":{\"width\":" << source.width()
              << ",\"height\":" << source.height()
              << ",\"layers\":" << source.layers().size()
              << ",\"frames\":" << source.frames().size()
              << ",\"facePayloads\":" << source.face_pixel_payload_count()
              << "},\"export\":{\"bytes\":" << exported.value().size()
              << ",\"dirtyFaces\":" << decoded.value().project.body.summary.dirty_face_count
              << ",\"rgbaFacePayloads\":" << decoded.value().project.body.summary.rgba_face_payload_count
              << ",\"compressedBytes\":" << decoded.value().project.body.summary.compressed_face_bytes
              << "},\"roundtrip\":{\"layers\":" << roundtrip.layers().size()
              << ",\"frames\":" << roundtrip.frames().size()
              << ",\"facePayloads\":" << roundtrip.face_pixel_payload_count()
              << ",\"layerNames\":[";
    for (std::size_t layer_index = 0; layer_index < roundtrip.layers().size(); ++layer_index) {
        if (layer_index != 0U) {
            std::cout << ",";
        }
        std::cout << "\"" << json_escape(roundtrip.layers()[layer_index].name) << "\"";
    }
    std::cout << "],\"layerFrameCounts\":[";
    for (std::size_t layer_index = 0; layer_index < roundtrip.layers().size(); ++layer_index) {
        if (layer_index != 0U) {
            std::cout << ",";
        }
        std::cout << roundtrip.layers()[layer_index].frames.size();
    }
    std::cout << "],\"layerDurationsMs\":[";
    for (std::size_t layer_index = 0; layer_index < roundtrip.layers().size(); ++layer_index) {
        if (layer_index != 0U) {
            std::cout << ",";
        }
        const auto duration = roundtrip.layer_animation_duration_ms(layer_index);
        std::cout << (duration ? duration.value() : 0U);
    }
    std::cout << "]},\"payloads\":[";
    for (std::size_t payload_index = 0; payload_index < decoded.value().faces.size(); ++payload_index) {
        const auto& payload = decoded.value().faces[payload_index];
        if (payload_index != 0U) {
            std::cout << ",";
        }
        std::cout << "{\"layer\":" << payload.layer_index
                  << ",\"frame\":" << payload.frame_index
                  << ",\"face\":" << payload.face_index
                  << ",\"x\":" << payload.descriptor.x0
                  << ",\"y\":" << payload.descriptor.y0
                  << ",\"bytes\":" << payload.image.pixels.size()
                  << ",\"alpha\":" << static_cast<int>(payload.image.pixels[3])
                  << "}";
    }
    std::cout << "]}\n";
    return 0;
}

pp::foundation::Status parse_simulate_document_render_args(
    int argc,
    char** argv,
    SimulateDocumentRenderArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--width" || key == "--height" || key == "--frame") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }

            if (key == "--width") {
                args.width = value.value();
            } else if (key == "--height") {
                args.height = value.value();
            } else {
                args.frame = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.width == 0 || args.height == 0) {
        return pp::foundation::Status::invalid_argument("width and height must be greater than zero");
    }

    if (args.width < 8 || args.height < 8) {
        return pp::foundation::Status::out_of_range("width and height must be at least 8 for render simulation");
    }

    return pp::foundation::Status::success();
}

[[nodiscard]] bool pixel_differs_from_clear(pp::paint::Rgba pixel, pp::paint::Rgba clear) noexcept
{
    return pixel.r != clear.r || pixel.g != clear.g || pixel.b != clear.b || pixel.a != clear.a;
}

int simulate_document_render(int argc, char** argv)
{
    SimulateDocumentRenderArgs args;
    const auto status = parse_simulate_document_render_args(argc, argv, args);
    if (!status.ok()) {
        print_error("simulate-document-render", status.message);
        return 2;
    }

    const auto document_result = create_export_sample_document(args.width, args.height);
    if (!document_result) {
        print_error("simulate-document-render", document_result.status().message);
        return 2;
    }

    constexpr pp::paint::Rgba clear_color {};
    pp::renderer::RecordingRenderDevice render_device;
    const auto uploaded = pp::paint_renderer::upload_document_frame_faces(
        render_device,
        pp::paint_renderer::DocumentFrameUploadRequest {
            .document = &document_result.value(),
            .frame_index = args.frame,
            .clear_color = clear_color,
        });
    if (!uploaded) {
        print_error("simulate-document-render", uploaded.status().message);
        return 2;
    }

    const auto& document = document_result.value();
    const auto& uploaded_value = uploaded.value();
    const auto& result = uploaded_value.composite;
    const auto commands = render_device.commands();
#ifdef PP_PANO_CLI_ENABLE_OPENGL_PLAN
    const auto open_gl_plan = pp::renderer::gl::plan_recorded_render_commands(commands);
#endif
    std::size_t upload_command_count = 0;
    std::size_t transition_command_count = 0;
    for (const auto& command : commands) {
        if (command.kind == pp::renderer::RecordedRenderCommandKind::upload_texture) {
            ++upload_command_count;
        }
        if (command.kind == pp::renderer::RecordedRenderCommandKind::transition_texture) {
            ++transition_command_count;
        }
    }

    std::cout << "{\"ok\":true,\"command\":\"simulate-document-render\""
              << ",\"source\":{\"width\":" << document.width()
              << ",\"height\":" << document.height()
              << ",\"layers\":" << document.layers().size()
              << ",\"frames\":" << document.frames().size()
              << ",\"facePayloads\":" << document.face_pixel_payload_count()
              << "},\"render\":{\"frame\":" << args.frame
              << ",\"width\":" << result.extent.width
              << ",\"height\":" << result.extent.height
              << ",\"faces\":" << result.faces.size()
              << ",\"visitedLayers\":" << result.visited_layer_count
              << ",\"compositedLayerFaces\":" << result.composited_layer_face_count
              << ",\"facePayloads\":" << result.face_payload_count
              << ",\"faceSummaries\":[";
    for (std::size_t face_index = 0; face_index < result.faces.size(); ++face_index) {
        const auto& face = result.faces[face_index];
        std::size_t non_clear_pixels = 0;
        std::size_t first_non_clear = face.pixels.size();
        for (std::size_t pixel_index = 0; pixel_index < face.pixels.size(); ++pixel_index) {
            if (!pixel_differs_from_clear(face.pixels[pixel_index], clear_color)) {
                continue;
            }
            if (first_non_clear == face.pixels.size()) {
                first_non_clear = pixel_index;
            }
            ++non_clear_pixels;
        }

        if (face_index != 0U) {
            std::cout << ",";
        }
        std::cout << "{\"face\":" << face_index
                  << ",\"pixels\":" << face.pixels.size()
                  << ",\"payloads\":" << face.face_payload_count
                  << ",\"nonClearPixels\":" << non_clear_pixels;
        if (first_non_clear != face.pixels.size()) {
            const auto& pixel = face.pixels[first_non_clear];
            std::cout << ",\"firstNonClear\":{\"index\":" << first_non_clear
                      << ",\"x\":" << (first_non_clear % result.extent.width)
                      << ",\"y\":" << (first_non_clear / result.extent.width)
                      << ",\"r\":" << pixel.r
                      << ",\"g\":" << pixel.g
                      << ",\"b\":" << pixel.b
                      << ",\"a\":" << pixel.a
                      << "}";
        }
        std::cout << "}";
    }
    std::cout << "],\"upload\":{\"backend\":\"" << render_device.backend_name()
              << "\",\"textures\":" << uploaded_value.texture_count
              << ",\"bytes\":" << uploaded_value.uploaded_bytes
              << ",\"commands\":" << commands.size()
              << ",\"uploadCommands\":" << upload_command_count
              << ",\"transitionCommands\":" << transition_command_count
              << ",\"transitions\":" << uploaded_value.transition_count
#ifdef PP_PANO_CLI_ENABLE_OPENGL_PLAN
              << ",\"openGlPlan\":{\"available\":true"
              << ",\"supported\":" << json_bool(open_gl_plan.supported)
              << ",\"commands\":" << open_gl_plan.commands.size()
              << ",\"uploadCommands\":" << open_gl_plan.upload_command_count
              << ",\"transitionCommands\":" << open_gl_plan.transition_command_count
              << ",\"unsupportedCommands\":" << open_gl_plan.unsupported_command_count
              << ",\"renderPassOrderErrors\":" << open_gl_plan.render_pass_order_error_count
              << ",\"dependencyErrors\":" << open_gl_plan.dependency_error_count
              << "}"
#else
              << ",\"openGlPlan\":{\"available\":false}"
#endif
              << "}}}\n";
    return 0;
}

pp::foundation::Status parse_simulate_document_history_args(
    int argc,
    char** argv,
    SimulateDocumentHistoryArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--width" || key == "--height" || key == "--history") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }

            if (key == "--width") {
                args.width = value.value();
            } else if (key == "--height") {
                args.height = value.value();
            } else {
                args.history_entries = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.width == 0 || args.height == 0) {
        return pp::foundation::Status::invalid_argument("width and height must be greater than zero");
    }

    return pp::foundation::Status::success();
}

int simulate_document_history(int argc, char** argv)
{
    SimulateDocumentHistoryArgs args;
    const auto status = parse_simulate_document_history_args(argc, argv, args);
    if (!status.ok()) {
        print_error("simulate-document-history", status.message);
        return 2;
    }

    const auto document_result = pp::document::CanvasDocument::create(
        pp::document::DocumentConfig {
            .width = args.width,
            .height = args.height,
            .layer_count = 1,
        });
    if (!document_result) {
        print_error("simulate-document-history", document_result.status().message);
        return 2;
    }

    auto history_result = pp::document::DocumentHistory::create(
        document_result.value(),
        static_cast<std::size_t>(args.history_entries));
    if (!history_result) {
        print_error("simulate-document-history", history_result.status().message);
        return 2;
    }

    auto history = history_result.value();
    auto with_layer = history.current();
    const auto layer_result = with_layer.add_layer("Paint");
    if (!layer_result) {
        print_error("simulate-document-history", layer_result.status().message);
        return 2;
    }

    auto apply_status = history.apply(with_layer);
    if (!apply_status.ok()) {
        print_error("simulate-document-history", apply_status.message);
        return 2;
    }

    auto with_frame = history.current();
    const auto frame_result = with_frame.add_frame(250);
    if (!frame_result) {
        print_error("simulate-document-history", frame_result.status().message);
        return 2;
    }

    apply_status = history.apply(with_frame);
    if (!apply_status.ok()) {
        print_error("simulate-document-history", apply_status.message);
        return 2;
    }

    const auto undo_status = history.undo();
    if (!undo_status.ok()) {
        print_error("simulate-document-history", undo_status.message);
        return 2;
    }

    const auto undo_layers = history.current().layers().size();
    const auto undo_frames = history.current().frames().size();
    const auto undo_can_redo = history.can_redo();
    const auto undo_index = history.current_index();

    const auto redo_status = history.redo();
    if (!redo_status.ok()) {
        print_error("simulate-document-history", redo_status.message);
        return 2;
    }

    const auto& current = history.current();
    std::cout << "{\"ok\":true,\"command\":\"simulate-document-history\""
              << ",\"history\":{\"size\":" << history.size()
              << ",\"currentIndex\":" << history.current_index()
              << ",\"canUndo\":" << (history.can_undo() ? "true" : "false")
              << ",\"canRedo\":" << (history.can_redo() ? "true" : "false")
              << "},\"undo\":{\"layers\":" << undo_layers
              << ",\"frames\":" << undo_frames
              << ",\"currentIndex\":" << undo_index
              << ",\"canRedo\":" << (undo_can_redo ? "true" : "false")
              << "},\"current\":{\"width\":" << current.width()
              << ",\"height\":" << current.height()
              << ",\"layers\":" << current.layers().size()
              << ",\"frames\":" << current.frames().size()
              << ",\"activeLayer\":" << current.active_layer_index()
              << ",\"activeFrame\":" << current.active_frame_index()
              << ",\"animationDurationMs\":" << current.animation_duration_ms()
              << "}}\n";
    return 0;
}

pp::foundation::Status parse_record_render_args(int argc, char** argv, RecordRenderArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--exercise-clear") {
            args.exercise_clear = true;
        } else if (key == "--width" || key == "--height") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            const auto value = pp::foundation::parse_u32(argv[++i]);
            if (!value) {
                return value.status();
            }

            if (key == "--width") {
                args.width = value.value();
            } else {
                args.height = value.value();
            }
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.width == 0 || args.height == 0) {
        return pp::foundation::Status::invalid_argument("width and height must be greater than zero");
    }

    return pp::foundation::Status::success();
}

int record_render(int argc, char** argv)
{
    RecordRenderArgs args;
    const auto status = parse_record_render_args(argc, argv, args);
    if (!status.ok()) {
        print_error("record-render", status.message);
        return 2;
    }

    pp::renderer::RecordingRenderDevice device;
    const auto texture = device.create_texture(pp::renderer::TextureDesc {
        .extent = pp::renderer::Extent2D { .width = args.width, .height = args.height },
        .format = pp::renderer::TextureFormat::rgba8,
        .usage = pp::renderer::TextureUsage::render_target | pp::renderer::TextureUsage::sampled | pp::renderer::TextureUsage::upload_destination | pp::renderer::TextureUsage::readback_source | pp::renderer::TextureUsage::copy_source | pp::renderer::TextureUsage::copy_destination,
        .debug_name = "record-render-texture",
    });
    const auto target = device.create_render_target(pp::renderer::TextureDesc {
        .extent = pp::renderer::Extent2D { .width = args.width, .height = args.height },
        .format = pp::renderer::TextureFormat::rgba8,
        .usage = pp::renderer::TextureUsage::render_target | pp::renderer::TextureUsage::sampled | pp::renderer::TextureUsage::upload_destination | pp::renderer::TextureUsage::readback_source | pp::renderer::TextureUsage::copy_source | pp::renderer::TextureUsage::copy_destination,
        .debug_name = "record-render-target",
    });
    const auto blit_target = device.create_render_target(pp::renderer::TextureDesc {
        .extent = pp::renderer::Extent2D { .width = args.width, .height = args.height },
        .format = pp::renderer::TextureFormat::rgba8,
        .usage = pp::renderer::TextureUsage::render_target | pp::renderer::TextureUsage::sampled | pp::renderer::TextureUsage::upload_destination | pp::renderer::TextureUsage::readback_source | pp::renderer::TextureUsage::copy_source | pp::renderer::TextureUsage::copy_destination,
        .debug_name = "record-render-blit-target",
    });
    const auto mip_texture = device.create_texture(pp::renderer::TextureDesc {
        .extent = pp::renderer::Extent2D { .width = 4, .height = 4 },
        .format = pp::renderer::TextureFormat::rgba8,
        .mip_levels = 3,
        .usage = pp::renderer::TextureUsage::sampled | pp::renderer::TextureUsage::copy_source | pp::renderer::TextureUsage::copy_destination,
        .debug_name = "record-render-mip-texture",
    });
    const auto readback_buffer = device.create_readback_buffer(
        static_cast<std::uint64_t>(args.width) * args.height * 4U);
    const std::array<std::byte, 4> upload_pixel {
        std::byte { 0xff },
        std::byte { 0x00 },
        std::byte { 0xff },
        std::byte { 0xff },
    };
    const std::array<std::byte, 64> uniform_mvp {};
    static constexpr char shader_source[] = "void main() {}";
    const auto shader = device.create_shader_program(pp::renderer::ShaderProgramDesc {
        .debug_name = "pano-cli-record-render",
        .vertex = pp::renderer::ShaderStageSource {
            .source = shader_source,
            .source_size = sizeof(shader_source) - 1U,
        },
        .fragment = pp::renderer::ShaderStageSource {
            .source = shader_source,
            .source_size = sizeof(shader_source) - 1U,
        },
    });
    const auto mesh = device.create_mesh(pp::renderer::MeshDesc {
        .vertex_count = 3,
        .index_count = 3,
        .topology = pp::renderer::PrimitiveTopology::triangles,
        .debug_name = "record-render-mesh",
    });

    if (!texture.ok()) {
        print_error("record-render", texture.status().message);
        return 2;
    }
    if (!target.ok()) {
        print_error("record-render", target.status().message);
        return 2;
    }
    if (!blit_target.ok()) {
        print_error("record-render", blit_target.status().message);
        return 2;
    }
    if (!mip_texture.ok()) {
        print_error("record-render", mip_texture.status().message);
        return 2;
    }
    if (!readback_buffer.ok()) {
        print_error("record-render", readback_buffer.status().message);
        return 2;
    }
    if (!shader.ok()) {
        print_error("record-render", shader.status().message);
        return 2;
    }
    if (!mesh.ok()) {
        print_error("record-render", mesh.status().message);
        return 2;
    }
    constexpr std::size_t created_resources = 7;

    auto* trace = device.trace();
    auto& context = device.immediate_context();
    bool clear_rejected_orphaned_trace_end = false;
    bool clear_reused_render_pass = false;
    if (args.exercise_clear) {
        const auto interrupted_trace_status = trace->begin_scope("renderer", "interrupted-frame");
        if (!interrupted_trace_status.ok()) {
            print_error("record-render", interrupted_trace_status.message);
            return 2;
        }

        const auto interrupted_begin_status = context.begin_render_pass(*target.value(), pp::renderer::RenderPassDesc {});
        if (!interrupted_begin_status.ok()) {
            print_error("record-render", interrupted_begin_status.message);
            return 2;
        }

        device.clear();
        const auto stale_trace_end_status = trace->end_scope();
        if (stale_trace_end_status.ok()) {
            print_error("record-render", "recording clear did not reset trace scope state");
            return 2;
        }
        clear_rejected_orphaned_trace_end = true;

        const auto reuse_begin_status = context.begin_render_pass(*target.value(), pp::renderer::RenderPassDesc {});
        if (!reuse_begin_status.ok()) {
            print_error("record-render", reuse_begin_status.message);
            return 2;
        }
        context.end_render_pass();
        clear_reused_render_pass = true;
        device.clear();
    }

    const auto trace_begin_status = trace->begin_scope("renderer", "pano_cli_record_render");
    if (!trace_begin_status.ok()) {
        print_error("record-render", trace_begin_status.message);
        return 2;
    }
    const auto trace_marker_status = trace->marker("renderer", "frame");
    if (!trace_marker_status.ok()) {
        print_error("record-render", trace_marker_status.message);
        return 2;
    }
    const auto trace_end_status = trace->end_scope();
    if (!trace_end_status.ok()) {
        print_error("record-render", trace_end_status.message);
        return 2;
    }

    const auto transition_upload_status = context.transition_texture(
        *texture.value(),
        pp::renderer::TextureState::undefined,
        pp::renderer::TextureState::upload_destination);
    if (!transition_upload_status.ok()) {
        print_error("record-render", transition_upload_status.message);
        return 2;
    }

    const auto upload_status = context.upload_texture(
        *texture.value(),
        pp::renderer::ReadbackRegion {
            .x = 0,
            .y = 0,
            .width = 1,
            .height = 1,
        },
        upload_pixel);
    if (!upload_status.ok()) {
        print_error("record-render", upload_status.message);
        return 2;
    }

    const auto transition_shader_read_status = context.transition_texture(
        *texture.value(),
        pp::renderer::TextureState::upload_destination,
        pp::renderer::TextureState::shader_read);
    if (!transition_shader_read_status.ok()) {
        print_error("record-render", transition_shader_read_status.message);
        return 2;
    }

    const auto transition_mip_destination_status = context.transition_texture(
        *mip_texture.value(),
        pp::renderer::TextureState::undefined,
        pp::renderer::TextureState::copy_destination);
    if (!transition_mip_destination_status.ok()) {
        print_error("record-render", transition_mip_destination_status.message);
        return 2;
    }

    const auto mipmap_status = context.generate_mipmaps(*mip_texture.value());
    if (!mipmap_status.ok()) {
        print_error("record-render", mipmap_status.message);
        return 2;
    }

    const auto transition_mip_shader_read_status = context.transition_texture(
        *mip_texture.value(),
        pp::renderer::TextureState::copy_destination,
        pp::renderer::TextureState::shader_read);
    if (!transition_mip_shader_read_status.ok()) {
        print_error("record-render", transition_mip_shader_read_status.message);
        return 2;
    }

    const auto begin_status = context.begin_render_pass(
        *target.value(),
        pp::renderer::RenderPassDesc {
            .clear_color = pp::renderer::ClearColor { .r = 0.0F, .g = 0.0F, .b = 0.0F, .a = 1.0F },
            .clear_depth_enabled = true,
            .clear_depth = 1.0F,
        });
    if (!begin_status.ok()) {
        print_error("record-render", begin_status.message);
        return 2;
    }

    const auto viewport_status = context.set_viewport(
        pp::renderer::Viewport { .x = 0, .y = 0, .width = args.width, .height = args.height });
    if (!viewport_status.ok()) {
        print_error("record-render", viewport_status.message);
        return 2;
    }

    const auto scissor_status = context.set_scissor(pp::renderer::ScissorRect {
        .enabled = true,
        .x = 0,
        .y = 0,
        .width = args.width,
        .height = args.height,
    });
    if (!scissor_status.ok()) {
        print_error("record-render", scissor_status.message);
        return 2;
    }

    const auto shader_status = context.bind_shader(*shader.value());
    const auto uniform_status = context.set_shader_uniform("mvp", uniform_mvp);
    const auto blend_status = context.set_blend_state(pp::renderer::BlendState {
        .enabled = true,
        .source_color = pp::renderer::BlendFactor::source_alpha,
        .destination_color = pp::renderer::BlendFactor::one_minus_source_alpha,
        .source_alpha = pp::renderer::BlendFactor::one,
        .destination_alpha = pp::renderer::BlendFactor::one_minus_source_alpha,
    });
    const auto depth_status = context.set_depth_state(pp::renderer::DepthState {
        .test_enabled = true,
        .write_enabled = true,
        .compare = pp::renderer::CompareOp::less_or_equal,
    });
    const auto bind_texture_status = context.bind_texture(0, *texture.value());
    const auto bind_sampler_status = context.bind_sampler(0, pp::renderer::SamplerDesc {
        .min_filter = pp::renderer::SamplerFilter::linear,
        .mag_filter = pp::renderer::SamplerFilter::linear,
        .mip_filter = pp::renderer::SamplerFilter::linear,
        .address_u = pp::renderer::SamplerAddressMode::clamp_to_edge,
        .address_v = pp::renderer::SamplerAddressMode::clamp_to_edge,
        .address_w = pp::renderer::SamplerAddressMode::clamp_to_edge,
    });
    const auto mesh_status = context.bind_mesh(*mesh.value());
    const auto draw_status = context.draw(pp::renderer::DrawDesc {
        .vertex_count = 3,
        .index_count = 3,
    });
    context.end_render_pass();

    if (!shader_status.ok()) {
        print_error("record-render", shader_status.message);
        return 2;
    }
    if (!uniform_status.ok()) {
        print_error("record-render", uniform_status.message);
        return 2;
    }
    if (!blend_status.ok()) {
        print_error("record-render", blend_status.message);
        return 2;
    }
    if (!depth_status.ok()) {
        print_error("record-render", depth_status.message);
        return 2;
    }
    if (!bind_texture_status.ok()) {
        print_error("record-render", bind_texture_status.message);
        return 2;
    }
    if (!bind_sampler_status.ok()) {
        print_error("record-render", bind_sampler_status.message);
        return 2;
    }
    if (!mesh_status.ok()) {
        print_error("record-render", mesh_status.message);
        return 2;
    }
    if (!draw_status.ok()) {
        print_error("record-render", draw_status.message);
        return 2;
    }

    const auto readback_status = context.read_texture(
        *texture.value(),
        pp::renderer::ReadbackRegion {
            .x = 0,
            .y = 0,
            .width = args.width,
            .height = args.height,
        },
        *readback_buffer.value());
    if (!readback_status.ok()) {
        print_error("record-render", readback_status.message);
        return 2;
    }

    const auto copy_status = context.copy_texture(
        *texture.value(),
        pp::renderer::ReadbackRegion {
            .x = 0,
            .y = 0,
            .width = args.width,
            .height = args.height,
        },
        *texture.value(),
        pp::renderer::ReadbackRegion {
            .x = 0,
            .y = 0,
            .width = args.width,
            .height = args.height,
        });
    if (!copy_status.ok()) {
        print_error("record-render", copy_status.message);
        return 2;
    }

    const auto capture_status = context.capture_frame(*target.value(), *readback_buffer.value());
    if (!capture_status.ok()) {
        print_error("record-render", capture_status.message);
        return 2;
    }

    const auto blit_status = context.blit_render_target(
        *target.value(),
        pp::renderer::ReadbackRegion {
            .x = 0,
            .y = 0,
            .width = args.width,
            .height = args.height,
        },
        *blit_target.value(),
        pp::renderer::ReadbackRegion {
            .x = 0,
            .y = 0,
            .width = args.width,
            .height = args.height,
        },
        pp::renderer::BlitFilter::nearest);
    if (!blit_status.ok()) {
        print_error("record-render", blit_status.message);
        return 2;
    }

    std::size_t draw_commands = 0;
    std::size_t scissor_commands = 0;
    std::size_t blend_commands = 0;
    std::size_t depth_commands = 0;
    std::size_t uniform_commands = 0;
    std::size_t bind_texture_commands = 0;
    std::size_t bind_sampler_commands = 0;
    std::size_t upload_commands = 0;
    std::size_t mipmap_commands = 0;
    std::size_t transition_commands = 0;
    std::size_t transition_to_upload = 0;
    std::size_t transition_to_shader_read = 0;
    std::size_t copy_commands = 0;
    std::size_t readback_commands = 0;
    std::size_t capture_commands = 0;
    std::size_t blit_commands = 0;
    std::size_t trace_markers = 0;
    std::size_t trace_begin_scopes = 0;
    std::size_t trace_end_scopes = 0;
    std::size_t render_passes = 0;
    std::size_t depth_clears = 0;
    std::size_t stencil_clears = 0;
    std::uint64_t draw_vertices = 0;
    std::uint64_t draw_indices = 0;
    std::uint64_t uniform_bytes = 0;
    std::uint64_t upload_bytes = 0;
    std::uint64_t mipmap_levels = 0;
    std::uint64_t mipmap_bytes = 0;
    std::uint64_t copy_source_bytes = 0;
    std::uint64_t copy_destination_bytes = 0;
    std::uint64_t bound_texture_bytes = 0;
    std::uint64_t readback_bytes = 0;
    std::uint64_t capture_bytes = 0;
    std::uint64_t blit_source_bytes = 0;
    std::uint64_t blit_destination_bytes = 0;
    std::size_t labeled_command_descriptors = 0;
    const auto count_label = [&labeled_command_descriptors](const char* label) {
        if (label != nullptr && label[0] != '\0') {
            ++labeled_command_descriptors;
        }
    };
    const auto commands = device.commands();
    const auto features = device.features();
#ifdef PP_PANO_CLI_ENABLE_OPENGL_PLAN
    const auto open_gl_plan = pp::renderer::gl::plan_recorded_render_commands(commands);
#endif
    for (const auto& command : commands) {
        if (command.kind == pp::renderer::RecordedRenderCommandKind::begin_render_pass) {
            ++render_passes;
            count_label(command.target_desc.debug_name);
            if (command.clear_depth_enabled) {
                ++depth_clears;
            }
            if (command.clear_stencil_enabled) {
                ++stencil_clears;
            }
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::draw) {
            ++draw_commands;
            count_label(command.mesh_desc.debug_name);
            draw_vertices += command.draw_desc.vertex_count;
            draw_indices += command.draw_desc.index_count;
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::set_scissor) {
            ++scissor_commands;
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::set_blend_state) {
            ++blend_commands;
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::set_depth_state) {
            ++depth_commands;
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::set_shader_uniform) {
            ++uniform_commands;
            uniform_bytes += command.uniform_bytes;
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::bind_texture) {
            ++bind_texture_commands;
            count_label(command.texture_desc.debug_name);
            const auto bound_bytes = pp::renderer::texture_byte_size(command.texture_desc);
            if (bound_bytes.ok()) {
                bound_texture_bytes += bound_bytes.value();
            }
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::bind_sampler) {
            ++bind_sampler_commands;
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::bind_mesh) {
            count_label(command.mesh_desc.debug_name);
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::generate_mipmaps) {
            ++mipmap_commands;
            count_label(command.texture_desc.debug_name);
            mipmap_levels += command.generated_mip_levels;
            mipmap_bytes += command.generated_mip_bytes;
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::transition_texture) {
            ++transition_commands;
            count_label(command.texture_desc.debug_name);
            if (command.after_state == pp::renderer::TextureState::upload_destination) {
                ++transition_to_upload;
            }
            if (command.after_state == pp::renderer::TextureState::shader_read) {
                ++transition_to_shader_read;
            }
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::upload_texture) {
            ++upload_commands;
            count_label(command.texture_desc.debug_name);
            upload_bytes += command.upload_bytes;
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::copy_texture) {
            ++copy_commands;
            count_label(command.source_desc.debug_name);
            count_label(command.destination_desc.debug_name);
            copy_source_bytes += command.copy_source_bytes;
            copy_destination_bytes += command.copy_destination_bytes;
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::read_texture) {
            ++readback_commands;
            count_label(command.texture_desc.debug_name);
            readback_bytes += command.readback_bytes;
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::capture_frame) {
            ++capture_commands;
            count_label(command.target_desc.debug_name);
            capture_bytes += command.capture_bytes;
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::blit_render_target) {
            ++blit_commands;
            count_label(command.source_desc.debug_name);
            count_label(command.destination_desc.debug_name);
            blit_source_bytes += command.blit_source_bytes;
            blit_destination_bytes += command.blit_destination_bytes;
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::trace_marker) {
            ++trace_markers;
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::trace_begin_scope) {
            ++trace_begin_scopes;
        } else if (command.kind == pp::renderer::RecordedRenderCommandKind::trace_end_scope) {
            ++trace_end_scopes;
        }
    }

    std::cout << "{\"ok\":true,\"command\":\"record-render\""
              << ",\"backend\":\"" << device.backend_name() << "\""
              << ",\"features\":{\"framebufferFetch\":" << json_bool(features.framebuffer_fetch)
              << ",\"explicitTextureTransitions\":" << json_bool(features.explicit_texture_transitions)
              << ",\"textureCopy\":" << json_bool(features.texture_copy)
              << ",\"renderTargetBlit\":" << json_bool(features.render_target_blit)
              << ",\"frameCapture\":" << json_bool(features.frame_capture)
              << ",\"float16RenderTargets\":" << json_bool(features.float16_render_targets)
              << ",\"float32RenderTargets\":" << json_bool(features.float32_render_targets)
              << "}"
              << ",\"target\":{\"width\":" << args.width
              << ",\"height\":" << args.height
              << ",\"format\":\"rgba8\"}"
              << ",\"createdResources\":" << created_resources
              << ",\"exercisedClearReset\":" << json_bool(args.exercise_clear)
              << ",\"clearRejectedOrphanedTraceEnd\":" << json_bool(clear_rejected_orphaned_trace_end)
              << ",\"clearReusedRenderPass\":" << json_bool(clear_reused_render_pass)
              << ",\"labeledCommandDescriptors\":" << labeled_command_descriptors
              << ",\"commands\":" << commands.size()
#ifdef PP_PANO_CLI_ENABLE_OPENGL_PLAN
              << ",\"openGlPlan\":{\"available\":true"
              << ",\"supported\":" << json_bool(open_gl_plan.supported)
              << ",\"commands\":" << open_gl_plan.commands.size()
              << ",\"renderPasses\":" << open_gl_plan.render_pass_count
              << ",\"drawCommands\":" << open_gl_plan.draw_command_count
              << ",\"shaderBindCommands\":" << open_gl_plan.shader_bind_command_count
              << ",\"uniformCommands\":" << open_gl_plan.uniform_command_count
              << ",\"textureBindCommands\":" << open_gl_plan.texture_bind_command_count
              << ",\"samplerBindCommands\":" << open_gl_plan.sampler_bind_command_count
              << ",\"uploadCommands\":" << open_gl_plan.upload_command_count
              << ",\"mipmapCommands\":" << open_gl_plan.mipmap_command_count
              << ",\"transitionCommands\":" << open_gl_plan.transition_command_count
              << ",\"copyCommands\":" << open_gl_plan.copy_command_count
              << ",\"readbackCommands\":" << open_gl_plan.readback_command_count
              << ",\"captureCommands\":" << open_gl_plan.capture_command_count
              << ",\"passthroughCommands\":" << open_gl_plan.passthrough_command_count
              << ",\"traceCommands\":" << open_gl_plan.trace_command_count
              << ",\"unsupportedCommands\":" << open_gl_plan.unsupported_command_count
              << ",\"renderPassOrderErrors\":" << open_gl_plan.render_pass_order_error_count
              << ",\"dependencyErrors\":" << open_gl_plan.dependency_error_count
              << ",\"endedInRenderPass\":" << json_bool(open_gl_plan.ended_in_render_pass)
              << "}"
#endif
              << ",\"renderPasses\":" << render_passes
              << ",\"depthClears\":" << depth_clears
              << ",\"stencilClears\":" << stencil_clears
              << ",\"drawCommands\":" << draw_commands
              << ",\"drawVertices\":" << draw_vertices
              << ",\"drawIndices\":" << draw_indices
              << ",\"scissorCommands\":" << scissor_commands
              << ",\"blendCommands\":" << blend_commands
              << ",\"depthCommands\":" << depth_commands
              << ",\"uniformCommands\":" << uniform_commands
              << ",\"uniformBytes\":" << uniform_bytes
              << ",\"bindTextureCommands\":" << bind_texture_commands
              << ",\"bindSamplerCommands\":" << bind_sampler_commands
              << ",\"boundTextureBytes\":" << bound_texture_bytes
              << ",\"uploadCommands\":" << upload_commands
              << ",\"uploadBytes\":" << upload_bytes
              << ",\"mipmapCommands\":" << mipmap_commands
              << ",\"mipmapLevels\":" << mipmap_levels
              << ",\"mipmapBytes\":" << mipmap_bytes
              << ",\"transitionCommands\":" << transition_commands
              << ",\"transitionToUpload\":" << transition_to_upload
              << ",\"transitionToShaderRead\":" << transition_to_shader_read
              << ",\"copyCommands\":" << copy_commands
              << ",\"copySourceBytes\":" << copy_source_bytes
              << ",\"copyDestinationBytes\":" << copy_destination_bytes
              << ",\"readbackCommands\":" << readback_commands
              << ",\"readbackBytes\":" << readback_bytes
              << ",\"captureCommands\":" << capture_commands
              << ",\"captureBytes\":" << capture_bytes
              << ",\"blitCommands\":" << blit_commands
              << ",\"blitSourceBytes\":" << blit_source_bytes
              << ",\"blitDestinationBytes\":" << blit_destination_bytes
              << ",\"traceMarkers\":" << trace_markers
              << ",\"traceBeginScopes\":" << trace_begin_scopes
              << ",\"traceEndScopes\":" << trace_end_scopes
              << ",\"first\":\""
              << pp::renderer::recorded_render_command_kind_name(commands.front().kind)
              << "\",\"last\":\""
              << pp::renderer::recorded_render_command_kind_name(commands.back().kind)
              << "\"}\n";
    return 0;
}

pp::foundation::Status parse_layout_args(int argc, char** argv, ParseLayoutArgs& args)
{
    for (int i = 2; i < argc; ++i) {
        const std::string_view key(argv[i]);
        if (key == "--path") {
            if (i + 1 >= argc) {
                return pp::foundation::Status::invalid_argument("missing value for option");
            }

            args.path = argv[++i];
        } else {
            return pp::foundation::Status::invalid_argument("unknown option");
        }
    }

    if (args.path.empty()) {
        return pp::foundation::Status::invalid_argument("path must not be empty");
    }

    return pp::foundation::Status::success();
}

int parse_layout(int argc, char** argv)
{
    ParseLayoutArgs args;
    const auto status = parse_layout_args(argc, argv, args);
    if (!status.ok()) {
        print_error("parse-layout", status.message);
        return 2;
    }

    std::ifstream stream(args.path, std::ios::binary);
    if (!stream) {
        print_error("parse-layout", "layout file could not be opened");
        return 2;
    }

    const std::string xml {
        std::istreambuf_iterator<char>(stream),
        std::istreambuf_iterator<char>()
    };
    const auto summary = pp::ui::parse_layout_xml(xml);
    if (!summary) {
        print_error("parse-layout", summary.status().message);
        return 2;
    }

    std::cout << "{\"ok\":true,\"command\":\"parse-layout\""
              << ",\"nodes\":" << summary.value().node_count
              << ",\"lengthAttributes\":" << summary.value().length_attribute_count
              << "}\n";
    return 0;
}

}

int main(int argc, char** argv)
{
    if (argc < 2) {
        print_help();
        return 1;
    }

    const std::string_view command(argv[1]);
    if (command == "--help" || command == "-h") {
        print_help();
        return 0;
    }

    if (command == "create-document") {
        return create_document(argc, argv);
    }

    if (command == "inspect-image") {
        return inspect_image(argc, argv);
    }

    if (command == "export-image") {
        return export_image(argc, argv);
    }

    if (command == "import-image") {
        return import_image(argc, argv);
    }

    if (command == "inspect-project") {
        return inspect_project(argc, argv);
    }

    if (command == "classify-open") {
        return classify_open(argc, argv);
    }

    if (command == "plan-open-route") {
        return plan_open_route(argc, argv);
    }

    if (command == "plan-file-menu") {
        return plan_file_menu(argc, argv);
    }

    if (command == "plan-document-file") {
        return plan_document_file(argc, argv);
    }

    if (command == "plan-new-document") {
        return plan_new_document(argc, argv);
    }

    if (command == "plan-document-version") {
        return plan_document_version(argc, argv);
    }

    if (command == "plan-document-session-prompt") {
        return plan_document_session_prompt(argc, argv);
    }

    if (command == "plan-export-start") {
        return plan_export_start(argc, argv);
    }

    if (command == "plan-export-menu") {
        return plan_export_menu(argc, argv);
    }

    if (command == "plan-export-snapshot-route") {
        return plan_export_snapshot_route(argc, argv);
    }

    if (command == "plan-export-target") {
        return plan_export_target(argc, argv);
    }

    if (command == "plan-export-message") {
        return plan_export_message(argc, argv);
    }

    if (command == "plan-export-report") {
        return plan_export_report(argc, argv);
    }

    if (command == "plan-cloud-upload") {
        return plan_cloud_upload(argc, argv);
    }

    if (command == "plan-cloud-browse") {
        return plan_cloud_browse(argc, argv);
    }

    if (command == "plan-cloud-upload-all") {
        return plan_cloud_upload_all(argc, argv);
    }

    if (command == "plan-cloud-transfer") {
        return plan_cloud_transfer(argc, argv);
    }

    if (command == "plan-app-dialog") {
        return plan_app_dialog(argc, argv);
    }

    if (command == "plan-recording-session") {
        return plan_recording_session(argc, argv);
    }

    if (command == "plan-app-preferences") {
        return plan_app_preferences(argc, argv);
    }

    if (command == "plan-app-startup") {
        return plan_app_startup(argc, argv);
    }

    if (command == "plan-app-startup-resources") {
        return plan_app_startup_resources(argc, argv);
    }

    if (command == "plan-app-frame") {
        return plan_app_frame(argc, argv);
    }

    if (command == "plan-app-thread") {
        return plan_app_thread(argc, argv);
    }

    if (command == "plan-app-input") {
        return plan_app_input(argc, argv);
    }

    if (command == "plan-app-shutdown") {
        return plan_app_shutdown(argc, argv);
    }

    if (command == "plan-command-convert") {
        return plan_command_convert(argc, argv);
    }

    if (command == "plan-brush-package-import") {
        return plan_brush_package_import(argc, argv);
    }

    if (command == "plan-brush-package-export") {
        return plan_brush_package_export(argc, argv);
    }

    if (command == "plan-app-status") {
        return plan_app_status(argc, argv);
    }

    if (command == "plan-tools-menu") {
        return plan_tools_menu(argc, argv);
    }

    if (command == "plan-tools-panel") {
        return plan_tools_panel(argc, argv);
    }

    if (command == "plan-about-menu") {
        return plan_about_menu(argc, argv);
    }

    if (command == "plan-document-resize") {
        return plan_document_resize(argc, argv);
    }

    if (command == "plan-canvas-clear") {
        return plan_canvas_clear(argc, argv);
    }

    if (command == "plan-canvas-project-save-target") {
        return plan_canvas_project_save_target(argc, argv);
    }

    if (command == "plan-canvas-document-snapshot") {
        return plan_canvas_document_snapshot(argc, argv);
    }

    if (command == "plan-image-import") {
        return plan_image_import(argc, argv);
    }

    if (command == "plan-layer-rename") {
        return plan_layer_rename(argc, argv);
    }

    if (command == "plan-layer-menu") {
        return plan_layer_menu(argc, argv);
    }

    if (command == "plan-layer-panel-view") {
        return plan_layer_panel_view(argc, argv);
    }

    if (command == "plan-layer-merge") {
        return plan_layer_merge(argc, argv);
    }

    if (command == "plan-layer-operation") {
        return plan_layer_operation(argc, argv);
    }

    if (command == "plan-animation-operation") {
        return plan_animation_operation(argc, argv);
    }

    if (command == "plan-animation-panel-action") {
        return plan_animation_panel_action(argc, argv);
    }

    if (command == "plan-animation-panel-view") {
        return plan_animation_panel_view(argc, argv);
    }

    if (command == "plan-animation-timeline-scrub") {
        return plan_animation_timeline_scrub(argc, argv);
    }

    if (command == "plan-brush-operation") {
        return plan_brush_operation(argc, argv);
    }

    if (command == "plan-brush-refresh") {
        return plan_brush_refresh(argc, argv);
    }

    if (command == "plan-brush-texture-list") {
        return plan_brush_texture_list(argc, argv);
    }

    if (command == "plan-brush-preset-list") {
        return plan_brush_preset_list(argc, argv);
    }

    if (command == "plan-brush-stroke-control") {
        return plan_brush_stroke_control(argc, argv);
    }

    if (command == "plan-brush-stroke-panel-view") {
        return plan_brush_stroke_panel_view(argc, argv);
    }

    if (command == "plan-paint-feedback") {
        return plan_paint_feedback(argc, argv);
    }

    if (command == "plan-stroke-composite") {
        return plan_stroke_composite(argc, argv);
    }

    if (command == "plan-canvas-hotkey") {
        return plan_canvas_hotkey(argc, argv);
    }

    if (command == "plan-canvas-tool") {
        return plan_canvas_tool(argc, argv);
    }

    if (command == "plan-canvas-tool-toolbar") {
        return plan_canvas_tool_toolbar(argc, argv);
    }

    if (command == "plan-canvas-tool-state") {
        return plan_canvas_tool_state(argc, argv);
    }

    if (command == "plan-canvas-camera-reset") {
        return plan_canvas_camera_reset(argc, argv);
    }

    if (command == "plan-canvas-view-density") {
        return plan_canvas_view_density(argc, argv);
    }

    if (command == "plan-canvas-view-cursor-mode") {
        return plan_canvas_view_cursor_mode(argc, argv);
    }

    if (command == "plan-canvas-cursor") {
        return plan_canvas_cursor(argc, argv);
    }

    if (command == "plan-grid-operation") {
        return plan_grid_operation(argc, argv);
    }

    if (command == "plan-history-operation") {
        return plan_history_operation(argc, argv);
    }

    if (command == "plan-main-toolbar") {
        return plan_main_toolbar(argc, argv);
    }

    if (command == "plan-quick-operation") {
        return plan_quick_operation(argc, argv);
    }

    if (command == "plan-quick-slider-preview") {
        return plan_quick_slider_preview(argc, argv);
    }

    if (command == "plan-share-file") {
        return plan_share_file(argc, argv);
    }

    if (command == "plan-picked-path") {
        return plan_picked_path(argc, argv);
    }

    if (command == "plan-display-file") {
        return plan_display_file(argc, argv);
    }

    if (command == "plan-keyboard-visibility") {
        return plan_keyboard_visibility(argc, argv);
    }

    if (command == "plan-cursor-visibility") {
        return plan_cursor_visibility(argc, argv);
    }

    if (command == "plan-clipboard-read") {
        return plan_clipboard_read(argc, argv);
    }

    if (command == "plan-clipboard-write") {
        return plan_clipboard_write(argc, argv);
    }

    if (command == "load-project") {
        return load_project(argc, argv);
    }

    if (command == "simulate-stroke") {
        return simulate_stroke(argc, argv);
    }

    if (command == "simulate-stroke-script") {
        return simulate_stroke_script(argc, argv);
    }

    if (command == "simulate-blend") {
        return simulate_blend(argc, argv);
    }

    if (command == "apply-stroke-script") {
        return apply_stroke_script(argc, argv);
    }

    if (command == "simulate-document-edits") {
        return simulate_document_edits(argc, argv);
    }

    if (command == "simulate-document-export") {
        return simulate_document_export(argc, argv);
    }

    if (command == "simulate-document-render") {
        return simulate_document_render(argc, argv);
    }

    if (command == "simulate-document-history") {
        return simulate_document_history(argc, argv);
    }

    if (command == "simulate-app-session") {
        return simulate_app_session(argc, argv);
    }

    if (command == "simulate-image-import") {
        return simulate_image_import(argc, argv);
    }

    if (command == "parse-layout") {
        return parse_layout(argc, argv);
    }

    if (command == "record-render") {
        return record_render(argc, argv);
    }

    if (command == "save-document-project") {
        return save_document_project(argc, argv);
    }

    if (command == "save-project") {
        return save_project(argc, argv);
    }

    print_error(command, "unknown command");
    return 2;
}
