// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the Math host service.
// It is intended for use in Navidrome plugins built with TinyGo.
//
//go:build wasip1

package ndhost

import (
	"encoding/json"
	"errors"

	"github.com/navidrome/navidrome/plugins/pdk/go/pdk"
)

// math_add is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user math_add
func math_add(uint64) uint64

type mathAddRequest struct {
	A int32 `json:"a"`
	B int32 `json:"b"`
}

type mathAddResponse struct {
	Result int32  `json:"result,omitempty"`
	Error  string `json:"error,omitempty"`
}

// MathAdd calls the math_add host function.
func MathAdd(a int32, b int32) (int32, error) {
	// Marshal request to JSON
	req := mathAddRequest{
		A: a,
		B: b,
	}
	reqBytes, err := json.Marshal(req)
	if err != nil {
		return 0, err
	}
	reqMem := pdk.AllocateBytes(reqBytes)
	defer reqMem.Free()

	// Call the host function
	responsePtr := math_add(reqMem.Offset())

	// Read the response from memory
	responseMem := pdk.FindMemory(responsePtr)
	responseBytes := responseMem.ReadBytes()

	// Parse the response
	var response mathAddResponse
	if err := json.Unmarshal(responseBytes, &response); err != nil {
		return 0, err
	}

	// Convert Error field to Go error
	if response.Error != "" {
		return 0, errors.New(response.Error)
	}

	return response.Result, nil
}
