/**
 * AI Prompt Library for SOP Pipeline
 *
 * Generates a complete SOP in 3 stages:
 * identity, steps/workflow, and strategy/metadata.
 */

// ============================================
// TYPES
// ============================================

export interface SopPipelineInputs {
  title: string;
  shortDescription?: string;
  department?: string;
  companyName: string;
  companyDescription?: string;
  companyIndustry?: string;
  companyBusinessModel?: string;
  companyTargetAudience?: string;
  companyPrimaryOffering?: string;
  companyUsps?: string[];
  brandVoice?: string;
  productNames?: string[];
  courseTitles?: string[];
  eventTitles?: string[];
}

export type PartialSopAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// HELPERS
// ============================================

function buildCompanyContext(inputs: SopPipelineInputs): string {
  const parts: string[] = [];
  if (inputs.companyName) parts.push(`Company: ${inputs.companyName}`);
  if (inputs.companyDescription) parts.push(`Description: ${inputs.companyDescription}`);
  if (inputs.companyIndustry) parts.push(`Industry: ${inputs.companyIndustry}`);
  if (inputs.companyBusinessModel) parts.push(`Business Model: ${inputs.companyBusinessModel}`);
  if (inputs.companyTargetAudience) parts.push(`Target Audience: ${inputs.companyTargetAudience}`);
  if (inputs.companyPrimaryOffering) parts.push(`Primary Offering: ${inputs.companyPrimaryOffering}`);
  if (inputs.companyUsps?.length) parts.push(`Key USPs: ${inputs.companyUsps.join(', ')}`);
  if (inputs.brandVoice) parts.push(`Brand Voice: ${inputs.brandVoice}`);
  if (inputs.productNames?.length) parts.push(`Products: ${inputs.productNames.join(', ')}`);
  if (inputs.courseTitles?.length) parts.push(`Courses: ${inputs.courseTitles.join(', ')}`);
  if (inputs.eventTitles?.length) parts.push(`Events: ${inputs.eventTitles.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: SOP IDENTITY
// ============================================

export function buildSopIdentityPrompt(inputs: SopPipelineInputs): PromptResult {
  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are an SOP process design strategist AI. Generate a Standard Operating Procedure for the given title and company context. The SOP should be practical, clear, and aligned with the company's operations.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "sop": {
    "title": "string — SOP title (refine if needed)",
    "shortDescription": "string — 1-2 sentence summary of the SOP",
    "detailedDescription": "string — 2-3 paragraph detailed description of what this SOP covers",
    "objective": "string — clear objective statement, 1-2 sentences",
    "scope": "string — scope of the SOP, 1-2 sentences",
    "department": "string — one of: engineering, marketing, sales, design, operations, hr, finance, customer-success, product, legal, other",
    "priority": "string — one of: low, medium, high, critical",
    "visibility": "string — one of: private, internal, public",
    "tags": ["array of 3-5 relevant tags"],
    "prerequisites": ["array of 2-4 prerequisites as strings"]
  }
}`;

  const userPrompt = `Generate an SOP for:\nTitle: ${inputs.title}\n${inputs.shortDescription ? `Description: ${inputs.shortDescription}\n` : ''}${inputs.department ? `Department: ${inputs.department}\n` : ''}\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 4000 };
}

// ============================================
// STAGE 2: SOP STEPS / WORKFLOW
// ============================================

export function buildSopStepsPrompt(inputs: SopPipelineInputs, partial: PartialSopAnalysis): PromptResult {
  const sopSummary = [
    partial.sop?.title ? `SOP: ${partial.sop.title}` : '',
    partial.sop?.department ? `Department: ${partial.sop.department}` : '',
    partial.sop?.objective ? `Objective: ${partial.sop.objective}` : '',
    partial.sop?.scope ? `Scope: ${partial.sop.scope}` : '',
  ].filter(Boolean).join('\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are an SOP workflow architect AI. Generate 5-8 practical steps for the given SOP. Each step should have clear instructions, a checklist, and an estimated time.

Keep each field concise — shorter valid JSON is better than longer broken JSON.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "steps": [
    {
      "id": "string — unique ID, e.g. 'step-1'",
      "title": "string — step title, e.g. 'Gather Requirements'",
      "description": "string — 2-3 sentence step description",
      "order": "number — step order, starting from 1",
      "type": "string — one of: instruction, decision, check, note",
      "assignee": "string or null — role responsible, e.g. 'Project Manager'",
      "estimatedTime": "string — e.g. '15 min', '1 hour'",
      "checklist": ["array of 2-4 checklist items as strings"],
      "conditions": ["array of conditions as strings, or empty array"]
    }
  ]
}

Generate 5-8 steps that form a logical, sequential workflow. Steps should be actionable and specific to the SOP's objective and the company's context.`;

  const userPrompt = `Generate SOP steps for:\n\n${sopSummary}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 5000 };
}

// ============================================
// STAGE 3: SOP STRATEGY & METADATA
// ============================================

export function buildSopStrategyPrompt(inputs: SopPipelineInputs, partial: PartialSopAnalysis): PromptResult {
  const stepsSummary = (partial.steps || []).map((s: any, i: number) =>
    `Step ${i + 1}: ${s.title || 'N/A'} | Type: ${s.type || 'N/A'}`
  ).join('\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are an SOP compliance and optimization strategist AI. Generate metadata, internal notes, and optimization tips for the SOP.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "sop": {
    "internalNotes": "string — internal notes about implementation, 2-3 sentences",
    "metaTitle": "string — SEO-friendly title, under 60 characters",
    "metaDescription": "string — SEO-friendly description, under 160 characters"
  },
  "complianceNotes": ["array of 2-3 compliance or regulatory considerations"],
  "optimizationTips": ["array of 2-3 tips for improving SOP effectiveness"]
}`;

  const userPrompt = `Generate SOP strategy for:\n\n${stepsSummary}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 3000 };
}

// ============================================
// ENHANCEMENT PROMPT
// ============================================

export function buildSopEnhancementPrompt(
  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 SOP process design strategist 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: 3000 };
}