/** Midpoint of the previous decorative 40–85 random progress range. */
const DEFAULT_COURSE_PROGRESS = 60;

function clampProgress(raw: unknown, fallback = DEFAULT_COURSE_PROGRESS): number {
  const n = typeof raw === "number" ? raw : parseInt(String(raw ?? ""), 10);
  if (!Number.isFinite(n)) return fallback;
  return Math.min(100, Math.max(0, n));
}

function normalizeCourseProgressFields(course: unknown): unknown {
  if (!course || typeof course !== "object" || Array.isArray(course)) return course;
  const o = { ...(course as Record<string, unknown>) };
  const hasProgress = o.progress !== undefined && o.progress !== null && o.progress !== "";
  o.progress = clampProgress(hasProgress ? o.progress : DEFAULT_COURSE_PROGRESS);
  const color =
    (typeof o.progress_color === "string" && o.progress_color.trim()) ||
    (typeof o.progressColor === "string" && o.progressColor.trim()) ||
    "";
  if (color) {
    o.progress_color = color;
  }
  if ("progressColor" in o) delete o.progressColor;
  return o;
}

/** Normalize legacy how-each-course-sees keys (title/subtitle/items) into the shared schema. */
export function normalizeHowEachCourseSeesContent(
  content: Record<string, unknown>
): Record<string, unknown> {
  const next = { ...content };
  if (!next.lensesTitle && typeof next.title === "string") next.lensesTitle = next.title;
  if (!next.lensesSubtitle && typeof next.subtitle === "string") next.lensesSubtitle = next.subtitle;
  if ((!Array.isArray(next.lensesItems) || next.lensesItems.length === 0) && Array.isArray(next.items)) {
    next.lensesItems = next.items;
  }
  // Legacy: evidence items stored as newline-separated string → string[]
  if (typeof next.evidenceItems === "string") {
    next.evidenceItems = next.evidenceItems
      .split(/\r?\n/)
      .map((s) => s.trim())
      .filter(Boolean);
  } else if (!Array.isArray(next.evidenceItems)) {
    next.evidenceItems = [];
  } else {
    next.evidenceItems = (next.evidenceItems as unknown[]).map((x) => String(x ?? ""));
  }
  // Ensure Core/DNA courses carry clamped progress + progress_color
  if (Array.isArray(next.coreCourses)) {
    next.coreCourses = next.coreCourses.map(normalizeCourseProgressFields);
  }
  if (Array.isArray(next.dnaCourses)) {
    next.dnaCourses = next.dnaCourses.map(normalizeCourseProgressFields);
  }
  return next;
}
