package response

import (
	"encoding/json"
	"time"

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

// AIConfigResponse AI配置响应
type AIConfigResponse struct {
	ID           uint                   `json:"id"`
	Name         string                 `json:"name"`
	Provider     string                 `json:"provider"`
	BaseURL      string                 `json:"baseUrl"`
	APIKey       string                 `json:"apiKey"` // 前端显示时应该脱敏
	Models       []string               `json:"models"`
	DefaultModel string                 `json:"defaultModel"`
	Settings     map[string]interface{} `json:"settings"`
	IsActive     bool                   `json:"isActive"`
	IsDefault    bool                   `json:"isDefault"`
	CreatedAt    time.Time              `json:"createdAt"`
	UpdatedAt    time.Time              `json:"updatedAt"`
}

// AIConfigListResponse AI配置列表响应
type AIConfigListResponse struct {
	List  []AIConfigResponse `json:"list"`
	Total int64              `json:"total"`
}

// TestAIConfigResponse 测试AI配置响应
type TestAIConfigResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
	Latency int64  `json:"latency"` // 响应延迟(ms)
}

// GetModelsResponse 获取模型列表响应
type GetModelsResponse struct {
	Models []ModelInfo `json:"models"`
}

// ModelInfo 模型信息
type ModelInfo struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	OwnedBy string `json:"ownedBy"`
}

// ToAIConfigResponse 转换为AI配置响应结构
func ToAIConfigResponse(config *app.AIConfig) AIConfigResponse {
	resp := AIConfigResponse{
		ID:           config.ID,
		Name:         config.Name,
		Provider:     config.Provider,
		BaseURL:      config.BaseURL,
		APIKey:       maskAPIKey(config.APIKey),
		DefaultModel: config.DefaultModel,
		IsActive:     config.IsActive,
		IsDefault:    config.IsDefault,
		CreatedAt:    config.CreatedAt,
		UpdatedAt:    config.UpdatedAt,
	}

	// 解析 JSON 字段
	if len(config.Models) > 0 {
		var models []string
		json.Unmarshal(config.Models, &models)
		resp.Models = models
	}

	if len(config.Settings) > 0 {
		var settings map[string]interface{}
		json.Unmarshal(config.Settings, &settings)
		resp.Settings = settings
	}

	return resp
}

// maskAPIKey 脱敏API Key
func maskAPIKey(apiKey string) string {
	if len(apiKey) <= 8 {
		return "****"
	}
	return apiKey[:4] + "****" + apiKey[len(apiKey)-4:]
}
