package fetchlink

import (
	"encoding/json"
	"fmt"
	"strings"
	"time"

	"be.ems/src/framework/logger"
	"be.ems/src/framework/utils/fetch"
	"be.ems/src/framework/utils/parse"
	"be.ems/src/modules/ne/model"
)

// NeState 获取网元端服务状态
func NeState(neInfo model.NeInfo) (map[string]any, error) {
	// 网元状态
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/systemManagement/v1/elementType/%s/objectType/systemState", neInfo.IP, neInfo.Port, strings.ToLower(neInfo.NeType))
	resBytes, err := fetch.Get(neUrl, nil, 1000)
	if err != nil {
		logger.Errorf("NeState %s", err.Error())
		return nil, fmt.Errorf("NeService System State API Error")
	}

	// 序列化结果
	var resData map[string]any
	err = json.Unmarshal(resBytes, &resData)
	if err != nil {
		logger.Errorf("NeState Unmarshal %s", err.Error())
		return nil, err
	}

	// 检查是否有许可时间
	if v, ok := resData["expiryDate"]; ok && v != nil {
		expiryDate := v.(string)
		// UPF存在2000的许可时间，MME会有空字符
		if strings.HasPrefix(expiryDate, "2000") || expiryDate == "" {
			logger.Warnf("NeState %s License Expiration Aanomaly. Get \"%s\"", neInfo.NeType, neUrl)
			return nil, fmt.Errorf("%s License Expiration Aanomaly", neInfo.NeType)
		}
	}

	info := map[string]any{
		"neType":      neInfo.NeType,
		"neId":        neInfo.NeId,
		"neName":      neInfo.NeName,
		"neIP":        neInfo.IP,
		"refreshTime": time.Now().UnixMilli(), // 获取时间
		"standby":     resData["standby"],     // 是否备用服务
		"version":     resData["version"],
		"capability":  resData["capability"],
		"sn":          resData["serialNum"],
		"expire":      resData["expiryDate"],
		"hostname":    resData["hostName"],
		"os":          resData["osInfo"],
		"cpu":         resData["cpuUsage"],
		"mem":         resData["memUsage"],
		"disk":        resData["diskSpace"],
	}

	if ueNumber, ok := resData["capability"]; ok {
		info["ueNumber"] = parse.Number(ueNumber)
	} else {
		info["ueNumber"] = 0
	}
	if nbNumber, ok := resData["nbNumber"]; ok {
		info["nbNumber"] = parse.Number(nbNumber)
	} else {
		info["nbNumber"] = 0
	}

	return info, nil
}
