package host

import (
	"context"
	"easyaudioencode/internal/conf"
	"easyaudioencode/pkg/pluginheart"
	"encoding/json"
	"fmt"
	"log/slog"

	"git.lnton.com/lnton/pluginsdk/pkg/data"
	"git.lnton.com/lnton/pluginsdk/pkg/plugin"
)

type Core struct {
	Plugin     *plugin.PluginSDK   // 用于业务GRPC通信
	HttpPlugin *pluginheart.Engine // 用于插件管理HTTP通信
	RtspConfig *ConfigBaseOutput
}

var StartOk chan struct{}

func NewCore(cfg *conf.Bootstrap) *Core {
	cb := plugin.PluginCallback{
		OnShutdown: func() { slog.Info("Plugin shutting down") },
	}
	sdk, err := plugin.NewPlugin(data.Plugin{
		ID:         "EasyAudioEncode",
		Name:       "EasyAudioEncode",
		Version:    "1.0.0",
		ServerAddr: fmt.Sprintf("%s:%d", "localhost", cfg.Plugin.GrpcPort),
	}, cb)
	if err != nil {
		panic(err)
	}

	engine := pluginheart.NewEngine("easyaudioencode", cfg.Plugin.HttpAPI)

	// 后台等待启动完成信号，然后触发心跳（不阻塞主流程）
	go func() {
		StartOk = make(chan struct{})
		<-StartOk
		engine.AutoHeart(pluginheart.HeartInput{
			Port: cfg.Server.HTTP.Port,
		}, false)
	}()

	c := &Core{
		Plugin:     sdk,
		HttpPlugin: engine,
	}

	sdk.AddResponseHandler("stop", c.stop)
	sdk.AddResponseHandler("ping", c.ping)

	// 这部分都是收到响应后的回调
	sdk.AddResponseHandler("findDevices", c.findDevicesRespH)
	sdk.AddResponseHandler("findChannels", c.findChannelsRespH)
	sdk.AddResponseHandler("getBaseConfig", c.getBaseConfigRespH)
	sdk.AddResponseHandler("findTalkUrl", c.findTalkUrlRespH)

	config, err := c.GetBaseConfig(context.TODO(), &ConfigBaseInput{Mode: "rtsp"})
	if err != nil {
		panic(err)
	}
	// defer sdk.Close()
	return &Core{
		Plugin:     sdk,
		RtspConfig: config,
	}
}

func (c Core) stop(requestID string, args json.RawMessage) (interface{}, error) {
	slog.Info("Received 'stop' from host", "request_id", requestID)
	return map[string]interface{}{"status": "stopped"}, nil
}

func (c Core) ping(requestID string, args json.RawMessage) (interface{}, error) {
	return nil, nil
}

func (c Core) findDevicesRespH(requestID string, args json.RawMessage) (interface{}, error) {
	slog.Debug("Received 'findDeviceList' from host", "request_id", requestID, "args", args)
	return nil, nil
}

func (c Core) findChannelsRespH(requestID string, args json.RawMessage) (interface{}, error) {
	slog.Debug("Received 'findChannels' from host", "request_id", requestID, "args", args)
	return nil, nil
}
func (c Core) getBaseConfigRespH(requestID string, args json.RawMessage) (interface{}, error) {
	slog.Debug("Received 'getBaseConfig' from host", "request_id", requestID, "args", args)
	return nil, nil
}
func (c Core) findTalkUrlRespH(requestID string, args json.RawMessage) (interface{}, error) {
	slog.Debug("Received 'findTalkUrl' from host", "request_id", requestID, "args", args)
	return nil, nil
}
