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

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(`${AI_SERVICE_URL}/v1/chat/completions`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        model: AI_MODEL,
        max_tokens: 512,
        messages: [{ role: 'user', content: buildPrompt(data) }],
      }),
    });

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

    const json = await response.json();
    const rawText = json?.choices?.[0]?.message?.content || '';
    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() });
}
