package ai

import (
	"bytes"
	"context"
	"crypto/tls"
	"encoding/json"
	"github.com/go-resty/resty/v2"
	"github.com/pkg/errors"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils/hws"
	"net/http"

	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProxyApiLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewProxyApiLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProxyApiLogic {
	return &ProxyApiLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

const (
	XProjectID  = "d18190e28e3f45a281ef0b0696ec9d52"
	XStage      = "RELEASE"
	ContentType = "application/json"
)

func (l *ProxyApiLogic) ProxyApi(req *types.ChatReq) (resp *types.ChatResult, err error) {
	logx.Infof("【开始处理请求，目标URL: %s】", req.ApiUrl)

	jsonBytes, err := json.Marshal(&req.ReqData)
	if err != nil {
		logx.Errorf("【序列化请求数据失败: %v】", err)
		return nil, errors.New("请求数据序列化失败")
	}

	resp = &types.ChatResult{}

	// 构建 HTTP 请求
	request, err := http.NewRequest("POST", req.ApiUrl, bytes.NewBuffer(jsonBytes))
	if err != nil {
		logx.Errorf("【构建 HTTP 请求失败: %v】", err)
		return nil, errors.New("网络错误，请稍后重试")
	}

	signer := &hws.Signer{
		Key:    "UNEHPHO4Z7YSNPKRXFE4",
		Secret: "JWXCE9qcYbc7RjpSRIWt4WgG3ZKF6Q4lPzkJReX9",
	}

	if err := signer.Sign(request); err != nil {
		logx.Errorf("【接口签名错误: %v】", err)
		return nil, errors.New("网络错误，请稍后重试")
	}

	client := resty.New().SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})

	response, err := client.R().
		SetHeader("X-Project-Id", XProjectID).
		SetHeader("x-stage", XStage).
		SetHeader("Content-Type", ContentType).
		SetHeader("Authorization", request.Header.Get(hws.HeaderXAuthorization)).
		SetHeader("X-Sdk-Date", request.Header.Get(hws.HeaderXDateTime)).
		SetBody(jsonBytes).
		SetResult(&resp).
		Post(req.ApiUrl)

	if err != nil {
		logx.Errorf("【远程调用接口URL:%s， 返回错误: %s】", req.ApiUrl, err.Error())
		return nil, errors.New("网络错误，请稍后重试")
	}

	if response.StatusCode() != 200 {
		logx.Errorf("【远程调用接口URL:%s， 返回错误: %s】", req.ApiUrl, response.Body())
		return nil, errors.New("网络错误，请稍后重试")
	}

	logx.Infof("【请求处理成功，目标URL: %s】", req.ApiUrl)
	return resp, nil
}
