package copy_mission

import (
	"context"
	"strings"

	libcopy "haixun-backend/internal/library/copymission"
	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	missiondomain "haixun-backend/internal/model/copy_mission/domain/usecase"
	kgusecase "haixun-backend/internal/model/knowledge_graph/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"

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

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

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

func (l *PatchCopyMissionGraphNodesLogic) PatchCopyMissionGraphNodes(req *types.PatchCopyMissionGraphNodesHandlerReq) (*types.KnowledgeGraphData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	if len(req.Updates) == 0 {
		return nil, app.For(code.Persona).InputMissingRequired("updates is required")
	}
	personaID := strings.TrimSpace(req.PersonaID)
	missionID := strings.TrimSpace(req.ID)
	mission, err := l.svcCtx.CopyMission.Get(l.ctx, tenantID, uid, personaID, missionID)
	if err != nil {
		return nil, err
	}

	updates := make([]kgusecase.NodeUpdate, 0, len(req.Updates))
	for _, item := range req.Updates {
		nodeID := strings.TrimSpace(item.NodeID)
		if nodeID == "" {
			continue
		}
		update := kgusecase.NodeUpdate{NodeID: nodeID}
		if item.SelectedForScan != nil {
			update.SelectedForScan = item.SelectedForScan
		}
		if item.RelevanceTags != nil {
			update.RelevanceTagsSet = true
			update.RelevanceTags = append([]string(nil), item.RelevanceTags...)
		}
		if item.RecencyTags != nil {
			update.RecencyTagsSet = true
			update.RecencyTags = append([]string(nil), item.RecencyTags...)
		}
		if update.SelectedForScan == nil && !update.RelevanceTagsSet && !update.RecencyTagsSet {
			return nil, app.For(code.Persona).InputMissingRequired("each update needs selected_for_scan or patrol tags")
		}
		updates = append(updates, update)
	}
	if len(updates) == 0 {
		return nil, app.For(code.Persona).InputMissingRequired("updates is required")
	}

	graph, err := l.svcCtx.KnowledgeGraph.UpdateNodes(l.ctx, kgusecase.UpdateNodesRequest{
		TenantID:      tenantID,
		OwnerUID:      uid,
		CopyMissionID: missionID,
		Updates:       updates,
	})
	if err != nil {
		return nil, err
	}

	prev := summaryToEntityResearchMap(mission.ResearchMap)
	researchMap := libcopy.BuildResearchMapFromGraph(prev, graph.Nodes, graph.BraveSources)
	_, err = l.svcCtx.CopyMission.Update(l.ctx, missiondomain.UpdateRequest{
		TenantID:  tenantID,
		OwnerUID:  uid,
		PersonaID: personaID,
		MissionID: missionID,
		Patch: missiondomain.MissionPatch{
			ResearchMap: &researchMap,
		},
	})
	if err != nil {
		return nil, err
	}

	data := toKnowledgeGraphData(graph)
	return &data, nil
}