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

package ndpdk

import (
	"encoding/binary"
	"encoding/json"
	"errors"

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

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

type streamGetStreamRequest struct {
	Uri string `json:"uri"`
}

// StreamGetStream calls the stream_getstream host function.
// GetStream returns raw binary stream data with content type.
func StreamGetStream(uri string) (string, []byte, error) {
	// Marshal request to JSON
	req := streamGetStreamRequest{
		Uri: uri,
	}
	reqBytes, err := json.Marshal(req)
	if err != nil {
		return "", nil, err
	}
	reqMem := pdk.AllocateBytes(reqBytes)
	defer reqMem.Free()

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

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

	// Parse binary-framed response
	if len(responseBytes) == 0 {
		return "", nil, errors.New("empty response from host")
	}
	if responseBytes[0] == 0x01 { // error
		return "", nil, errors.New(string(responseBytes[1:]))
	}
	if responseBytes[0] != 0x00 {
		return "", nil, errors.New("unknown response status")
	}
	if len(responseBytes) < 5 {
		return "", nil, errors.New("malformed raw response: incomplete header")
	}
	ctLen := binary.BigEndian.Uint32(responseBytes[1:5])
	if uint32(len(responseBytes)) < 5+ctLen {
		return "", nil, errors.New("malformed raw response: content-type overflow")
	}
	return string(responseBytes[5 : 5+ctLen]), responseBytes[5+ctLen:], nil
}
