// DragonX Wallet - ImGui Edition
// Copyright 2024-2026 The Hush Developers
// Released under the GPLv3
//
// LiteBridgeOwnedString — RAII wrapper for a Rust-allocated C string returned by the litelib_*
// backend. It is the memory-safety boundary for owned strings: copy the value before freeing,
// free it exactly once via the backend's freeString function, wipe the copy, and convert to a
// LiteBridgeStringResult (classifying "Error:"-prefixed payloads as failures).
//
// Extracted from the former lite_bridge_runtime.{cpp,h} — a ~25k-line dry-dispatch /
// dynamic-loader scaffold the shipping wallet never used. Only this owned-string helper was on
// the live path: LiteClientBridge::linkedSdxl() loads the backend via direct litelib_* externs
// in lite_client_bridge.cpp, and lite_client_bridge.cpp converts each owned string through
// liteBridgeRuntimeTakeOwnedString() below.

#pragma once

#include "lite_client_bridge.h"

#include <string>

namespace dragonx::wallet {

class LiteBridgeOwnedString {
public:
    using FreeStringFn = LiteClientBridgeApi::FreeStringFn;

    LiteBridgeOwnedString() = default;
    LiteBridgeOwnedString(char* rawValue, FreeStringFn freeString);
    LiteBridgeOwnedString(const LiteBridgeOwnedString&) = delete;
    LiteBridgeOwnedString& operator=(const LiteBridgeOwnedString&) = delete;
    LiteBridgeOwnedString(LiteBridgeOwnedString&& other) noexcept;
    LiteBridgeOwnedString& operator=(LiteBridgeOwnedString&& other) noexcept;
    ~LiteBridgeOwnedString();

    // Consume the owned string into a result (copy-before-free, free-once). Idempotent: a second
    // call returns an "already consumed" failure.
    LiteBridgeStringResult intoResult();

    bool rawPointerReceived() const { return rawPointerReceived_; }
    bool copiedBeforeFree() const { return copiedBeforeFree_; }
    bool freed() const { return freed_; }
    bool rawPointerEscaped() const { return false; }

private:
    void copyValueBeforeFree();
    void releaseRawValue();
    void moveFrom(LiteBridgeOwnedString&& other) noexcept;

    char* rawValue_ = nullptr;
    FreeStringFn freeString_ = nullptr;
    bool rawPointerReceived_ = false;
    bool copiedBeforeFree_ = false;
    bool freed_ = false;
    bool resultTaken_ = false;
    std::string copiedValue_;
};

// Take ownership of a backend-returned raw string and convert it to a result (copy-before-free,
// free-once) using the backend's deallocator. The single live entry point used by the bridge.
LiteBridgeStringResult liteBridgeRuntimeTakeOwnedString(
    char* rawValue,
    LiteClientBridgeApi::FreeStringFn freeString);

} // namespace dragonx::wallet
