// plugin.go v1
package sandbox

import (
	"os"
	"path/filepath"
	"sync/atomic"

	"apigo.cc/gojs"
	"github.com/ssgo/config"
	"github.com/ssgo/u"
)

var pluginObject = gojs.Map{
	"start": Start,
	"fetch": Fetch,
	"query": Query,
}

var isRunning atomic.Bool

func init() {
	config.LoadConfig("sandbox", &pluginConfig)
	if pluginConfig.Root == "" {
		if wd, err := os.Getwd(); err == nil {
			pluginConfig.Root = filepath.Join(wd, "sandbox")
		}
	}
	pluginConfig.Root = u.GetAbsFilename(pluginConfig.Root)
	sandboxStoreFile = filepath.Join(pluginConfig.Root, ".sandboxlist.json")
	gojs.Register("apigo.cc/gojs/sandbox", gojs.Module{
		Object: gojs.ToMap(pluginObject),
		TsCode: gojs.MakeTSCode(pluginObject),
		OnKill: func() {
			isRunning.Store(false)
		},
	})

	onStart()
	go checkSandboxStatusTask()
	isRunning.Store(true)
}

// 异步起动，恢复所有已存在的沙箱进程
func onStart() {
	sandboxLock.Lock()
	u.Load(sandboxStoreFile, &sandboxStoreList)
	sandboxLock.Unlock()
	idLock.Lock()
	for id := range sandboxStoreList {
		currentIds[id] = true // 避免重复分配Id
	}
	idLock.Unlock()
	for id, ss := range sandboxStoreList {
		sb := Restore(id, ss.Config)
		if sb != nil {
			sandboxList[id] = sb // 恢复成功
		} else {
			delete(sandboxStoreList, id) // 进程已结束，从列表中移除
			delete(currentIds, id)       // 从当前Id列表中移除
		}
	}
	sandboxLock.Lock()
	u.Save(sandboxStoreFile, sandboxStoreList)
	sandboxLock.Unlock()
}
