package svc

import (
	"context"
	"fmt"
	"log"

	jobworker "haixun-backend/internal/worker/job"
)

var inlineCopyWorkerTypes = []string{
	"go-generate-topic-matrix",
	"go-generate-formula-draft",
	"go-generate-rewrite-draft",
}

func registerCopyJobHandlers(runner *jobworker.Runner, sc *ServiceContext) {
	if runner == nil || sc == nil {
		return
	}
	jobworker.RegisterGenerateTopicMatrixHandler(runner, jobworker.GenerateTopicMatrixDeps{
		Jobs:           sc.Job,
		Persona:        sc.Persona,
		CopyDraft:      sc.CopyDraft,
		ContentOps:     sc.ContentOps,
		ThreadsAccount: sc.ThreadsAccount,
		Placement:      sc.Placement,
		AI:             sc.AI,
	})
	jobworker.RegisterGenerateFormulaDraftHandler(runner, jobworker.GenerateFormulaDraftDeps{
		Jobs:           sc.Job,
		Persona:        sc.Persona,
		ContentFormula: sc.ContentFormula,
		CopyDraft:      sc.CopyDraft,
		ThreadsAccount: sc.ThreadsAccount,
		Placement:      sc.Placement,
		AI:             sc.AI,
	})
	jobworker.RegisterGenerateRewriteDraftHandler(runner, jobworker.GenerateRewriteDraftDeps{
		Jobs:           sc.Job,
		Persona:        sc.Persona,
		ContentFormula: sc.ContentFormula,
		CopyDraft:      sc.CopyDraft,
		ThreadsAccount: sc.ThreadsAccount,
		Placement:      sc.Placement,
		AI:             sc.AI,
	})
}

func (sc *ServiceContext) startInlineCopyWorkers(ctx context.Context, hostname string) {
	if sc == nil || sc.Redis == nil {
		return
	}
	for _, workerType := range inlineCopyWorkerTypes {
		workerType := workerType
		workerID := fmt.Sprintf("%s-inline-%s", hostname, workerType)
		runner := jobworker.NewRunner(workerID, workerType, sc.Job)
		registerCopyJobHandlers(runner, sc)
		go runner.Start(ctx)
		log.Printf("inline copy job worker started: id=%s type=%s", workerID, workerType)
	}
}
