package core

import (
	"context"
	"fmt"
	"sync"

	"github.com/tencentyun/cos-go-sdk-v5"
	"index-go/config"
	"index-go/utils"
)

// IndexEngine 负责与 COS 通信并维护内存索引
type IndexEngine struct {
	client *cos.Client
	config *config.Config

	mu   sync.RWMutex
	tree IndexNode
}

// NewIndexEngine 创建新的索引引擎
func NewIndexEngine(cfg *config.Config) (*IndexEngine, error) {
	client, err := NewCosClient(cfg)
	if err != nil {
		return nil, fmt.Errorf("创建 COS 客户端失败: %w", err)
	}

	return &IndexEngine{
		client: client,
		config: cfg,
	}, nil
}

// GetClient 获取COS客户端
func (e *IndexEngine) GetClient() *cos.Client {
	return e.client
}

// Refresh 从 COS 重新拉取文件并构建索引树
func (e *IndexEngine) Refresh(ctx context.Context) error {
	utils.IndexLog("开始刷新索引数据，存储桶: %s, 区域: %s", e.config.Bucket, e.config.Region)

	files, err := ListAllFiles(ctx, e.client, e.config.Prefix)
	if err != nil {
		return fmt.Errorf("列出文件失败: %w", err)
	}
	utils.IndexLog("共获取到 %d 个文件", len(files))

	treeRoot := BuildTree(files, e.config.Prefix)

	e.mu.Lock()
	e.tree = treeRoot
	e.mu.Unlock()

	utils.IndexLog("索引刷新完成，记录已更新")
	return nil
}

// GetDirectory 根据路径获取目录节点
func (e *IndexEngine) GetDirectory(pathSegments []string) (IndexNode, bool) {
	e.mu.RLock()
	defer e.mu.RUnlock()

	if e.tree == nil {
		return nil, false
	}

	node := e.tree
	for _, segment := range pathSegments {
		child, exists := node[segment]
		if !exists {
			return nil, false
		}

		nextNode, ok := child.(IndexNode)
		if !ok {
			return nil, false
		}
		node = nextNode
	}

	return node, true
}

// HasIndex 判断是否已经构建索引
func (e *IndexEngine) HasIndex() bool {
	e.mu.RLock()
	defer e.mu.RUnlock()
	return e.tree != nil
}
