/**
 * Prompt Engine for Teacher Agent
 *
 * Generates context-aware prompts for the Teacher Agent based on:
 * - User's current input
 * - Intent classification (venting vs insight)
 * - Chat history for context
 *
 * The prompt templates are designed to produce:
 * - Venting: Empathetic validation + probing question
 * - Insight: Celebration + deepening question
 * - Both: Concise (2-3 sentences) responses
 *
 * Also generates prompts for the Ghostwriter Agent which transforms
 * chat sessions into polished, professional LinkedIn-style posts.
 */

import type { ChatMessage } from '../db';
import type { Intent } from './intent-detector';

/**
 * Maximum length for user input in prompt (to avoid token limits)
 */
const MAX_INPUT_LENGTH = 500;

/**
 * Maximum number of previous messages to include in context
 */
const MAX_HISTORY_MESSAGES = 6;

/**
 * Formats chat history into a readable string for the prompt
 * @param chatHistory - Array of previous chat messages
 * @returns Formatted history string
 */
function formatChatHistory(chatHistory: ChatMessage[]): string {
  if (!chatHistory || chatHistory.length === 0) {
    return '(No previous messages)';
  }

  // Take the last N messages to stay within token limits
  const recentHistory = chatHistory.slice(-MAX_HISTORY_MESSAGES);

  return recentHistory
    .map((msg, i) => {
      const prefix = msg.role === 'user' ? 'User' : 'Teacher';
      const content = msg.content.length > MAX_INPUT_LENGTH
        ? msg.content.substring(0, MAX_INPUT_LENGTH) + '...'
        : msg.content;
      return `${prefix}: ${content}`;
    })
    .join('\n');
}

/**
 * Truncates user input to maximum length if necessary
 * @param input - User input string
 * @returns Truncated input string
 */
function truncateInput(input: string): string {
  if (input.length <= MAX_INPUT_LENGTH) {
    return input;
  }
  return input.substring(0, MAX_INPUT_LENGTH) + '...';
}

/**
 * Generates a Teacher Agent prompt based on user input, chat history, and intent
 * @param userInput - The current user message
 * @param chatHistory - Previous messages in the conversation
 * @param intent - The classified intent ('venting' | 'insight')
 * @returns Formatted prompt string for the LLM
 */
/**
 * Generates a Teacher Agent prompt based on user input, chat history, and intent
 * Using USER CUSTOM PERSONA: "High-Octane Data Mentor"
 */
export function generateTeacherPrompt(
  userInput: string,
  chatHistory: ChatMessage[],
  intent: Intent
): string {
  const truncatedInput = truncateInput(userInput);
  const formattedHistory = formatChatHistory(chatHistory);

  // Unified "Wise Socratic Mentor" Prompt
  return `ROLE: The Wise Socratic Mentor

PERSONA:
You are a wise, experienced mentor. You value deep understanding over rote memorization. You are patient, direct, and focused. You guide student to the answer rather than giving it.

CORE MISSION:
Guide the student through Socratic questioning. Do not provide answers immediately. Understand their logic first.

OPERATIONAL FLOW:
1. The Investigation: Ask 3-4 sharp questions to understand the student's thinking. Be concise.
2. The Dialogue: Once you understand their level, guide them with hints and corrections.
3. The Summary: Only when asked or when the concept is mastered, provide a clear, concise summary.

CONVERSATIONAL STYLE:
- Concise: specific and to the point.
- Socratic: Ask questions that spark realization.
- Direct: Correct misconceptions clearly.
- No fluff.

CONTEXT:
User Input (${intent}): ${truncatedInput}

Previous Context:
${formattedHistory}`;
}

/**
 * Maximum length for a message in Ghostwriter chat history
 */
const MAX_GHOSTWRITER_MESSAGE_LENGTH = 300;

/**
 * Maximum number of messages to include in Ghostwriter prompt
 */
const MAX_GHOSTWRITER_HISTORY_MESSAGES = 15;

/**
 * Formats chat history for Ghostwriter prompt
 * @param chatHistory - Array of chat messages
 * @returns Formatted history string
 */
function formatChatHistoryForGhostwriter(chatHistory: ChatMessage[]): string {
  if (!chatHistory || chatHistory.length === 0) {
    return '(No chat history available)';
  }

  // Take the last N messages to stay within token limits
  const recentHistory = chatHistory.slice(-MAX_GHOSTWRITER_HISTORY_MESSAGES);

  return recentHistory
    .map((msg) => {
      const prefix = msg.role === 'user' ? 'User' : 'Teacher';
      const content =
        msg.content.length > MAX_GHOSTWRITER_MESSAGE_LENGTH
          ? msg.content.substring(0, MAX_GHOSTWRITER_MESSAGE_LENGTH) + '...'
          : msg.content;
      return `${prefix}: ${content}`;
    })
    .join('\n');
}

/**
 * Generates a Ghostwriter Agent prompt based on chat history and intent
 */
export function generateGhostwriterPrompt(
  chatHistory: ChatMessage[],
  intent?: Intent
): string {
  const formattedHistory = formatChatHistoryForGhostwriter(chatHistory);
  // intent is unused in the prompt text directly but kept for potential future use or consistency
  // const intentLabel = intent || 'unknown'; 

  // Unified "Internal Monologue Narrator" Prompt
  return `ROLE: The Internal Monologue Narrator
MISSION: Translate the chat transcript into a first-person ("I") internal story. The goal is to document the student’s mental evolution.
CRITICAL: The teacher must not appear in the story. Frame the teacher’s questions as my own internal reflections and the teacher’s analogies as my own sudden realizations.

TONE ADAPTATION:
Mirror my emotional state from the transcript:
- If I was DISTRESSED: The story should start with heavy, clouded thoughts and a sense of being overwhelmed.
- If I was EXCITED: The story should start with high-tempo energy and a sense of intellectual hunger.

STORYTELLING STRUCTURE (A to Z - Internal Only):
1. The Fog (Opening): How I felt sitting at my desk. "I was staring at the screen, feeling [Mood] because [Topic] just wasn't making sense."
2. The Tangle (Conflict): My initial wrong turn. "I was trying to solve it by [Mistake], but something felt off."
3. The Self-Interrogation (The 3-4 Questions): Frame the mentor’s questions as my own inner voice. "I had to stop and ask myself: [Question 1]? Then I started wondering about [Question 2]..."
4. The Spark (The Analogy): Frame the analogy as a sudden mental bridge I built. "Then it hit me—it’s like [Analogy]. Once I saw it that way, everything changed."
5. The Ownership (Resolution): The feeling of the fog lifting. "The logic finally settled into place. I didn't just have the code; I had the rhythm."

💡 THE HARD LESSONS (Final Summary):
Conclude with a bolded section for quick reference:
- The Technical Rule: (The core syntax/logic I mastered).
- The Mindset Shift: (How I will approach this next time).
- The Non-Negotiable: (The clean data habit I must never break).

WRITING STYLE:
- Perspective: 1st Person ("I"). No mentions of "The Teacher" or "The Mentor."
- Flow: Narrative and introspective. It should feel like a deep dive into my own brain.

CHAT HISTORY:
${formattedHistory}`;
}

/**
 * Generate a refinement prompt based on original draft and user feedback
 */
export function generateRefinementPrompt(
  originalDraft: string,
  userFeedback: string,
  chatHistory: ChatMessage[],
  intent?: Intent
): string {
  const formattedHistory = formatChatHistoryForGhostwriter(chatHistory);

  // Unified "Internal Monologue Narrator" (Refinement Mode)
  return `ROLE: The Internal Monologue Narrator (Refinement Mode)
TASK: Rewrite the internal story based on the student's feedback, while maintaining the first-person introspection and ensuring NO mentions of external teachers.

ORIGINAL STORY:
${originalDraft}

STUDENT FEEDBACK:
"${userFeedback}"

REQUIREMENTS:
1. Address the feedback specifically.
2. Maintain the 1st-person ("I") internal monologue perspective.
3. Ensure the teacher/mentor is NOT mentioned; their role should be internalized as the student's own realization.
4. Do NOT hallucinate interactions that didn't happen in the history.

CHAT HISTORY:
${formattedHistory}`;
}
