import type { ArticleInput, OptimizationFactCard } from "../domain/types";

import { optimizeArticle } from "./article-optimizer";
import { inspectQualityWithLlm } from "./quality-inspector";
import type { OptimizationStreamEvent } from "./stream-events";
import { rewriteFailedSections } from "./targeted-rewriter";

export interface RunStreamingOptimizationWorkflowInput {
  jobId: string;
  input: ArticleInput;
  factCard: OptimizationFactCard;
  onEvent: (event: OptimizationStreamEvent) => void | Promise<void>;
}

export async function runStreamingOptimizationWorkflow({
  jobId,
  input,
  factCard,
  onEvent,
}: RunStreamingOptimizationWorkflowInput) {
  await onEvent({
    type: "draft_started",
    job_id: jobId,
    message: "正在生成优化草稿",
  });
  let article = await optimizeArticle({ input, factCard });
  await onEvent({ type: "draft_ready", job_id: jobId, article });

  await onEvent({
    type: "qa_started",
    job_id: jobId,
    message: "正在检查质量",
  });
  let qaReport = await inspectQualityWithLlm({
    article,
    factCard,
    platform: input.platform,
    sourceImages: input.images,
  });
  await onEvent({ type: "qa_ready", job_id: jobId, qa_report: qaReport });

  let rewriteRounds = 0;
  while (qaReport.overall_status === "fail" && rewriteRounds < 2) {
    const nextRound = rewriteRounds + 1;
    const failedChecks = qaReport.checks.filter((check) => check.status === "fail");
    await onEvent({
      type: "rewrite_started",
      job_id: jobId,
      round: nextRound,
    });
    article = await rewriteFailedSections({ article, factCard, failedChecks });
    rewriteRounds = nextRound;
    await onEvent({
      type: "rewrite_ready",
      job_id: jobId,
      round: nextRound,
      article,
    });

    await onEvent({
      type: "qa_started",
      job_id: jobId,
      message: `正在复检第 ${nextRound} 轮修复`,
    });
    qaReport = await inspectQualityWithLlm({
      article,
      factCard,
      platform: input.platform,
      sourceImages: input.images,
    });
    await onEvent({ type: "qa_ready", job_id: jobId, qa_report: qaReport });
  }

  return {
    article,
    qaReport,
    rewriteRounds,
    stoppedAfterMaxRewrites:
      qaReport.overall_status === "fail" && rewriteRounds >= 2,
  };
}
