import { prisma } from "../db/prisma.js";

/**
 * Maintainer-facing report of every `TechStepTrainingSuggestion` still
 * `status: "pending"` (`TechStepTrainingSuggestion`'s own schema doc
 * comment) — generated by `services/tech-step-llm-worker`'s scheduled
 * jobs, from either a user correction or the worker's own low-confidence
 * audit (`sourceType`). What a maintainer reads *before* hand-editing
 * `services/tech-step-intent-service/intent_service/training_data.py` and
 * running `retrain-tech-steps.ts` — this script never writes anything,
 * purely a read-only report to stdout:
 *
 *   pnpm --filter api exec tsx src/scripts/list-pending-training-suggestions.ts
 *
 * Grouped by technique key so every suggestion for the same entry in
 * `training_data.py`'s `TECH_STEP_TRAINING_DATA` is read together, matching
 * how that file itself is organized (one block per technique).
 */
async function listPendingTrainingSuggestions(): Promise<void> {
  const suggestions = await prisma.techStepTrainingSuggestion.findMany({
    where: { status: "pending" },
    orderBy: [{ techStepId: "asc" }, { createdAt: "asc" }],
    include: { techStep: { select: { key: true } } },
  });

  if (suggestions.length === 0) {
    console.info("No pending training suggestions.");
    return;
  }

  const byTechStepKey = new Map<string, typeof suggestions>();
  for (const suggestion of suggestions) {
    const key = suggestion.techStep.key;
    const group = byTechStepKey.get(key);
    if (group) {
      group.push(suggestion);
    } else {
      byTechStepKey.set(key, [suggestion]);
    }
  }

  const lines: string[] = [`# Pending tech-step training suggestions (${suggestions.length})`, ""];
  for (const [techStepKey, group] of byTechStepKey) {
    lines.push(`## ${techStepKey}`, "");
    for (const suggestion of group) {
      const source =
        suggestion.sourceCorrectionId !== null
          ? `${suggestion.sourceType} (correction #${suggestion.sourceCorrectionId})`
          : suggestion.sourceType;
      lines.push(`- id ${suggestion.id} · locale ${suggestion.locale} · source: ${source}`);
      if (suggestion.suggestedSynonyms.length > 0) {
        lines.push(`  - synonyms: ${suggestion.suggestedSynonyms.join(", ")}`);
      }
      if (suggestion.suggestedUtterances.length > 0) {
        lines.push(
          `  - utterances: ${suggestion.suggestedUtterances.map((u) => `"${u}"`).join(", ")}`,
        );
      }
    }
    lines.push("");
  }

  console.info(lines.join("\n"));
}

listPendingTrainingSuggestions()
  .then(() => prisma.$disconnect())
  .catch(async (err) => {
    console.error(err);
    await prisma.$disconnect();
    process.exit(1);
  });
