package job

import (
	"context"
	"fmt"

	libpersonacopy "haixun-backend/internal/library/personacopy"
	aiusecase "haixun-backend/internal/model/ai/usecase"
	contentformuladomain "haixun-backend/internal/model/content_formula/domain/usecase"
	copydraftdomain "haixun-backend/internal/model/copy_draft/domain/usecase"
	jobdom "haixun-backend/internal/model/job/domain/usecase"
	personadomain "haixun-backend/internal/model/persona/domain/usecase"
	placementusecase "haixun-backend/internal/model/placement/usecase"
	threadsaccountdomain "haixun-backend/internal/model/threads_account/domain/usecase"
)

type GenerateRewriteDraftDeps struct {
	Jobs           jobdom.UseCase
	Persona        personadomain.UseCase
	ContentFormula contentformuladomain.UseCase
	CopyDraft      copydraftdomain.UseCase
	ThreadsAccount threadsaccountdomain.UseCase
	Placement      placementusecase.UseCase
	AI             aiusecase.UseCase
}

func RegisterGenerateRewriteDraftHandler(runner *Runner, deps GenerateRewriteDraftDeps) {
	if runner == nil {
		return
	}
	runner.RegisterStepHandler("rewrite_draft_generate", func(ctx context.Context, step StepContext) error {
		return runGenerateRewriteDraft(ctx, step, deps)
	})
}

func runGenerateRewriteDraft(ctx context.Context, step StepContext, deps GenerateRewriteDraftDeps) error {
	payload := step.Run.Payload
	tenantID, ownerUID := runActorFromPayload(payload, step.Run)
	personaID := stringField(payload, "persona_id")
	accountID := stringField(payload, "account_id")
	referenceText := stringField(payload, "reference_text")
	topic := stringField(payload, "topic")
	if tenantID == "" || ownerUID == "" || personaID == "" || accountID == "" || referenceText == "" || topic == "" {
		return fmt.Errorf("generate-rewrite-draft payload missing required fields")
	}

	updateProgress := func(summary string, percentage int) {
		_ = step.Heartbeat(ctx)
		_, _ = deps.Jobs.UpdateProgress(ctx, jobdom.UpdateProgressRequest{
			JobID:      step.JobID,
			WorkerID:   step.WorkerID,
			Phase:      "rewrite_draft_generate",
			Summary:    summary,
			Percentage: percentage,
		})
	}

	count, err := libpersonacopy.RunRewriteDraft(ctx, libpersonacopy.RewriteDraftDeps{
		Persona:        deps.Persona,
		ContentFormula: deps.ContentFormula,
		CopyDraft:      deps.CopyDraft,
		ThreadsAccount: deps.ThreadsAccount,
		Placement:      deps.Placement,
		AI:             deps.AI,
	}, libpersonacopy.RewriteDraftInput{
		TenantID:      tenantID,
		OwnerUID:      ownerUID,
		PersonaID:     personaID,
		AccountID:     accountID,
		ReferenceText: referenceText,
		Topic:         topic,
		Brief:         stringField(payload, "brief"),
		SaveLabel:     stringField(payload, "save_label"),
		UseWebSearch:  boolField(payload, "use_web_search"),
		DraftCount:    intField(payload, "draft_count"),
	}, updateProgress)
	if err != nil {
		return err
	}
	_ = count
	return nil
}
