import {
  buildTrajectory
} from "./chunk-RZTMDUO7.js";
import {
  isLlmSpan,
  isToolSpan
} from "./chunk-5BKGXME7.js";

// src/prm/training-export.ts
async function exportTrainingData(store, graded, options = {}) {
  const window = options.contextWindow ?? 5;
  const out = [];
  for (const g of graded) {
    const trajectory = await buildTrajectory(store, g.runId);
    const spanById = new Map(trajectory.steps.map((s) => [s.span.spanId, s]));
    for (const gs of g.steps) {
      const node = spanById.get(gs.spanId);
      if (!node) continue;
      const idx = trajectory.steps.indexOf(node);
      const priorSpans = trajectory.steps.slice(Math.max(0, idx - window), idx).map((s) => s.span);
      out.push({
        runId: g.runId,
        spanId: gs.spanId,
        rubricId: gs.rubricId,
        score: gs.score,
        context: {
          priorTurns: priorSpans.map(spanToTurn).filter((t) => t !== null),
          step: { kind: node.span.kind, text: spanToText(node.span) }
        },
        rationale: gs.rationale,
        evidence: gs.evidence
      });
    }
  }
  return out;
}
function toNdjson(samples) {
  return `${samples.map((s) => JSON.stringify(s)).join("\n")}
`;
}
function spanToTurn(span) {
  if (isLlmSpan(span)) {
    const text = span.output ?? span.messages.map((m) => `${m.role}: ${m.content}`).join("\n");
    return { role: "assistant", content: text };
  }
  if (isToolSpan(span)) {
    return {
      role: "tool",
      content: `${span.toolName}(${safeStringify(span.args)}) \u2192 ${safeStringify(span.result)}`
    };
  }
  return null;
}
function spanToText(span) {
  if (isLlmSpan(span)) return span.output ?? "";
  if (isToolSpan(span))
    return `${span.toolName}(${safeStringify(span.args)}) \u2192 ${safeStringify(span.result)}`;
  return span.name;
}
function safeStringify(v) {
  if (v === null || v === void 0) return "";
  if (typeof v === "string") return v;
  try {
    return JSON.stringify(v);
  } catch {
    return String(v);
  }
}

export {
  exportTrainingData,
  toNdjson
};
//# sourceMappingURL=chunk-KMPRBJK4.js.map