/**
 * AI Prompt Library for Course Quick Generate Pipeline
 *
 * Generates a complete course in 3 stages: course identity,
 * chapter structure with quizzes, and lesson content with quizzes.
 */

// ============================================
// TYPES
// ============================================

export interface CoursePipelineInputs {
  title: string;
  shortDescription?: string;
  format?: string;
  difficulty?: string;
  targetChapterCount: number;

  companyName?: string;
  companyDescription?: string;
  companyIndustry?: string;
  brandVoice?: string;
  productNames?: string[];
}

export type PartialCourseAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// HELPERS
// ============================================

function buildInputContext(inputs: CoursePipelineInputs): string {
  const parts: string[] = [];
  parts.push(`Course Title: ${inputs.title}`);
  if (inputs.shortDescription) parts.push(`Description: ${inputs.shortDescription}`);
  if (inputs.format) parts.push(`Format: ${inputs.format}`);
  if (inputs.difficulty) parts.push(`Difficulty: ${inputs.difficulty}`);
  if (inputs.targetChapterCount) parts.push(`Target Chapters: ${inputs.targetChapterCount}`);
  if (inputs.companyName) parts.push(`Company: ${inputs.companyName}`);
  if (inputs.companyDescription) parts.push(`Company Description: ${inputs.companyDescription}`);
  if (inputs.companyIndustry) parts.push(`Industry: ${inputs.companyIndustry}`);
  if (inputs.brandVoice) parts.push(`Brand Voice: ${inputs.brandVoice}`);
  if (inputs.productNames?.length) parts.push(`Products: ${inputs.productNames.join(', ')}`);
  return parts.join('\n');
}

const JSON_INSTRUCTION = '\n\nCRITICAL OUTPUT FORMAT RULES:\n1. Respond with ONLY a single valid JSON object.\n2. Do NOT wrap in markdown code fences (no ```json``` or ``` blocks).\n3. Do NOT include any text, explanation, or commentary before or after the JSON.\n4. Ensure all strings are properly escaped. Ensure all arrays and objects are properly closed.\n5. If the response is too long, reduce detail per item rather than producing broken JSON.';

// ============================================
// STAGE 1: COURSE IDENTITY
// ============================================

export function buildCourseIdentityPrompt(inputs: CoursePipelineInputs): PromptResult {
  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are an expert instructional designer AI. Generate a complete course profile based on the given title and context.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "course": {
    "title": "string — the course title, refined and polished if needed (keep it professional and descriptive)",
    "shortDescription": "string — concise course description, max 500 chars",
    "detailedDescription": "string — comprehensive course description, 2-3 paragraphs",
    "summary": "string — one-sentence course summary",
    "format": "string — one of: video, text, live, hybrid, workshop",
    "difficulty": "string — one of: beginner, intermediate, advanced, expert",
    "duration": "string — estimated total duration, e.g. '8 hours'",
    "estimatedCompletionTime": "string — e.g. '4 weeks'",
    "language": "string — default 'English'",
    "instructor": "string — suggested instructor name or role",
    "skillLevel": "string — skill level description, e.g. 'Foundational to Intermediate'",
    "learningObjectives": ["array of 4-6 learning objectives"],
    "outcomes": ["array of 4-6 expected outcomes"],
    "prerequisites": ["array of 1-3 prerequisites, or empty array if none"],
    "tags": ["array of 3-5 relevant tags"],
    "audienceType": "string — one of: public, internal, team-specific, department-specific, admin-only"
  }
}`;

  const userPrompt = `Generate a complete course profile for:\n\n${buildInputContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 40000 };
}

// ============================================
// STAGE 2: CHAPTER STRUCTURE + QUIZZES
// ============================================

export function buildCourseChapterPrompt(inputs: CoursePipelineInputs, partial: PartialCourseAnalysis): PromptResult {
  const courseSummary = [
    partial.course?.shortDescription ? `Description: ${partial.course.shortDescription}` : '',
    partial.course?.difficulty ? `Difficulty: ${partial.course.difficulty}` : '',
    partial.course?.learningObjectives?.length ? `Objectives: ${partial.course.learningObjectives.join(', ')}` : '',
  ].filter(Boolean).join('\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are an expert instructional designer AI. Generate ${inputs.targetChapterCount} chapters for the given course, each with 2-3 lessons and a chapter quiz.

Keep each field concise — shorter valid JSON is better than longer broken JSON.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "chapters": [
    {
      "title": "string — chapter title, e.g. 'Introduction to Digital Marketing'",
      "description": "string — 1-2 sentence chapter description",
      "order": "number — chapter order, starting from 0",
      "duration": "string — e.g. '2 hours'",
      "learningObjectives": ["array of 2-4 chapter learning objectives"],
      "lessons": [
        {
          "title": "string — lesson title",
          "description": "string — 1-2 sentence lesson description",
          "order": "number — lesson order within chapter, starting from 0",
          "format": "string — one of: video, text, audio, pdf, presentation, interactive, quiz",
          "duration": "string — e.g. '30 minutes'"
        }
      ],
      "quizQuestions": [
        {
          "id": "string — unique ID, e.g. 'ch1-q1'",
          "question": "string — multiple choice question",
          "options": ["array of exactly 4 answer options"],
          "correctAnswer": "number — 0-based index of correct option, 0-3",
          "explanation": "string — brief explanation of why the answer is correct"
        }
      ]
    }
  ]
}

Generate exactly ${inputs.targetChapterCount} chapters. Each chapter should have 2-3 lessons and 2-3 quiz questions. Chapters should follow a logical learning progression.`;

  const userPrompt = `Generate chapter structure for the course "${inputs.title}":\n\n${courseSummary}\n\n${buildInputContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 100000 };
}

// ============================================
// STAGE 3: LESSON CONTENT + QUIZZES
// ============================================

export function buildCourseLessonPrompt(inputs: CoursePipelineInputs, partial: PartialCourseAnalysis): PromptResult {
  const chaptersSummary = (partial.chapters || []).map((ch: any, i: number) => {
    const lessons = (ch.lessons || []).map((l: any, j: number) =>
      `  Lesson ${j + 1}: ${l.title || 'N/A'} | Format: ${l.format || 'text'} | Duration: ${l.duration || 'N/A'}`
    ).join('\n');
    return `Chapter ${i + 1}: ${ch.title || 'N/A'}\n${lessons}`;
  }).join('\n\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are an expert instructional content writer AI. For each lesson, generate detailed content, learning objectives, key takeaways, and quiz questions.

Keep each field concise — shorter valid JSON is better than longer broken JSON.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "chapters": [
    {
      "title": "string — same chapter title",
      "lessons": [
        {
          "title": "string — same lesson title",
          "content": "string — comprehensive lesson content in HTML format using <h3>, <p>, <ul>, <li>, <strong>, <em> tags. Well-structured educational content, 500-1500 chars",
          "learningObjectives": ["array of 2-3 specific lesson objectives"],
          "keyTakeaways": ["array of 2-3 key takeaways from the lesson"],
          "quizQuestions": [
            {
              "id": "string — unique ID, e.g. 'ch1-l1-q1'",
              "question": "string — multiple choice question specific to the lesson",
              "options": ["array of exactly 4 answer options"],
              "correctAnswer": "number — 0-based index, 0-3",
              "explanation": "string — brief explanation"
            }
          ]
        }
      ]
    }
  ]
}

Generate content for ALL lessons across ALL chapters. Each lesson should have 2-3 quiz questions.`;

  const userPrompt = `Generate lesson content for course "${inputs.title}":\n\n${chaptersSummary}\n\n${buildInputContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 120000 };
}

// ============================================
// ENHANCEMENT PROMPT
// ============================================

export function buildCourseEnhancementPrompt(
  stageName: string,
  stageOutput: Record<string, any>,
  lowConfidenceFields: string[]
): PromptResult {
  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are an expert instructional designer AI performing a refinement pass. The previous analysis for "${stageName}" had low confidence on certain fields. Provide more specific, detailed content for the indicated fields.${JSON_INSTRUCTION}

Respond with the SAME JSON schema as before, but with improved values for the flagged fields. Keep the fields that already had good results unchanged.`;

  const userPrompt = `Previous analysis:\n${JSON.stringify(stageOutput, null, 2)}\n\nFields needing improvement (low confidence): ${lowConfidenceFields.join(', ')}\n\nPlease refine the analysis.`;

  return { systemPrompt, userPrompt, maxTokens: 30000 };
}