package benchmark

import (
	"context"
	"fmt"

	"apps/backend/internal/middleware"
	"apps/backend/internal/module/growth/usecase"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *GetBenchmarkLogic) GetBenchmark(req *types.BenchmarkReq) (*types.BenchmarkData, error) {
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok || uid <= 0 {
		return nil, fmt.Errorf("unauthorized")
	}
	niche := usecase.NormalizeNiche(req.Niche)
	var yourEng, yourViews float64
	// 只讀自己的貼文算出對照值。這裡刻意不 ContributeBenchmark：查詢是讀路徑，
	// 若順手寫入，任何人只要輸入某個利基名稱就能把自己的數字灌進那個桶。
	// 貢獻的唯一入口是 insights summary（那裡的數字來自使用者自己的已同步貼文）。
	if l.svcCtx.Studio != nil {
		posts, err := l.svcCtx.Studio.ListOwnPosts(l.ctx, uid, req.AccountId)
		if err == nil && len(posts) > 0 {
			var views, likes, replies int
			n := 0
			for _, p := range posts {
				if p == nil {
					continue
				}
				n++
				views += p.ViewCount
				likes += p.LikeCount
				replies += p.ReplyCount
			}
			if n > 0 {
				yourViews = float64(views) / float64(n)
				if views > 0 {
					yourEng = float64(likes+replies) / float64(views)
				}
			}
		}
	}
	sample, medEng, medViews, avail, hint := l.svcCtx.Growth.GetBenchmark(l.ctx, niche, yourEng, yourViews)
	return &types.BenchmarkData{
		Available: avail, SampleSize: sample, Niche: niche,
		MedianEngRate: usecase.RoundRate(medEng), MedianViews: usecase.Round2(medViews),
		YourEngRate: usecase.RoundRate(yourEng), YourViews: usecase.Round2(yourViews),
		PercentileHint: hint, Message: hint,
	}, nil
}
