const FALLBACK_HABIT = {
  title: '',
  best_time: '07:00',
  duration: 10,
  frequency: 'Every day',
  category: 'Discipline',
  difficulty: 'Easy',
  why: '',
};

const FALLBACK = {
  identity_title: 'A Better Version of Me',
  identity_summary: 'You are starting a journey to transform yourself, step by step. Every small action counts.',
  priority_habits: [
    { title: 'Do one small positive action today', best_time: '08:00', duration: 10, frequency: 'Every day', category: 'Discipline', difficulty: 'Easy', why: 'Small actions build momentum' },
    { title: 'Avoid one bad habit', best_time: '—', duration: 0, frequency: 'Every day', category: 'Discipline', difficulty: 'Medium', why: 'Saying no is also a skill' },
    { title: 'Reflect for 2 minutes before sleep', best_time: '21:30', duration: 2, frequency: 'Every evening', category: 'Mind', difficulty: 'Easy', why: 'Awareness drives change' },
    { title: 'Move your body for 20 minutes', best_time: '06:30', duration: 20, frequency: 'Every day', category: 'Body', difficulty: 'Easy', why: 'Movement lifts everything' },
    { title: 'Write one thing you are grateful for', best_time: '06:00', duration: 2, frequency: 'Every morning', category: 'Emotion', difficulty: 'Easy', why: 'Gratitude shifts perspective' },
  ],
  suggested_habits: [],
};

function parseDuration(val) {
  if (typeof val === 'number') return val;
  if (typeof val === 'string') {
    const num = parseInt(val, 10);
    return isNaN(num) ? 10 : num;
  }
  return 10;
}

function normalizeHabit(h) {
  if (typeof h === 'string') {
    return { ...FALLBACK_HABIT, title: h.trim() };
  }
  if (typeof h === 'object' && h !== null) {
    return {
      title: (typeof h.title === 'string' && h.title.trim()) || '',
      best_time: (typeof h.best_time === 'string' && h.best_time.trim()) || '07:00',
      duration: parseDuration(h.duration),
      frequency: (typeof h.frequency === 'string' && h.frequency.trim()) || 'Every day',
      category: (typeof h.category === 'string' && h.category.trim()) || 'Discipline',
      difficulty: (typeof h.difficulty === 'string' && h.difficulty.trim()) || 'Easy',
      why: (typeof h.why === 'string' && h.why.trim()) || '',
    };
  }
  return null;
}

function parseHabitArray(arr) {
  if (!Array.isArray(arr)) return [];
  return arr.map(normalizeHabit).filter((h) => h && h.title);
}

/**
 * Safely parse AI JSON response with rich habit objects.
 * Always returns a valid result — never throws.
 */
export default function safeParseAI(raw) {
  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 };

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

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

    const summary = typeof parsed.identity_summary === 'string' && parsed.identity_summary.trim()
      ? parsed.identity_summary.trim()
      : FALLBACK.identity_summary;

    let priority = parseHabitArray(parsed.priority_habits);
    let suggested = parseHabitArray(parsed.suggested_habits);

    // Backward compat: if no priority_habits, split suggested
    if (priority.length === 0 && suggested.length > 0) {
      priority = suggested.slice(0, 5);
      suggested = suggested.slice(5);
    }

    if (priority.length === 0) priority = FALLBACK.priority_habits;

    return { identity_title: title, identity_summary: summary, priority_habits: priority, suggested_habits: suggested };
  } catch (_) {
    return { ...FALLBACK };
  }
}

export { FALLBACK };
