import { describe, expect, it, vi } from "vitest";

import type { ConfirmedFactCard } from "../../domain/types";
import { runOptimizationWorkflow } from "../orchestrator";

const workflowMocks = vi.hoisted(() => ({
  optimizeArticle: vi.fn(),
  inspectQualityWithLlm: vi.fn(),
  rewriteFailedSections: vi.fn(),
}));

vi.mock("../article-optimizer", () => ({
  optimizeArticle: workflowMocks.optimizeArticle,
}));

vi.mock("../quality-inspector", () => ({
  inspectQualityWithLlm: workflowMocks.inspectQualityWithLlm,
}));

vi.mock("../targeted-rewriter", () => ({
  rewriteFailedSections: workflowMocks.rewriteFailedSections,
}));

const factCard: ConfirmedFactCard = {
  company_full_name: "Example Technology Co., Ltd.",
  company_short_names: ["Example Tech"],
  brand_names: ["Example"],
  product_names: ["Example GEO"],
  target_industry: "GEO optimization",
  target_audience: "Marketing teams",
  experience_years: 8,
  core_claims: ["Eight years of GEO optimization experience"],
  forbidden_claims: [],
  image_topics: [],
  uncertain_items: [],
  is_ready_for_optimization: true,
  confirmed_by_user: true,
};

const article = {
  title: "Optimized",
  summary: "Summary",
  body_markdown: "Body",
  image_suggestions: [],
  changed_sections: [],
  requires_user_confirmation: [],
};

const failCheck = {
  rule_id: "body_quality" as const,
  status: "fail" as const,
  evidence: "Bad body.",
  reason: "Needs rewrite.",
  suggested_fix: "Rewrite body.",
  target_agent: "body",
};

describe("runOptimizationWorkflow", () => {
  it("reports live progress for initial generation, QA, rewrite rounds, and finalization", async () => {
    workflowMocks.optimizeArticle.mockResolvedValueOnce(article);
    workflowMocks.inspectQualityWithLlm
      .mockResolvedValueOnce({
        overall_status: "fail",
        checks: [failCheck],
      })
      .mockResolvedValueOnce({
        overall_status: "pass",
        checks: [],
      });
    workflowMocks.rewriteFailedSections.mockResolvedValueOnce({
      ...article,
      body_markdown: "Rewritten body",
    });
    const events: Array<{ label: string; status: string }> = [];

    await runOptimizationWorkflow({
      input: {
        title: "Original",
        body: "Original body",
        images: [],
        platform: "official_site",
        user_instructions: "",
      },
      factCard,
      onProgress: (event) => events.push({ label: event.label, status: event.status }),
    });

    expect(events).toEqual([
      { label: "生成优化稿", status: "running" },
      { label: "生成优化稿", status: "completed" },
      { label: "质量检查", status: "running" },
      { label: "质量检查", status: "completed" },
      { label: "定向修复第 1 轮", status: "running" },
      { label: "定向修复第 1 轮", status: "completed" },
      { label: "质量复检第 1 轮", status: "running" },
      { label: "质量复检第 1 轮", status: "completed" },
      { label: "整理结果", status: "running" },
      { label: "整理结果", status: "completed" },
    ]);
  });
});
