/**
 * Phase 6.1 — Snapshot conversion
 * Convert Phase 5 FeedbackReport -> Snapshot (normalized, timestamped)
 */
import { FeedbackReport } from '../../types/phase5';
import { Snapshot, PolicyOutcome } from '../../types/core';

function clamp01(v: number) {
  return Math.max(0, Math.min(1, Number(v) || 0));
}

/**
 * Convert a FeedbackReport coming from Phase 5 to a normalized Snapshot.
 */
export function toSnapshot(report: FeedbackReport): Snapshot {
  const outcomes: PolicyOutcome[] = report.policies.map((p) => {
    const score = clamp01(p.score);
    const attempts = Math.max(1, Number(p.attempts ?? 0));
    const failures = Math.max(0, Number(p.failures ?? 0));
    const failureRate = clamp01(failures / attempts);

    return {
      policyId: p.policyId,
      score,
      failureRate,
      iteration: report.iteration,
      timestamp: report.timestamp,
    };
  });

  return {
    id: `snap-${report.iteration}-${report.timestamp}`,
    timestamp: report.timestamp,
    outcomes,
    notes: report.notes || '',
  };
}
