package compose

import (
	"context"
	"strings"

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

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

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

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

func (l *ComposeMimicLogic) ComposeMimic(req *types.ComposeMimicReq) (*types.ComposeMimicData, error) {
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok {
		return nil, response.Biz(401, 401001, "missing authorization")
	}
	src := strings.TrimSpace(req.SourceText)
	if src == "" {
		return nil, response.Biz(400, 400001, "source_text is required")
	}

	// 優先背景 Job（避免 HTTP 120s 逾時）
	if l.svcCtx.Jobs != nil {
		lang := "zh-TW"
		if v := l.ctx.Value("lang"); v != nil {
			if s, ok := v.(string); ok && s != "" {
				lang = s
			}
		}
		j, err := l.svcCtx.Jobs.ScheduleComposeMimic(l.ctx, uid, src, req.PersonaId, req.Direction, req.StructureNotes, lang)
		if err != nil {
			return nil, err
		}
		return &types.ComposeMimicData{JobId: j.ID, Async: true}, nil
	}

	// 無 Jobs（測試／降級）：同步執行
	if l.svcCtx.Studio == nil {
		return nil, response.Biz(503, 503001, "studio not configured")
	}
	text, err := l.svcCtx.Studio.Mimic(l.ctx, uid, src, req.PersonaId, req.Direction, req.StructureNotes)
	if err != nil {
		return nil, err
	}
	return &types.ComposeMimicData{Text: text, Async: false}, nil
}
