import type { ConfirmedFactCard, OptimizedArticle, QaCheck } from "../domain/types";
import { optimizedArticleSchema } from "../domain/validation";
import { generateValidatedJson } from "../llm/client";
import {
  TARGETED_REWRITER_SYSTEM_PROMPT,
  buildTargetedRewritePrompt,
} from "../llm/prompts";

export interface RewriteFailedSectionsInput {
  article: OptimizedArticle;
  factCard: ConfirmedFactCard;
  failedChecks: QaCheck[];
}

export async function rewriteFailedSections({
  article,
  factCard,
  failedChecks,
}: RewriteFailedSectionsInput): Promise<OptimizedArticle> {
  const llmArticle = await generateValidatedJson({
    schema: optimizedArticleSchema,
    system: TARGETED_REWRITER_SYSTEM_PROMPT,
    prompt: buildTargetedRewritePrompt({ article, factCard, failedChecks }),
    temperature: 0.15,
    task: "targeted_rewriter",
  });

  return optimizedArticleSchema.parse({
    ...llmArticle,
    image_suggestions: [],
  });
}
