package app

import (
	"encoding/json"
	"strings"

	"git.echol.cn/loser/ai_proxy/server/global"
	"git.echol.cn/loser/ai_proxy/server/model/app"
	"git.echol.cn/loser/ai_proxy/server/model/common/request"
	"git.echol.cn/loser/ai_proxy/server/model/common/response"
	"git.echol.cn/loser/ai_proxy/server/service"
	"git.echol.cn/loser/ai_proxy/server/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type AiPresetApi struct{}

var aiPresetService = service.ServiceGroupApp.AppServiceGroup.AiPresetService

// CreateAiPreset 创建预设
// @Tags AiPreset
// @Summary 创建预设
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body app.AiPreset true "预设信息"
// @Success 200 {object} response.Response{msg=string} "创建成功"
// @Router /aiPreset/createAiPreset [post]
func (a *AiPresetApi) CreateAiPreset(c *gin.Context) {
	var preset app.AiPreset
	err := c.ShouldBindJSON(&preset)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	preset.UserID = utils.GetUserID(c)

	if err := aiPresetService.CreateAiPreset(&preset); err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败", c)
	} else {
		response.OkWithMessage("创建成功", c)
	}
}

// DeleteAiPreset 删除预设
// @Tags AiPreset
// @Summary 删除预设
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.GetById true "ID"
// @Success 200 {object} response.Response{msg=string} "删除成功"
// @Router /aiPreset/deleteAiPreset [delete]
func (a *AiPresetApi) DeleteAiPreset(c *gin.Context) {
	var reqId request.GetById
	err := c.ShouldBindJSON(&reqId)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	userID := utils.GetUserID(c)

	if err := aiPresetService.DeleteAiPreset(reqId.Uint(), userID); err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
	} else {
		response.OkWithMessage("删除成功", c)
	}
}

// UpdateAiPreset 更新预设
// @Tags AiPreset
// @Summary 更新预设
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body app.AiPreset true "预设信息"
// @Success 200 {object} response.Response{msg=string} "更新成功"
// @Router /aiPreset/updateAiPreset [put]
func (a *AiPresetApi) UpdateAiPreset(c *gin.Context) {
	var preset app.AiPreset
	err := c.ShouldBindJSON(&preset)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	userID := utils.GetUserID(c)

	if err := aiPresetService.UpdateAiPreset(&preset, userID); err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败", c)
	} else {
		response.OkWithMessage("更新成功", c)
	}
}

// FindAiPreset 查询预设
// @Tags AiPreset
// @Summary 查询预设
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.GetById true "ID"
// @Success 200 {object} response.Response{data=app.AiPreset,msg=string} "查询成功"
// @Router /aiPreset/findAiPreset [get]
func (a *AiPresetApi) FindAiPreset(c *gin.Context) {
	var reqId request.GetById
	err := c.ShouldBindQuery(&reqId)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	userID := utils.GetUserID(c)

	if preset, err := aiPresetService.GetAiPreset(reqId.Uint(), userID); err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithData(preset, c)
	}
}

// GetAiPresetList 获取预设列表
// @Tags AiPreset
// @Summary 获取预设列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.PageInfo true "分页参数"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "获取成功"
// @Router /aiPreset/getAiPresetList [get]
func (a *AiPresetApi) GetAiPresetList(c *gin.Context) {
	var pageInfo request.PageInfo
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	userID := utils.GetUserID(c)

	if list, total, err := aiPresetService.GetAiPresetList(pageInfo, userID); err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	} else {
		response.OkWithDetailed(response.PageResult{
			List:     list,
			Total:    total,
			Page:     pageInfo.Page,
			PageSize: pageInfo.PageSize,
		}, "获取成功", c)
	}
}

// ImportAiPreset 导入预设(JSON粘贴)
// @Tags AiPreset
// @Summary 导入预设(支持SillyTavern格式)
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body app.AiPreset true "预设JSON"
// @Success 200 {object} response.Response{msg=string} "导入成功"
// @Router /aiPreset/importAiPreset [post]
func (a *AiPresetApi) ImportAiPreset(c *gin.Context) {
	var rawData map[string]interface{}
	err := c.ShouldBindJSON(&rawData)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	preset, err := aiPresetService.ParseImportedPreset(rawData, "")
	if err != nil {
		response.FailWithMessage("解析预设失败:"+err.Error(), c)
		return
	}
	preset.UserID = utils.GetUserID(c)

	if err := aiPresetService.CreateAiPreset(preset); err != nil {
		global.GVA_LOG.Error("导入失败!", zap.Error(err))
		response.FailWithMessage("导入失败:"+err.Error(), c)
	} else {
		response.OkWithMessage("导入成功", c)
	}
}

// ImportAiPresetFile 导入预设文件
// @Tags AiPreset
// @Summary 通过文件导入预设(支持SillyTavern格式)
// @Security ApiKeyAuth
// @accept multipart/form-data
// @Produce application/json
// @Param file formData file true "预设JSON文件"
// @Success 200 {object} response.Response{msg=string} "导入成功"
// @Router /aiPreset/importAiPresetFile [post]
func (a *AiPresetApi) ImportAiPresetFile(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		response.FailWithMessage("文件上传失败:"+err.Error(), c)
		return
	}

	// 检查文件类型
	if file.Header.Get("Content-Type") != "application/json" && !strings.HasSuffix(file.Filename, ".json") {
		response.FailWithMessage("只支持JSON文件", c)
		return
	}

	// 读取文件内容
	fileContent, err := file.Open()
	if err != nil {
		response.FailWithMessage("文件读取失败:"+err.Error(), c)
		return
	}
	defer fileContent.Close()

	// 解析JSON
	var rawData map[string]interface{}
	if err := json.NewDecoder(fileContent).Decode(&rawData); err != nil {
		response.FailWithMessage("JSON解析失败:"+err.Error(), c)
		return
	}

	// 从文件名提取预设名称（去掉 .json 后缀）
	fileName := file.Filename
	if strings.HasSuffix(fileName, ".json") {
		fileName = fileName[:len(fileName)-5]
	}

	preset, err := aiPresetService.ParseImportedPreset(rawData, fileName)
	if err != nil {
		response.FailWithMessage("解析预设失败:"+err.Error(), c)
		return
	}
	preset.UserID = utils.GetUserID(c)

	if err := aiPresetService.CreateAiPreset(preset); err != nil {
		global.GVA_LOG.Error("导入失败!", zap.Error(err))
		response.FailWithMessage("导入失败:"+err.Error(), c)
	} else {
		response.OkWithMessage("导入成功", c)
	}
}
