package controllers

import (
	"crypto/ecdsa"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/common/hexutil"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/log"
	_ "image/gif"  // 导入 GIF 支持
	_ "image/jpeg" // 导入 JPEG 支持
	_ "image/png"  // 导入 PNG 支持
	"net/http"
	"os"
	"time"
	"token-uri/models"
)

type LLMController struct {
	BaseController
}

func (c *LLMController) GetContainerSign() {
	signData := &models.TaskInfo{}
	reqData := c.Ctx.Input.RequestBody
	err := json.Unmarshal(reqData, signData)
	if err != nil {
		c.ResponseInfo(500, "sign container failed", nil)
		return
	}
	signPrv := beego.AppConfig.String("sign_prv")
	if signData.TaskResult == "" || signData.TaskParam == "" || signData.TaskId == "" {
		c.ResponseInfo(500, "sign container is failed", nil)
		return
	}
	bridgePrv := stringToPrivateKey(signPrv)
	reqHash := crypto.Keccak256Hash([]byte(signData.TaskParam))
	respHash := crypto.Keccak256Hash([]byte(signData.TaskResult))
	signHash := crypto.Keccak256Hash([]byte(signData.TaskId), reqHash.Bytes(), respHash.Bytes())
	fmt.Println("signHash :", signHash.String())
	signature, err := crypto.Sign(signHash.Bytes(), bridgePrv)
	if err != nil {
		return
	}
	signHex := common.Bytes2Hex(signature)
	fmt.Println("signature :", signHex)
	containerPubKey, err := crypto.SigToPub(signHash.Bytes(), signature)
	fmt.Println("container address:", crypto.PubkeyToAddress(*containerPubKey).String())
	c.ResponseInfo(200, "sign container successful", signHex)
}

func (c *LLMController) GetImage() {
	filePath := "response.png" // 替换为实际图片文件路径
	// 打开图片文件
	file, err := os.Open(filePath)
	if err != nil {
		log.Error("Error opening file:", err)
		c.ResponseInfo(500, "Error opening file:", err)
		return
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			log.Error("Error closing file:", err)
		}
	}(file)

	// 设置 Content-Type 为图片类型
	c.Ctx.Output.Header("Content-Type", "image/jpeg")

	http.ServeContent(c.Ctx.ResponseWriter, c.Ctx.Request, "", time.Now(), file)

}

func (c *LLMController) GetText() {
	c.ResponseInfo(200, "sss", nil)
}

func (c *LLMController) GetExecRes() {
	time.Sleep(time.Second * 5)
	c.ResponseInfo(200, "OK", "https://paint4art.oss-cn-beijing.aliyuncs.com/aiimages/SN90P6aKwh.jpg")
}

func stringToPrivateKey(privateKeyStr string) *ecdsa.PrivateKey {
	privateKeyByte, err := hexutil.Decode(privateKeyStr)
	if err != nil {
		return nil
	}
	privateKey, err := crypto.ToECDSA(privateKeyByte)
	if err != nil {
		return nil
	}
	return privateKey
}
