package main

import (
	database "PsycheEpic/src/datasource"
	"fmt"
	"log"
	"os"
	"strconv"
)

// 假设的聊天记录数据类型
type Record struct {
	SenderId   int64
	Timestamp  int64
	Message    string
	Status     map[string]interface{}
	SenderType string
}

// 用于存储和计算每个指标的总值和出现的次数
type IndicatorStat struct {
	Values map[int]bool
	Total  int
	Count  int
}

func main() {
	// 模拟的从数据库获取的数据
	records := []database.ChatRecord{
		{
			SenderId: 25,
			Status: map[string]interface{}{
				"用户分析": map[string]string{
					"冲动倾向": "10",
					"孤独倾向": "10",
					"学习焦虑": "9",
					"对人焦虑": "10",
					"恐怖倾向": "10",
					"自责倾向": "10",
					"身体症状": "10",
					"过敏倾向": "10",
				},
			},
			SenderType: "bot",
		},
		{
			SenderId: 25,
			Status: map[string]interface{}{
				"用户分析": map[string]string{
					"冲动倾向": "10",
					"孤独倾向": "10",
					"学习焦虑": "9",
					"对人焦虑": "10",
					"恐怖倾向": "10",
					"自责倾向": "10",
					"身体症状": "10",
					"过敏倾向": "9",
				},
			},
			SenderType: "bot",
		},
		{
			SenderId:  25,
			Timestamp: 1709019129,
			Message:   "“你是独一无二的你，不必被标签定义。身高体重不是衡量你价值的标准。学习焦虑是常见的挑战，但不代表你不能克服。让我们一起探讨如何应对学习焦虑，找到更适合自己的学习方式吧。” 轻声倡导，鼓励探索。 \n\n ",
			Status: map[string]interface{}{
				"内心活动": "积极引导用户发现自身潜力",
				"表情":   "鼓励",
			},
			SenderType: "bot",
		},
	}

	stats := CalculateAverageAnalysis(records)
	//SaveResults(stats)
	for key, val := range stats {
		if val.Count > 0 {
			fmt.Printf("%s avg: %.2f\n", key, float64(val.Total)/float64(val.Count))
		} else {
			fmt.Printf("%s avg: %d\n", key, 0)
		}
	}
}

func calculateAverageAnalysis2(records []Record) map[string]*IndicatorStat {
	stats := make(map[string]*IndicatorStat)

	for _, record := range records {
		if record.SenderType != "bot" {
			continue
		}

		if userAnalysis, ok := record.Status["用户分析"].(map[string]string); ok {
			for key, value := range userAnalysis {
				if _, exists := stats[key]; !exists {
					stats[key] = &IndicatorStat{
						Values: make(map[int]bool),
						Total:  0,
						Count:  0,
					}
				}
				valueInt, err := strconv.Atoi(value)
				if err != nil {
					continue
				}
				if !stats[key].Values[valueInt] {
					stats[key].Values[valueInt] = true
					stats[key].Total += valueInt
					stats[key].Count++
				}
			}
		}

	}

	return stats
}

func SaveResults(stats map[string]*IndicatorStat) {
	file, err := os.Create("analysis_results.txt")
	if err != nil {
		fmt.Println("Error creating file:", err)
		return
	}
	defer file.Close()

	for key, val := range stats {
		if val.Count > 0 {
			fmt.Fprintf(file, "%s avg: %.2f\n", key, float64(val.Total)/float64(val.Count))
		} else {
			fmt.Fprintf(file, "%s avg: %d\n", key, 0)
		}
	}
	fmt.Println("Results saved to analysis_results.txt")
}

func CalculateAverageAnalysis(records []database.ChatRecord) map[string]*IndicatorStat {
	allowedMetrics := map[string]bool{
		"对人焦虑": true,
		"冲动倾向": true,
		"学习焦虑": true,
		"孤独倾向": true,
		"恐怖倾向": true,
		"身体症状": true,
		"自责倾向": true,
		"过敏倾向": true,
	}

	stats := make(map[string]*IndicatorStat)
	lastValuesMap := make(map[string]int)

	for _, record := range records {
		if record.SenderType != "bot" {
			continue
		}

		if userAnalysis, ok := record.Status["用户分析"].(map[string]string); ok {
			for key, valueStr := range userAnalysis {
				if !allowedMetrics[key] {
					continue
				}

				valueInt, err := strconv.Atoi(valueStr)
				if err != nil {
					log.Printf("无法将值 %s 转换为整数: %v\n", valueStr, err)
					continue
				}

				if _, exists := stats[key]; !exists {
					stats[key] = &IndicatorStat{
						Values: make(map[int]bool),
						Total:  0,
						Count:  0,
					}
				}

				lastValue, lastValueExists := lastValuesMap[key]
				if !lastValueExists || lastValue != valueInt {
					stats[key].Values[valueInt] = true
					stats[key].Total += valueInt
					stats[key].Count++
					lastValuesMap[key] = valueInt
				}
				log.Printf("处理指标 %s: 当前值 %d, 上一值 %d, 计数 %d\n", key, valueInt, lastValue, stats[key].Count)
			}
		}

	}

	for key, stat := range stats {
		avg := float64(stat.Total) / float64(stat.Count)
		log.Printf("最终统计 - %s: 平均值 %.2f\n", key, avg)
	}

	return stats
}
