package review_service

import (
	"encoding/json"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
	moderation "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/moderation/v3"
	moderationRegion "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/moderation/v3/region"
	ocr "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ocr/v1"
	ocrRegion "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ocr/v1/region"
	"io/ioutil"
	"log"
	"sync"
)

type Config struct {
	Ak        string                       `json:"review_ak"`
	Sk        string                       `json:"review_sk"`
	ProjectId string                       `json:"project_id"`
	Client    *moderation.ModerationClient `json:"client"`
	OcrClient *ocr.OcrClient               `json:"ocr_client"`
}

const configFile = "app/config/review_config.json"

var configInstance *Config
var once sync.Once

// 加载配置文件
func loadConfig() *Config {
	data, err := ioutil.ReadFile(configFile)
	if err != nil {
		log.Fatalf("Failed to read config file: %v", err)
	}

	var config Config
	err = json.Unmarshal(data, &config)
	if err != nil {
		log.Fatalf("Failed to parse config file: %v", err)
	}

	auth := basic.NewCredentialsBuilder().
		WithAk(config.Ak).
		WithSk(config.Sk).
		//WithProjectId(projectId).
		Build()

	client := moderation.NewModerationClient(
		moderation.ModerationClientBuilder().
			WithRegion(moderationRegion.ValueOf("cn-north-4")).
			WithCredential(auth).
			Build())

	ocrClient := ocr.NewOcrClient(
		ocr.OcrClientBuilder().
			WithRegion(ocrRegion.ValueOf("cn-north-4")).
			WithCredential(auth).
			Build())

	config.Client = client
	config.OcrClient = ocrClient

	return &config
}

// 获取配置的单例实例
func GetConfig() *Config {
	once.Do(func() {
		configInstance = loadConfig()
	})
	return configInstance
}
