package inspire

import (
	"context"

	"apps/backend/internal/middleware"
	"apps/backend/internal/response"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *InspirePromptPreviewLogic) InspirePromptPreview(req *types.InspirePromptPreviewReq) (*types.InspirePromptPreviewData, error) {
	if l.svcCtx.Inspire == nil {
		return nil, response.Biz(503, 503001, "inspire not configured")
	}
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok {
		return nil, response.Biz(401, 401001, "missing authorization")
	}
	r, err := l.svcCtx.Inspire.PreviewPrompt(l.ctx, uid, req.Message, req.PinnedIds, req.Mode, req.PersonaId, req.SessionId, req.Material)
	if err != nil {
		return nil, err
	}
	pinned := make([]types.InspirePromptPinnedPublic, 0, len(r.Pinned))
	for _, p := range r.Pinned {
		pinned = append(pinned, types.InspirePromptPinnedPublic{
			Id: p.ID, Kind: p.Kind, Title: p.Title, Body: p.Body,
		})
	}
	blocks := make([]types.InspirePromptBlockPublic, 0, len(r.Blocks))
	for _, blk := range r.Blocks {
		blocks = append(blocks, types.InspirePromptBlockPublic{Title: blk.Title, Body: blk.Body})
	}
	return &types.InspirePromptPreviewData{
		Prompt:      r.Prompt,
		Mode:        r.Mode,
		Sections:    r.Sections,
		Blocks:      blocks,
		Fingerprint: r.Fingerprint,
		CharCount:   r.CharCount,
		RuneCount:   r.RuneCount,
		Pinned:      pinned,
		Note:        r.Note,
	}, nil
}
