package utils

import (
	"encoding/json"
	"os"
	"path/filepath"
	"sync"
)

// ConfigCache 配置缓存
type ConfigCache struct {
	mu           sync.RWMutex
	toolStatus   map[string]interface{}
	updateInfo   map[string]interface{}
	mediaTypes   map[string]interface{}
}

var configCache = &ConfigCache{}

// LoadConfig 加载配置文件
func LoadConfig(filename string) (map[string]interface{}, error) {
	filePath := filepath.Join("public", filename)
	
	data, err := os.ReadFile(filePath)
	if err != nil {
		return nil, err
	}
	
	var config map[string]interface{}
	if err := json.Unmarshal(data, &config); err != nil {
		return nil, err
	}
	
	return config, nil
}

// SaveConfig 保存配置文件并更新缓存
func SaveConfig(filename string, config map[string]interface{}) error {
	filePath := filepath.Join("public", filename)
	
	// 转换为 JSON
	jsonData, err := json.MarshalIndent(config, "", "  ")
	if err != nil {
		return err
	}
	
	// 保存文件
	if err := os.WriteFile(filePath, jsonData, 0644); err != nil {
		return err
	}
	
	// 更新缓存
	configCache.mu.Lock()
	defer configCache.mu.Unlock()
	
	switch filename {
	case "tool-status.json":
		configCache.toolStatus = config
	case "update-info.json":
		configCache.updateInfo = config
	case "media-types.json":
		configCache.mediaTypes = config
	}
	
	return nil
}

// GetCachedConfig 获取缓存的配置
func GetCachedConfig(filename string) (map[string]interface{}, bool) {
	configCache.mu.RLock()
	defer configCache.mu.RUnlock()
	
	switch filename {
	case "tool-status.json":
		if configCache.toolStatus != nil {
			return configCache.toolStatus, true
		}
	case "update-info.json":
		if configCache.updateInfo != nil {
			return configCache.updateInfo, true
		}
	case "media-types.json":
		if configCache.mediaTypes != nil {
			return configCache.mediaTypes, true
		}
	}
	
	return nil, false
}

// ReloadConfig 重新加载配置
func ReloadConfig(filename string) error {
	config, err := LoadConfig(filename)
	if err != nil {
		return err
	}
	
	return SaveConfig(filename, config)
}

// InitConfigCache 初始化配置缓存
func InitConfigCache() error {
	files := []string{"tool-status.json", "update-info.json", "media-types.json"}
	
	for _, file := range files {
		if _, err := os.Stat(filepath.Join("public", file)); err == nil {
			config, err := LoadConfig(file)
			if err == nil {
				SaveConfig(file, config)
			}
		}
	}
	
	return nil
}
