// Code generated by ndpgen. DO NOT EDIT.

package testpkg

import (
	"context"
	"encoding/json"

	extism "github.com/extism/go-sdk"
	"github.com/navidrome/navidrome/plugins/streams"
)

// wireDownload is the wire form of Download: streams travel as handles.
type wireDownload struct {
	Size int64  `json:"size"`
	Body uint32 `json:"body"`
}

func downloadFromWire(w wireDownload, conv *streams.Conv) Download {
	return Download{
		Size: w.Size,
		Body: conv.Reader(w.Body),
	}
}

func downloadPtrFromWire(w *wireDownload, conv *streams.Conv) *Download {
	if w == nil {
		return nil
	}
	v := downloadFromWire(*w, conv)
	return &v
}

func downloadToWire(v Download, conv *streams.Conv) wireDownload {
	return wireDownload{
		Size: v.Size,
		Body: conv.ReaderHandle(v.Body),
	}
}

func downloadPtrToWire(v *Download, conv *streams.Conv) *wireDownload {
	if v == nil {
		return nil
	}
	w := downloadToWire(*v, conv)
	return &w
}

// wireUpload is the wire form of Upload: streams travel as handles.
type wireUpload struct {
	Name string `json:"name"`
	Body uint32 `json:"body"`
}

func uploadFromWire(w wireUpload, conv *streams.Conv) Upload {
	return Upload{
		Name: w.Name,
		Body: conv.Reader(w.Body),
	}
}

func uploadPtrFromWire(w *wireUpload, conv *streams.Conv) *Upload {
	if w == nil {
		return nil
	}
	v := uploadFromWire(*w, conv)
	return &v
}

func uploadToWire(v Upload, conv *streams.Conv) wireUpload {
	return wireUpload{
		Name: v.Name,
		Body: conv.ReaderHandle(v.Body),
	}
}

func uploadPtrToWire(v *Upload, conv *streams.Conv) *wireUpload {
	if v == nil {
		return nil
	}
	w := uploadToWire(*v, conv)
	return &w
}

// BlobOpenRequest is the request type for Blob.Open.
type BlobOpenRequest struct {
	Name string `json:"name"`
}

// BlobOpenResponse is the response type for Blob.Open.
type BlobOpenResponse struct {
	Result uint32 `json:"result,omitempty"`
	Error  string `json:"error,omitempty"`
}

// BlobCreateRequest is the request type for Blob.Create.
type BlobCreateRequest struct {
	Name string `json:"name"`
}

// BlobCreateResponse is the response type for Blob.Create.
type BlobCreateResponse struct {
	Result uint32 `json:"result,omitempty"`
	Error  string `json:"error,omitempty"`
}

// BlobPutRequest is the request type for Blob.Put.
type BlobPutRequest struct {
	Upload wireUpload `json:"upload"`
}

// BlobPutResponse is the response type for Blob.Put.
type BlobPutResponse struct {
	Result *wireDownload `json:"result,omitempty"`
	Error  string        `json:"error,omitempty"`
}

// BlobCopyRequest is the request type for Blob.Copy.
type BlobCopyRequest struct {
	Src uint32 `json:"src"`
	Dst uint32 `json:"dst"`
}

// BlobCopyResponse is the response type for Blob.Copy.
type BlobCopyResponse struct {
	Result int64  `json:"result,omitempty"`
	Error  string `json:"error,omitempty"`
}

// RegisterBlobHostFunctions registers Blob service host functions.
// The returned host functions should be added to the plugin's configuration.
func RegisterBlobHostFunctions(service BlobService) []extism.HostFunction {
	return []extism.HostFunction{
		newBlobOpenHostFunction(service),
		newBlobCreateHostFunction(service),
		newBlobPutHostFunction(service),
		newBlobCopyHostFunction(service),
	}
}

func newBlobOpenHostFunction(service BlobService) extism.HostFunction {
	return extism.NewHostFunctionWithStack(
		"blob_open",
		func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
			conv := streams.NewConv(ctx)

			// Read JSON request from plugin memory
			reqBytes, err := p.ReadBytes(stack[0])
			if err != nil {
				blobWriteError(p, stack, err)
				return
			}
			var req BlobOpenRequest
			if err := json.Unmarshal(reqBytes, &req); err != nil {
				blobWriteError(p, stack, err)
				return
			}

			// Call the service method
			result, svcErr := service.Open(ctx, req.Name)
			if svcErr != nil {
				conv.Fail(svcErr)
			}

			// Write JSON response to plugin memory
			resp := BlobOpenResponse{
				Result: conv.ReaderHandle(result),
			}
			if err := conv.Err(); err != nil {
				blobWriteError(p, stack, err)
				return
			}
			blobWriteStreamResponse(p, stack, resp, conv)
		},
		[]extism.ValueType{extism.ValueTypePTR},
		[]extism.ValueType{extism.ValueTypePTR},
	)
}

func newBlobCreateHostFunction(service BlobService) extism.HostFunction {
	return extism.NewHostFunctionWithStack(
		"blob_create",
		func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
			conv := streams.NewConv(ctx)

			// Read JSON request from plugin memory
			reqBytes, err := p.ReadBytes(stack[0])
			if err != nil {
				blobWriteError(p, stack, err)
				return
			}
			var req BlobCreateRequest
			if err := json.Unmarshal(reqBytes, &req); err != nil {
				blobWriteError(p, stack, err)
				return
			}

			// Call the service method
			result, svcErr := service.Create(ctx, req.Name)
			if svcErr != nil {
				conv.Fail(svcErr)
			}

			// Write JSON response to plugin memory
			resp := BlobCreateResponse{
				Result: conv.WriterHandle(result),
			}
			if err := conv.Err(); err != nil {
				blobWriteError(p, stack, err)
				return
			}
			blobWriteStreamResponse(p, stack, resp, conv)
		},
		[]extism.ValueType{extism.ValueTypePTR},
		[]extism.ValueType{extism.ValueTypePTR},
	)
}

func newBlobPutHostFunction(service BlobService) extism.HostFunction {
	return extism.NewHostFunctionWithStack(
		"blob_put",
		func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
			conv := streams.NewConv(ctx)

			// Read JSON request from plugin memory
			reqBytes, err := p.ReadBytes(stack[0])
			if err != nil {
				blobWriteError(p, stack, err)
				return
			}
			var req BlobPutRequest
			if err := json.Unmarshal(reqBytes, &req); err != nil {
				blobWriteError(p, stack, err)
				return
			}
			argUpload := uploadFromWire(req.Upload, conv)
			if err := conv.Err(); err != nil {
				blobWriteError(p, stack, err)
				return
			}

			// Call the service method
			result, svcErr := service.Put(ctx, argUpload)
			if svcErr != nil {
				conv.Fail(svcErr)
			}

			// Write JSON response to plugin memory
			resp := BlobPutResponse{
				Result: downloadPtrToWire(result, conv),
			}
			if err := conv.Err(); err != nil {
				blobWriteError(p, stack, err)
				return
			}
			blobWriteStreamResponse(p, stack, resp, conv)
		},
		[]extism.ValueType{extism.ValueTypePTR},
		[]extism.ValueType{extism.ValueTypePTR},
	)
}

func newBlobCopyHostFunction(service BlobService) extism.HostFunction {
	return extism.NewHostFunctionWithStack(
		"blob_copy",
		func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
			conv := streams.NewConv(ctx)

			// Read JSON request from plugin memory
			reqBytes, err := p.ReadBytes(stack[0])
			if err != nil {
				blobWriteError(p, stack, err)
				return
			}
			var req BlobCopyRequest
			if err := json.Unmarshal(reqBytes, &req); err != nil {
				blobWriteError(p, stack, err)
				return
			}
			argSrc := conv.Reader(req.Src)
			argDst := conv.Writer(req.Dst)
			if err := conv.Err(); err != nil {
				blobWriteError(p, stack, err)
				return
			}

			// Call the service method
			result, svcErr := service.Copy(ctx, argSrc, argDst)
			if svcErr != nil {
				conv.Fail(svcErr)
			}

			// Write JSON response to plugin memory
			resp := BlobCopyResponse{
				Result: result,
			}
			if err := conv.Err(); err != nil {
				blobWriteError(p, stack, err)
				return
			}
			blobWriteStreamResponse(p, stack, resp, conv)
		},
		[]extism.ValueType{extism.ValueTypePTR},
		[]extism.ValueType{extism.ValueTypePTR},
	)
}

// blobWriteResponse writes a JSON response to plugin memory.
func blobWriteResponse(p *extism.CurrentPlugin, stack []uint64, resp any) {
	respBytes, err := json.Marshal(resp)
	if err != nil {
		blobWriteError(p, stack, err)
		return
	}
	respPtr, err := p.WriteBytes(respBytes)
	if err != nil {
		stack[0] = 0
		return
	}
	stack[0] = respPtr
}

// blobWriteStreamResponse writes a response with stream handles, and releases the streams
// when it cannot: the plugin would never get the handles.
func blobWriteStreamResponse(p *extism.CurrentPlugin, stack []uint64, resp any, conv *streams.Conv) {
	respBytes, err := json.Marshal(resp)
	if err == nil {
		stack[0], err = p.WriteBytes(respBytes)
	}
	if err != nil {
		conv.Release()
		blobWriteError(p, stack, err)
	}
}

// blobWriteError writes an error response to plugin memory.
func blobWriteError(p *extism.CurrentPlugin, stack []uint64, err error) {
	errResp := struct {
		Error string `json:"error"`
	}{Error: err.Error()}
	respBytes, _ := json.Marshal(errResp)
	respPtr, _ := p.WriteBytes(respBytes)
	stack[0] = respPtr
}
