package xray

import (
	"context"
	"errors"
	"runtime/debug"
	"strings"
	"sync"

	"github.com/xtls/libxray/memory"
	"github.com/xtls/xray-core/core"
	"github.com/xtls/xray-core/features/inbound"
	_ "github.com/xtls/xray-core/main/distro/all"
	"github.com/xtls/xray-core/proxy"
	"github.com/xtls/xray-core/proxy/tun"
)

var (
	coreServerMu     sync.Mutex
	coreServer       *core.Instance
	coreProbeContext context.Context
	coreProbeCancel  context.CancelFunc
)

var ErrAlreadyRunning = errors.New("xray is already running")

func newXrayInstance(xrayJSON string) (*core.Instance, error) {
	config, err := core.LoadConfig("json", strings.NewReader(xrayJSON))
	if err != nil {
		return nil, err
	}

	server, err := core.New(config)
	if err != nil {
		return nil, err
	}

	return server, nil
}

// Run Xray instance.
// xrayJSON is the serialized Xray JSON configuration.
func RunXray(xrayJSON string) error {
	coreServerMu.Lock()
	defer coreServerMu.Unlock()
	if coreServer != nil {
		return ErrAlreadyRunning
	}
	memory.InitForceFree()
	server, err := newXrayInstance(xrayJSON)
	if err != nil {
		return err
	}
	if err = server.Start(); err != nil {
		_ = server.Close()
		return err
	}
	coreServer = server
	coreProbeContext, coreProbeCancel = context.WithCancel(context.Background())

	debug.FreeOSMemory()
	return nil
}

// Get Xray State
func GetXrayState() bool {
	coreServerMu.Lock()
	defer coreServerMu.Unlock()
	return coreServer != nil && coreServer.IsRunning()
}

// ManagedXrayState adds local TUN lifecycle evidence without claiming traffic
// forwarding. Missing readers and inactive instances are not reader failures.
type ManagedXrayState struct {
	Running    bool                       `json:"running"`
	TUNReaders map[string]tun.ReaderState `json:"tunReaders,omitempty"`
}

func GetManagedXrayState() ManagedXrayState {
	coreServerMu.Lock()
	defer coreServerMu.Unlock()
	result := ManagedXrayState{Running: coreServer != nil && coreServer.IsRunning()}
	if !result.Running {
		return result
	}
	if manager, ok := coreServer.GetFeature(inbound.ManagerType()).(inbound.Manager); ok {
		result.TUNReaders = managedTUNReaders(manager.ListHandlers(context.Background()))
	}
	return result
}

func managedTUNReaders(handlers []inbound.Handler) map[string]tun.ReaderState {
	result := make(map[string]tun.ReaderState)
	for _, handler := range handlers {
		unwrapped, ok := handler.(interface{ GetInbound() proxy.Inbound })
		if !ok {
			continue
		}
		reader, ok := unwrapped.GetInbound().(interface{ TUNReaderState() tun.ReaderState })
		if !ok {
			continue
		}
		result[handler.Tag()] = reader.TUNReaderState()
	}
	return result
}

// Stop Xray instance.
func StopXray() error {
	coreServerMu.Lock()
	defer coreServerMu.Unlock()
	if coreServer != nil {
		if coreProbeCancel != nil {
			coreProbeCancel()
		}
		err := coreServer.Close()
		coreServer = nil
		coreProbeContext, coreProbeCancel = nil, nil
		if err != nil {
			return err
		}
	}
	return nil
}

// Xray's version
func XrayVersion() string {
	return core.Version()
}
