package proxy

import (
	"context"

	"apps/backend/internal/middleware"
	usageDomain "apps/backend/internal/module/usage/domain"
	"apps/backend/internal/response"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *AICompleteLogic) AIComplete(req *types.AICompleteReq) (_ *types.AICompleteData, err error) {
	if l.svcCtx.Usage == nil || l.svcCtx.AI == nil || l.svcCtx.KeyResolver == nil {
		return nil, response.Biz(503, 503001, "ai proxy not configured")
	}
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok {
		return nil, response.Biz(401, 401001, "missing authorization")
	}
	meter := req.Meter
	if meter == "" {
		meter = usageDomain.MeterAICopy
	}
	mode, apiKey, err := l.svcCtx.KeyResolver.ResolveKey(l.ctx, uid, meter)
	if err != nil {
		return nil, err
	}
	charge, err := reserveQuota(l.ctx, l.svcCtx, uid, meter, mode, "AI complete", "proxy.ai")
	if err != nil {
		return nil, err
	}
	defer charge.Settle(l.ctx, &err)
	model := req.Model
	if model == "" {
		model = "grok-3"
	}
	// 語言 system prompt 已由 middleware 注入 ctx；AI client 強制加 system message
	text, err := l.svcCtx.AI.Complete(l.ctx, apiKey, model, req.Prompt)
	if err != nil {
		return nil, response.Biz(502, 502001, err.Error())
	}
	return &types.AICompleteData{Text: text, KeyMode: mode, Model: model}, nil
}
