/**
 * Safely parse AI-generated transformation story.
 * Always returns a valid result — never throws.
 */
export default function safeParseStory(raw, identity, logs, stats) {
  const fallback = buildMinimalFallback(identity, logs);

  if (!raw || typeof raw !== 'string') return fallback;

  try {
    let cleaned = raw.trim();
    cleaned = cleaned.replace(/```json\s*/gi, '').replace(/```\s*/gi, '');

    const start = cleaned.indexOf('{');
    const end = cleaned.lastIndexOf('}');
    if (start === -1 || end === -1) return fallback;

    cleaned = cleaned.slice(start, end + 1);
    const parsed = JSON.parse(cleaned);

    const title = typeof parsed.title === 'string' && parsed.title.trim()
      ? parsed.title.trim()
      : fallback.title;

    let paragraphs = fallback.paragraphs;
    if (Array.isArray(parsed.paragraphs) && parsed.paragraphs.length >= 2) {
      paragraphs = parsed.paragraphs
        .filter((p) => typeof p === 'string' && p.trim())
        .map((p) => p.trim());
    }

    const closing_line = typeof parsed.closing_line === 'string' && parsed.closing_line.trim()
      ? parsed.closing_line.trim()
      : fallback.closing_line;

    return { title, paragraphs, closing_line };
  } catch (_) {
    return fallback;
  }
}

function buildMinimalFallback(identity, logs) {
  const yesCount = logs.filter((l) => l.identity_check === 'yes').length;
  return {
    title: 'Your Transformation',
    paragraphs: [
      `You set out to become "${identity?.title || 'someone new'}". That took courage.`,
      `Over 40 days, you showed up ${yesCount} times fully aligned with your identity.`,
      `The journey wasn't perfect, but it was yours. And that's what matters.`,
    ],
    closing_line: 'This is not the end. This is who you are now.',
  };
}
