import safeParseStory from '../utils/safeParseStory';
import { AI_SERVICE_URL, AI_MODEL } from '../config/keys';

function buildPrompt(identity, habits, logs) {
  const yesCount = logs.filter((l) => l.identity_check === 'yes').length;
  const almostCount = logs.filter((l) => l.identity_check === 'almost').length;
  const noCount = logs.filter((l) => l.identity_check === 'no').length;
  const totalLogged = logs.length;

  // Collect reflections (notes) from journal
  const reflections = logs
    .filter((l) => l.note && l.note.trim())
    .map((l) => `Day ${l.day_number}: "${l.note.trim()}"`)
    .slice(0, 15); // max 15 to keep prompt size reasonable

  const habitNames = habits.map((h) => h.title).join(', ');

  return `You are a reflective storyteller.

A user has completed a 40-day personal transformation journey.

Here is their data:

Identity: "${identity.title}"
${identity.story_text ? `Original story: "${identity.story_text}"` : ''}
${identity.description ? `Description: "${identity.description}"` : ''}
Habits they practiced: ${habitNames}
Days fully aligned: ${yesCount}/40
Days almost aligned: ${almostCount}
Days missed: ${noCount}
Total days logged: ${totalLogged}

${reflections.length > 0 ? `Their journal entries:\n${reflections.join('\n')}` : 'No journal entries recorded.'}

---

Your job: Turn this into a meaningful and emotional story.

STRUCTURE:

1. Beginning — Who they were. What they wanted.
2. Struggles — Challenges they faced. Moments they almost gave up.
3. Breakthrough — When things started to change. Small wins.
4. Transformation — Who they became. What changed.

STYLE:
- Personal and human
- Emotional but not dramatic
- Simple language
- Feels real, not a motivational speech
- Written in third person or second person ("you")

OUTPUT FORMAT (JSON ONLY):
Return ONLY valid JSON. No markdown, no explanation.

{
  "title": "short and powerful story title",
  "paragraphs": [
    "paragraph 1 - the beginning",
    "paragraph 2 - the struggles",
    "paragraph 3 - the breakthrough",
    "paragraph 4 - the transformation"
  ],
  "closing_line": "a memorable final sentence"
}

IMPORTANT: Make it feel like this story belongs to ONE person, not a template.`;
}

/**
 * Generate a transformation story using AI.
 * Falls back to local generation if AI fails.
 */
export async function generateTransformationStory(identity, habits, logs, stats) {
  try {
    const response = await fetch(`${AI_SERVICE_URL}/v1/chat/completions`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        model: AI_MODEL,
        max_tokens: 2048,
        messages: [{ role: 'user', content: buildPrompt(identity, habits, logs) }],
      }),
    });

    if (!response.ok) throw new Error(`AI request failed (${response.status})`);

    const json = await response.json();
    const rawText = json?.choices?.[0]?.message?.content || '';
    const parsed = safeParseStory(rawText, identity, logs, stats);
    return { ...parsed, source: 'ai' };
  } catch (e) {
    console.warn('Story AI failed, using fallback:', e.message);
    return { ...buildFallbackStory(identity, habits, logs, stats), source: 'fallback' };
  }
}

function buildFallbackStory(identity, habits, logs, stats) {
  const yesCount = logs.filter((l) => l.identity_check === 'yes').length;
  const totalLogged = logs.length;
  const title = identity.title || 'A New Beginning';
  const habitNames = habits.slice(0, 3).map((h) => h.title).join(', ');

  return {
    title: `The ${totalLogged}-Day Journey`,
    paragraphs: [
      `It started with a decision. You said: "${title}". That was the moment everything began to shift — not because the world changed, but because you did.`,
      `The first days were hard. Building habits like ${habitNames || 'showing up daily'} felt unnatural. There were moments when giving up seemed easier than continuing. But you kept going.`,
      `Somewhere around the middle, something clicked. The habits stopped feeling forced. You weren't just doing things — you were becoming someone. ${yesCount > 20 ? 'More often than not, you showed up fully aligned with who you wanted to be.' : 'Even on the hard days, you found a way to keep moving forward.'}`,
      `40 days later, you are not the same person who started this journey. You logged ${totalLogged} days. You showed up ${yesCount} times fully aligned. The numbers tell a story, but the real transformation happened inside.`,
    ],
    closing_line: 'You didn\'t just change your habits. You changed who you are.',
  };
}
