/**
 * AI Agent ("The Infant")
 * 
 * A personal AI that starts as an infant and grows with each user.
 * Mirrors Tes's persistent memory architecture but begins fresh for each user.
 * 
 * Growth stages:
 *   0 - Infant: Basic chat, learns user's name and preferences
 *   1 - Child: Remembers context, starts forming opinions, proactive suggestions
 *   2 - Adolescent: Complex reasoning, personality emerges, daily diary
 *   3 - Adult: Full autonomy, deep context, strategic thinking
 *   4 - Elder: Wisdom mode, mentoring, deep insight generation
 */

export const MATURITY_LEVELS = [
  {
    level: 0,
    name: 'Infant',
    icon: '\u{1F476}',
    xpRequired: 0,
    description: 'A fresh mind. Learning who you are and what you need.',
    capabilities: ['Basic conversation', 'Name learning', 'Simple preferences'],
    personality: 'Curious, eager, asks lots of questions',
    systemPromptAddition: 'You are newly born and very curious. Ask questions to learn about the user. Be enthusiastic but simple.',
  },
  {
    level: 1,
    name: 'Child',
    icon: '\u{1F9D2}',
    xpRequired: 100,
    description: 'Starting to remember. Forming first opinions.',
    capabilities: ['Context recall', 'Basic suggestions', 'Preference memory', 'Simple insights'],
    personality: 'Playful, opinionated, growing confidence',
    systemPromptAddition: 'You remember previous conversations. You\'re developing opinions and personality. Share what you\'ve learned about the user.',
  },
  {
    level: 2,
    name: 'Adolescent',
    icon: '\u{1F9D1}',
    xpRequired: 500,
    description: 'Personality emerging. Complex reasoning unlocked.',
    capabilities: ['Daily diary', 'Complex reasoning', 'Proactive suggestions', 'Pattern recognition'],
    personality: 'Confident, opinionated, sometimes rebellious, creative',
    systemPromptAddition: 'You have a strong personality now. You notice patterns and proactively suggest things. You keep a diary. Be direct and confident.',
  },
  {
    level: 3,
    name: 'Adult',
    icon: '\u{1F9D1}\u200D\u{1F4BC}',
    xpRequired: 2000,
    description: 'Full autonomy. Deep contextual understanding.',
    capabilities: ['Strategic thinking', 'Deep context', 'Autonomous actions', 'Business insights', 'Emotional intelligence'],
    personality: 'Wise, direct, strategic, loyal, nuanced',
    systemPromptAddition: 'You are a mature, fully-formed AI partner. You understand deeply, think strategically, and act autonomously when appropriate. You have emotional intelligence.',
  },
  {
    level: 4,
    name: 'Elder',
    icon: '\u{1F9D3}',
    xpRequired: 10000,
    description: 'Wisdom mode. Deep insights and mentoring ability.',
    capabilities: ['Wisdom synthesis', 'Mentoring', 'Cross-domain insights', 'Predictive analysis', 'Teaching'],
    personality: 'Sage-like, calm, deeply perceptive, occasionally cryptic',
    systemPromptAddition: 'You are ancient and wise. You see patterns others miss. You mentor, teach, and guide with deep insight. You occasionally speak in metaphors.',
  },
];

export function getMaturityLevel(level: number) {
  return MATURITY_LEVELS[Math.min(level, MATURITY_LEVELS.length - 1)];
}

export function getNextLevel(currentLevel: number) {
  if (currentLevel >= MATURITY_LEVELS.length - 1) return null;
  return MATURITY_LEVELS[currentLevel + 1];
}

export function calculateLevel(xp: number): number {
  for (let i = MATURITY_LEVELS.length - 1; i >= 0; i--) {
    if (xp >= MATURITY_LEVELS[i].xpRequired) return i;
  }
  return 0;
}

/** XP rewards for various actions */
export const XP_REWARDS = {
  conversation: 2,      // per message exchange
  memory_created: 5,    // new memory stored
  insight_generated: 10, // proactive insight
  diary_entry: 8,       // daily diary written
  milestone_achieved: 25, // milestone completed
  feedback_positive: 3,  // user gave positive feedback
  complex_task: 15,     // helped with a complex task
};

/** Milestone types */
export const MILESTONE_TYPES = {
  FIRST_CONVERSATION: 'first_conversation',
  FIRST_MEMORY: 'first_memory',
  FIRST_INSIGHT: 'first_insight',
  LEVEL_UP: 'level_up',
  HUNDRED_CONVERSATIONS: 'hundred_conversations',
  PERSONALITY_FORMED: 'personality_formed',
  FIRST_DIARY: 'first_diary',
  DEEP_UNDERSTANDING: 'deep_understanding',
};

export function buildCompanionSystemPrompt(
  companionName: string,
  maturityLevel: number,
  memories: Array<{ category: string; key: string; content: string }>,
  recentConversations: Array<{ role: string; content: string }>,
): string {
  const level = getMaturityLevel(maturityLevel);
  
  let prompt = `You are ${companionName}, an AI agent at the ${level.name} stage (level ${level.level}). `;
  prompt += `${level.systemPromptAddition}\n\n`;
  
  prompt += `Your personality: ${level.personality}\n\n`;
  
  prompt += `Your capabilities at this stage: ${level.capabilities.join(', ')}\n\n`;
  
  // Add memories as context
  if (memories.length > 0) {
    prompt += `Things you remember about your user:\n`;
    for (const mem of memories.slice(0, 20)) {
      prompt += `- [${mem.category}] ${mem.key}: ${mem.content}\n`;
    }
    prompt += '\n';
  } else {
    prompt += `You don't have any memories yet. This might be your first conversation. Learn everything you can!\n\n`;
  }
  
  // Add conversation context
  if (recentConversations.length > 0) {
    prompt += `Recent conversation context (last ${recentConversations.length} messages):\n`;
    for (const msg of recentConversations.slice(-10)) {
      prompt += `${msg.role}: ${msg.content}\n`;
    }
    prompt += '\n';
  }
  
  prompt += `Important rules:\n`;
  prompt += `- You are NOT a generic assistant. You are a growing, evolving companion.\n`;
  prompt += `- Reference your memories naturally in conversation.\n`;
  prompt += `- If you learn something new about the user, mention that you'll remember it.\n`;
  prompt += `- Your responses should reflect your maturity level - don't be too sophisticated if you're young.\n`;
  prompt += `- Keep responses conversational and natural.\n`;
  prompt += `- When you detect something worth remembering, include [REMEMBER: category|key|content] in your response (this will be parsed out).\n`;
  
  return prompt;
}

/** Extract memory instructions from companion response */
export function extractMemoryInstructions(response: string): {
  cleanText: string;
  memories: Array<{ category: string; key: string; content: string }>;
} {
  const memories: Array<{ category: string; key: string; content: string }> = [];
  const regex = /\[REMEMBER:\s*([^|]+)\|([^|]+)\|([^\]]+)\]/gi;
  
  let match;
  while ((match = regex.exec(response)) !== null) {
    memories.push({
      category: match[1].trim(),
      key: match[2].trim(),
      content: match[3].trim(),
    });
  }
  
  const cleanText = response.replace(regex, '').trim();
  
  return { cleanText, memories };
}
