package glue

import (
	"context"
)

type CompletionReq struct {
	ConversationID int64  `json:"conversation_id"`
	BranchName     string `json:"branch"`
	Prompt         string `json:"prompt"`
}

type CompletionResp struct {
	PromptNodeID   int64  `json:"prompt_node_id"`
	AnswerNodeID   int64  `json:"answer_node_id"`
	Answer         string `json:"answer"`
}

// For v0 we stub the answer as a simple echo with a prefix.
func (g *Glue) AppendCompletion(ctx context.Context, req CompletionReq) (CompletionResp, error) {
	b, err := g.repo.GetBranch(ctx, req.ConversationID, req.BranchName)
	if err != nil { return CompletionResp{}, err }

	// 1) create user prompt node
	promptID, err := g.repo.CreateNode(ctx, req.ConversationID, "user", req.Prompt)
	if err != nil { return CompletionResp{}, err }
	if err := g.repo.Link(ctx, b.HeadNodeID, promptID); err != nil { return CompletionResp{}, err }

	// 2) create assistant answer node (stub)
	answerText := "(stub) You said: " + req.Prompt
	answerID, err := g.repo.CreateNode(ctx, req.ConversationID, "assistant", answerText)
	if err != nil { return CompletionResp{}, err }
	if err := g.repo.Link(ctx, promptID, answerID); err != nil { return CompletionResp{}, err }

	// 3) move branch head
	if err := g.repo.MoveBranchHead(ctx, b.ID, answerID); err != nil { return CompletionResp{}, err }

	return CompletionResp{PromptNodeID: promptID, AnswerNodeID: answerID, Answer: answerText}, nil
}
