package handler

import (
	"net/http"

	"github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/internal/service"
	"github.com/gin-gonic/gin"
)

// AIHandler AI相关处理器
type AIHandler struct {
	aiService service.AIService
}

// NewAIHandler 创建AI处理器
func NewAIHandler() *AIHandler {
	return &AIHandler{
		aiService: service.NewAIService(),
	}
}

// WritingCorrectionRequest 写作批改请求
type WritingCorrectionRequest struct {
	Content  string `json:"content" binding:"required"`
	TaskType string `json:"task_type" binding:"required"`
}

// CorrectWriting 写作批改
func (h *AIHandler) CorrectWriting(c *gin.Context) {
	var req WritingCorrectionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":   "Invalid request parameters",
			"details": err.Error(),
		})
		return
	}

	// 调用AI服务进行写作批改
	result, err := h.aiService.CorrectWriting(c.Request.Context(), req.Content, req.TaskType)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "AI service error",
			"details": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "Writing correction completed",
		"data":    result,
	})
}

// SpeakingEvaluationRequest 口语评估请求
type SpeakingEvaluationRequest struct {
	AudioText string `json:"audio_text" binding:"required"`
	Prompt    string `json:"prompt" binding:"required"`
}

// EvaluateSpeaking 口语评估
func (h *AIHandler) EvaluateSpeaking(c *gin.Context) {
	var req SpeakingEvaluationRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":   "Invalid request parameters",
			"details": err.Error(),
		})
		return
	}

	// 调用AI服务进行口语评估
	result, err := h.aiService.EvaluateSpeaking(c.Request.Context(), req.AudioText, req.Prompt)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "AI service error",
			"details": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "Speaking evaluation completed",
		"data":    result,
	})
}

// GetAIUsageStats 获取AI使用统计
func (h *AIHandler) GetAIUsageStats(c *gin.Context) {
	// TODO: 实现实际的统计查询逻辑
	// 目前返回模拟数据
	stats := gin.H{
		"writing_corrections":  15,
		"speaking_evaluations": 8,
		"recommendations":      5,
		"exercises_generated":  12,
		"total_requests":       40,
		"this_month_requests":  15,
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "AI usage statistics",
		"data":    stats,
	})
}