package logic

import (
	"context"
	"errors"
	"fmt"

	plantModel "sundynix-micro-go/app/plant/model"
	"sundynix-micro-go/app/plant/rpc/internal/svc"
	"sundynix-micro-go/app/plant/rpc/plant"

	"github.com/zeromicro/go-zero/core/logx"
)

type SyncAllWikiVectorLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSyncAllWikiVectorLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SyncAllWikiVectorLogic {
	return &SyncAllWikiVectorLogic{ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx)}
}

func (l *SyncAllWikiVectorLogic) SyncAllWikiVector(in *plant.PageReq) (*plant.CommonResp, error) {
	if l.svcCtx.Config.Ai.EmbeddingApiUrl == "" || l.svcCtx.Config.Ai.QdrantUrl == "" || l.svcCtx.Config.Ai.QdrantCollection == "" {
		return nil, errors.New("AI/RAG 未配置 EmbeddingApiUrl、QdrantUrl 或 QdrantCollection")
	}
	var wikis []plantModel.Wiki
	if err := l.svcCtx.DB.Find(&wikis).Error; err != nil {
		return nil, err
	}
	success := 0
	for _, wiki := range wikis {
		if err := upsertWikiVector(l.ctx, l.svcCtx.Config, wiki); err != nil {
			l.Logger.Errorf("sync wiki vector failed, wiki_id=%s, err=%v", wiki.ID, err)
			continue
		}
		success++
		_ = l.svcCtx.DB.Model(&plantModel.Wiki{}).Where("id = ?", wiki.ID).Update("is_vector_synced", true).Error
	}
	return &plant.CommonResp{Code: 0, Msg: fmt.Sprintf("同步完成: %d/%d", success, len(wikis))}, nil
}
