package response

import (
	"encoding/json"
	"time"

	"git.echol.cn/loser/st/server/model/app"
)

// ConversationResponse 对话响应
type ConversationResponse struct {
	ID               uint                   `json:"id"`
	CharacterID      uint                   `json:"characterId"`
	Title            string                 `json:"title"`
	PresetID         *uint                  `json:"presetId"`
	WorldbookID      *uint                  `json:"worldbookId"`
	WorldbookEnabled bool                   `json:"worldbookEnabled"`
	AIProvider       string                 `json:"aiProvider"`
	Model            string                 `json:"model"`
	Settings         map[string]interface{} `json:"settings,omitempty"`
	MessageCount     int                    `json:"messageCount"`
	TokenCount       int                    `json:"tokenCount"`
	CreatedAt        time.Time              `json:"createdAt"`
	UpdatedAt        time.Time              `json:"updatedAt"`

	// 关联数据
	Character *CharacterResponse `json:"character,omitempty"`
}

// ConversationListItemResponse 对话列表项响应（轻量级）
type ConversationListItemResponse struct {
	ID           uint                     `json:"id"`
	CharacterID  uint                     `json:"characterId"`
	Title        string                   `json:"title"`
	MessageCount int                      `json:"messageCount"`
	TokenCount   int                      `json:"tokenCount"`
	CreatedAt    time.Time                `json:"createdAt"`
	UpdatedAt    time.Time                `json:"updatedAt"`
	Character    *CharacterSimpleResponse `json:"character,omitempty"`
}

// MessageResponse 消息响应
type MessageResponse struct {
	ID             uint      `json:"id"`
	ConversationID uint      `json:"conversationId"`
	Role           string    `json:"role"`
	Content        string    `json:"content"`
	TokenCount     int       `json:"tokenCount"`
	CreatedAt      time.Time `json:"createdAt"`
}

// ConversationListResponse 对话列表响应
type ConversationListResponse struct {
	List     []ConversationListItemResponse `json:"list"`
	Total    int64                          `json:"total"`
	Page     int                            `json:"page"`
	PageSize int                            `json:"pageSize"`
}

// MessageListResponse 消息列表响应
type MessageListResponse struct {
	List     []MessageResponse `json:"list"`
	Total    int64             `json:"total"`
	Page     int               `json:"page"`
	PageSize int               `json:"pageSize"`
}

// ToConversationResponse 转换为对话响应结构
func ToConversationResponse(conv *app.Conversation) ConversationResponse {
	// 解析 settings JSON
	var settings map[string]interface{}
	if len(conv.Settings) > 0 {
		// 尝试解析 JSON,如果失败则返回 nil
		if err := json.Unmarshal(conv.Settings, &settings); err != nil {
			settings = nil
		}
	}

	return ConversationResponse{
		ID:               conv.ID,
		CharacterID:      conv.CharacterID,
		Title:            conv.Title,
		PresetID:         conv.PresetID,
		WorldbookID:      conv.WorldbookID,
		WorldbookEnabled: conv.WorldbookEnabled,
		AIProvider:       conv.AIProvider,
		Model:            conv.Model,
		Settings:         settings,
		MessageCount:     conv.MessageCount,
		TokenCount:       conv.TokenCount,
		CreatedAt:        conv.CreatedAt,
		UpdatedAt:        conv.UpdatedAt,
	}
}

// ToMessageResponse 转换为消息响应结构
func ToMessageResponse(msg *app.Message) MessageResponse {
	return MessageResponse{
		ID:             msg.ID,
		ConversationID: msg.ConversationID,
		Role:           msg.Role,
		Content:        msg.Content,
		TokenCount:     msg.TokenCount,
		CreatedAt:      msg.CreatedAt,
	}
}

// ToConversationListItemResponse 转换为对话列表项响应结构（轻量级）
func ToConversationListItemResponse(conv *app.Conversation, character *app.AICharacter) ConversationListItemResponse {
	resp := ConversationListItemResponse{
		ID:           conv.ID,
		CharacterID:  conv.CharacterID,
		Title:        conv.Title,
		MessageCount: conv.MessageCount,
		TokenCount:   conv.TokenCount,
		CreatedAt:    conv.CreatedAt,
		UpdatedAt:    conv.UpdatedAt,
	}

	if character != nil {
		simpleChar := ToCharacterSimpleResponse(character)
		resp.Character = &simpleChar
	}

	return resp
}
