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

package host

import (
	"encoding/json"
	"errors"

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

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

// MatchOptions represents the MatchOptions data structure.
// MatchOptions carries optional parameters for a match request.
type MatchOptions struct {
	Username string `json:"username"`
}

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

type matcherMatchSongsRequest struct {
	Songs []types.SongRef `json:"songs"`
	Opts  MatchOptions    `json:"opts"`
}

type matcherMatchSongsResponse struct {
	Results []*types.Track `json:"results,omitempty"`
	Error   string         `json:"error,omitempty"`
}

// MatcherMatchSongs calls the matcher_matchsongs host function.
// MatchSongs resolves each input song to its best-matching library track.
// It returns one entry per input song, in the same order as the input; the
// entry for an input song that had no match is empty (absent). Results are
// limited to the libraries the plugin (and the scoped user, if any) can access.
func MatcherMatchSongs(songs []types.SongRef, opts MatchOptions) ([]*types.Track, error) {
	// Marshal request to JSON
	req := matcherMatchSongsRequest{
		Songs: songs,
		Opts:  opts,
	}
	reqBytes, err := json.Marshal(req)
	if err != nil {
		return nil, err
	}
	reqMem := pdk.AllocateBytes(reqBytes)
	defer reqMem.Free()

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

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

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

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

	return response.Results, nil
}
