/**
 * AI Prompt Library for Event Quick Generate Pipeline
 *
 * Generates a complete event with sessions in 3 stages:
 * event identity, session structure, and optimization.
 */

// ============================================
// TYPES
// ============================================

export interface EventPipelineInputs {
  title: string;
  shortDescription?: string;
  eventDate?: string;
  startTime?: string;
  endTime?: string;
  eventType?: string;
  eventMode?: string;
  targetSessionCount: number;

  companyName?: string;
  companyDescription?: string;
  companyIndustry?: string;
  brandVoice?: string;
  productNames?: string[];
  // Optional free-text context compiled from user-selected Data Sources (Generate with AI flow)
  additionalContext?: string;
}

export type PartialEventAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// HELPERS
// ============================================

function buildInputContext(inputs: EventPipelineInputs): string {
  const parts: string[] = [];
  parts.push(`Event Title: ${inputs.title}`);
  if (inputs.shortDescription) parts.push(`Description: ${inputs.shortDescription}`);
  if (inputs.eventDate) parts.push(`Date: ${inputs.eventDate}`);
  if (inputs.startTime) parts.push(`Start Time: ${inputs.startTime}`);
  if (inputs.endTime) parts.push(`End Time: ${inputs.endTime}`);
  if (inputs.eventType) parts.push(`Event Type: ${inputs.eventType}`);
  if (inputs.eventMode) parts.push(`Event Mode: ${inputs.eventMode}`);
  if (inputs.targetSessionCount) parts.push(`Target Sessions: ${inputs.targetSessionCount}`);
  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(', ')}`);
  if (inputs.additionalContext) parts.push(`\nReference data from selected data sources (use where relevant to make the event specific and accurate):\n${inputs.additionalContext}`);
  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: EVENT IDENTITY
// ============================================

export function buildEventIdentityPrompt(inputs: EventPipelineInputs): PromptResult {
  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are an expert event planner AI. Generate a complete event profile based on the given title and context.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "event": {
    "shortDescription": "string — concise event description, max 500 chars",
    "detailedDescription": "string — comprehensive event description, 2-3 paragraphs",
    "summary": "string — one-sentence event summary",
    "eventType": "string — one of: meeting, workshop, conference, webinar, training, product_launch, campaign_event, sop_training, team_activity, onboarding, hr_activity, other",
    "eventMode": "string — one of: online, offline, hybrid",
    "priority": "string — one of: low, medium, high, critical",
    "visibility": "string — one of: private, internal, public",
    "audienceType": "string — one of: public, internal, team_specific, department_specific, admin_only",
    "duration": "string — e.g. '3 hours'",
    "location": "string — suggested venue or 'Virtual' for online events",
    "meetingLink": "string — suggested meeting URL path, e.g. '/meet/event-name'",
    "organizer": "string — suggested organizer name or role",
    "coordinator": "string — suggested coordinator name or role",
    "objectives": ["array of 3-5 event objectives"],
    "expectedOutcomes": ["array of 3-5 expected outcomes"],
    "prerequisites": ["array of 1-3 prerequisites, or empty array"],
    "tags": ["array of 3-5 relevant tags"]
  }
}`;

  const userPrompt = `Generate a complete event profile for:\n\n${buildInputContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 40000 };
}

// ============================================
// STAGE 2: SESSION STRUCTURE
// ============================================

export function buildEventSessionPrompt(inputs: EventPipelineInputs, partial: PartialEventAnalysis): PromptResult {
  const eventSummary = [
    partial.event?.shortDescription ? `Description: ${partial.event.shortDescription}` : '',
    partial.event?.eventType ? `Type: ${partial.event.eventType}` : '',
    partial.event?.eventMode ? `Mode: ${partial.event.eventMode}` : '',
    partial.event?.objectives?.length ? `Objectives: ${partial.event.objectives.join(', ')}` : '',
  ].filter(Boolean).join('\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are an expert event planner AI. Generate ${inputs.targetSessionCount} sessions for the given event, each with a checklist.

Keep each field concise — shorter valid JSON is better than longer broken JSON.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "sessions": [
    {
      "title": "string — session title, e.g. 'Opening Keynote: The Future of AI'",
      "description": "string — 1-2 sentence session description",
      "order": "number — session order, starting from 0",
      "duration": "string — e.g. '45 minutes'",
      "speakerInfo": "string — speaker name and title, e.g. 'Dr. Sarah Chen, CTO'",
      "objectives": ["array of 1-3 session objectives"],
      "status": "string — one of: draft, review, approved, published, cancelled",
      "checklistItems": [
        {
          "id": "string — unique ID, e.g. 's1-c1'",
          "text": "string — checklist item text",
          "order": "number — item order, starting from 0",
          "done": "boolean — always false"
        }
      ]
    }
  ]
}

Generate exactly ${inputs.targetSessionCount} sessions. Sessions should follow a logical event flow (opening, content sessions, closing). Each session should have 2-4 checklist items.`;

  const userPrompt = `Generate session structure for event "${inputs.title}":\n\n${eventSummary}\n\n${buildInputContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 50000 };
}

// ============================================
// STAGE 3: EVENT STRATEGY & SEO
// ============================================

export function buildEventStrategyPrompt(inputs: EventPipelineInputs, partial: PartialEventAnalysis): PromptResult {
  const sessionsSummary = (partial.sessions || []).map((s: any, i: number) =>
    `Session ${i + 1}: ${s.title || 'N/A'} | Duration: ${s.duration || 'N/A'} | Speaker: ${s.speakerInfo || 'N/A'}`
  ).join('\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are an expert event marketing strategist AI. Generate SEO and optimization data for the given event.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "event": {
    "metaTitle": "string — SEO title, max 60 chars",
    "metaDescription": "string — SEO description, max 160 chars",
    "seoKeywords": ["array of 3-5 SEO keywords"],
    "timeZone": "string — suggested timezone, e.g. 'UTC', 'America/New_York', 'Asia/Kolkata'"
  },
  "bestPractices": ["array of 3-5 event planning best practices"],
  "optimizationTips": ["array of 2-3 tips for maximizing event impact"]
}`;

  const userPrompt = `Generate event strategy for "${inputs.title}":\n\n${sessionsSummary}\n\n${buildInputContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 30000 };
}

// ============================================
// ENHANCEMENT PROMPT
// ============================================

export function buildEventEnhancementPrompt(
  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 event planner 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: 20000 };
}