import * as offline from './offlineStorage';
import safeParseJournal from '../utils/safeParseJournal';
import { GEMINI_API_KEY } from '../config/keys';
import { todayISO } from '../utils/date';

const GEMINI_URL =
  'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent';

function buildPrompt({ mood, win, struggle, highlight, note }) {
  return `You are a reflective and thoughtful journal companion.

A user wrote a daily journal.

Your job: Turn it into a meaningful reflection.

INPUT:
- Mood: "${mood || 'not specified'}"
- What went well: "${win || 'not specified'}"
- What was difficult: "${struggle || 'not specified'}"
- Highlight of the day: "${highlight || 'not specified'}"
- Reflection: "${note || 'not specified'}"

OUTPUT:

1. title: Short, emotional, personal (max 8 words)
2. summary: 2-3 sentences, natural, human, not generic. Reflect what they actually experienced.
3. quote: 1 short powerful sentence, relatable, feels like it was written for them.

STYLE:
- calm and reflective
- real, not a motivational speech
- avoid generic phrases like "keep going" or "believe in yourself"

Return ONLY valid JSON:
{
  "title": "",
  "summary": "",
  "quote": ""
}`;
}

/**
 * Generate AI reflection from journal inputs.
 */
export async function generateDailyReflection(data) {
  try {
    const response = await fetch(`${GEMINI_URL}?key=${GEMINI_API_KEY}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        contents: [{ parts: [{ text: buildPrompt(data) }] }],
        generationConfig: { temperature: 0.8, topP: 0.9, maxOutputTokens: 512 },
      }),
    });

    if (response.status === 429) {
      await new Promise((r) => setTimeout(r, 4000));
      const retry = await fetch(`${GEMINI_URL}?key=${GEMINI_API_KEY}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          contents: [{ parts: [{ text: buildPrompt(data) }] }],
          generationConfig: { temperature: 0.8, topP: 0.9, maxOutputTokens: 512 },
        }),
      });
      if (!retry.ok) throw new Error('Rate limited');
      const json = await retry.json();
      return { ...safeParseJournal(json?.candidates?.[0]?.content?.parts?.[0]?.text), source: 'ai' };
    }

    if (!response.ok) throw new Error('AI failed');

    const json = await response.json();
    const rawText = json?.candidates?.[0]?.content?.parts?.[0]?.text || '';
    return { ...safeParseJournal(rawText), source: 'ai' };
  } catch (e) {
    console.warn('Journal AI failed, using fallback:', e.message);
    return { ...buildFallback(data), source: 'fallback' };
  }
}

function buildFallback({ mood, win, struggle }) {
  const titles = {
    great: 'A Day That Lifted You',
    good: 'Quiet Progress',
    okay: 'Steady and Present',
    bad: 'Through the Hard Parts',
    terrible: 'Surviving Is Enough',
  };

  return {
    title: titles[mood?.toLowerCase()] || 'Another Step Forward',
    summary: win
      ? `Today you noticed something good: ${win.toLowerCase()}. ${struggle ? `Even though ${struggle.toLowerCase()}, you kept moving.` : 'That awareness is growth.'}`
      : 'You showed up today. Some days that is the whole victory.',
    quote: struggle
      ? 'The hard days are proof that you are still trying.'
      : 'You are closer than yesterday.',
  };
}

/**
 * Save daily journal with all fields.
 */
export async function saveDailyJournal(identityId, dayNumber, data) {
  const today = todayISO();

  const record = {
    identity_id: identityId,
    date: today,
    day_number: dayNumber,
    identity_check: data.identityCheck || 'almost',
    habits_completed: data.habitsCompleted || 0,
    mood: data.mood || '',
    win: data.win || '',
    struggle: data.struggle || '',
    highlight: data.highlight || '',
    note: data.note || '',
    ai_title: data.aiTitle || '',
    ai_summary: data.aiSummary || '',
    ai_quote: data.aiQuote || '',
  };

  await offline.upsert(
    'daily_logs',
    { identity_id: identityId, date: today },
    record
  );

  // Update stats
  const scoreAdd = data.identityCheck === 'yes' ? 3 : data.identityCheck === 'almost' ? 1 : 0;
  if (scoreAdd > 0) {
    const stats = await offline.getOne('stats', { identity_id: identityId });
    if (stats) {
      await offline.update('stats', { id: stats.id }, {
        discipline_score: stats.discipline_score + scoreAdd,
        consistency_score: stats.consistency_score + (data.identityCheck === 'yes' ? 2 : 1),
        focus_score: stats.focus_score + scoreAdd,
      });
    }
  }

  return record;
}

/**
 * Get journal entry for a specific date.
 */
export async function getJournalEntry(identityId, date) {
  return offline.getOne('daily_logs', { identity_id: identityId, date: date || todayISO() });
}
