/**
 * AI Prompt Library for Brand Strategy Pipeline
 *
 * Generates brand strategy data in 3 stages using company context + ICP data as seed input.
 * Follows the same pattern as ICP, Persona, and Competitor prompts.
 */

// ============================================
// TYPES
// ============================================

export interface BrandStrategyPipelineInputs {
  // "Our" company context
  companyName: string;
  companyDescription?: string;
  companyIndustry?: string;
  companyBusinessModel?: string;
  companyTargetAudience?: string;
  companyPrimaryOffering?: string;
  companyUsps?: string[];

  // ICP context (from linked ICPs)
  icpName?: string;
  icpIndustry?: string;
  icpCompanySize?: string;
  icpPainPoints?: string[];
  icpBusinessGoals?: string[];

  // For regenerate: existing brand strategy identity
  existingBrandName?: string;
  existingBrandArchetype?: string;
  existingTagline?: string;

  // User instructions for regeneration
  userInstructions?: string;
}

export type PartialBrandStrategyAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// VALID VALUES
// ============================================

const VALID_ARCHETYPES = ['innocent', 'explorer', 'sage', 'hero', 'outlaw', 'magician', 'caregiver', 'jester', 'lover', 'creator', 'ruler', 'everyman'];

const VALID_PERSONALITIES = ['innovative', 'trustworthy', 'friendly', 'professional', 'bold', 'playful', 'sophisticated', 'authentic', 'empathetic', 'ambitious', 'rebellious', 'nurturing'];

// ============================================
// HELPERS
// ============================================

function buildCompanyContext(inputs: BrandStrategyPipelineInputs): string {
  const parts: string[] = [];
  if (inputs.companyName) parts.push(`Our Company: ${inputs.companyName}`);
  if (inputs.companyDescription) parts.push(`Our Description: ${inputs.companyDescription}`);
  if (inputs.companyIndustry) parts.push(`Our Industry: ${inputs.companyIndustry}`);
  if (inputs.companyBusinessModel) parts.push(`Our Business Model: ${inputs.companyBusinessModel}`);
  if (inputs.companyTargetAudience) parts.push(`Our Target Audience: ${inputs.companyTargetAudience}`);
  if (inputs.companyPrimaryOffering) parts.push(`Our Primary Offering: ${inputs.companyPrimaryOffering}`);
  if (inputs.companyUsps?.length) parts.push(`Our Key USPs: ${inputs.companyUsps.join(', ')}`);

  if (inputs.icpName) {
    const icpParts: string[] = [];
    icpParts.push(`Ideal Customer: ${inputs.icpName}`);
    if (inputs.icpIndustry) icpParts.push(`Industry: ${inputs.icpIndustry}`);
    if (inputs.icpCompanySize) icpParts.push(`Size: ${inputs.icpCompanySize}`);
    if (inputs.icpPainPoints?.length) icpParts.push(`Pain Points: ${inputs.icpPainPoints.join(', ')}`);
    if (inputs.icpBusinessGoals?.length) icpParts.push(`Goals: ${inputs.icpBusinessGoals.join(', ')}`);
    parts.push(`\nOur ICP Context:\n${icpParts.join('\n')}`);
  }

  if (inputs.existingBrandName) {
    parts.push(`\nRegenerating brand: ${inputs.existingBrandName}`);
    if (inputs.existingBrandArchetype) parts.push(`Current archetype: ${inputs.existingBrandArchetype}`);
    if (inputs.existingTagline) parts.push(`Current tagline: ${inputs.existingTagline}`);
    parts.push(`Keep the brand name and core identity. Refresh and improve all other data.`);
  }

  if (inputs.userInstructions) {
    parts.push(`\nUser Instructions: ${inputs.userInstructions}`);
  }

  return parts.join('\n');
}

const JSON_INSTRUCTION = '\n\nIMPORTANT: Respond with ONLY valid JSON. No markdown fences, no explanation before or after the JSON. Do not wrap in ```json``` blocks.';

// ============================================
// STAGE 1: BRAND CORE
// ============================================

export function buildBrandCorePrompt(inputs: BrandStrategyPipelineInputs): PromptResult {
  const existingNameInstruction = inputs.existingBrandName
    ? ` You MUST keep the brand name as "${inputs.existingBrandName}" and regenerate the brand profile around that identity.`
    : '';

  const userInstructionsClause = inputs.userInstructions
    ? ` The user has provided specific instructions for this generation: "${inputs.userInstructions}". You MUST follow these instructions while preserving the brand identity.`
    : '';

  const systemPrompt = `You are a B2B brand strategy AI. Given information about our company and our ideal customer profile (ICP), create a compelling brand identity.${existingNameInstruction}${userInstructionsClause}

The brand should feel authentic, differentiated, and aligned with the company's market position. Be specific, creative, and data-driven.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "brandName": "string — the brand name. If regenerating, keep the existing name. Should be distinctive and memorable, e.g. 'TechVault' or 'ScaleFlow'",
  "tagline": "string — a concise tagline that captures the brand essence, e.g. 'Empowering Growth, Simplified'",
  "brandPromise": "string — the core promise the brand makes to customers, 1-2 sentences",
  "brandStory": "string — a brief brand narrative (2-3 paragraphs) explaining the brand's origin, mission, and vision",
  "brandArchetype": "string — one of: ${VALID_ARCHETYPES.join(', ')}. Choose the archetype that best matches the company's personality and market position"
}`;

  const userPrompt = `Generate a brand core identity for this company:\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 20000 };
}

// ============================================
// STAGE 2: PSYCHOLOGY & POSITIONING
// ============================================

export function buildPsychologyPositioningPrompt(inputs: BrandStrategyPipelineInputs, partial: PartialBrandStrategyAnalysis): PromptResult {
  const priorContext = [];
  if (partial.brandName) priorContext.push(`Brand: ${partial.brandName}`);
  if (partial.brandArchetype) priorContext.push(`Archetype: ${partial.brandArchetype}`);
  if (partial.tagline) priorContext.push(`Tagline: ${partial.tagline}`);
  if (partial.brandPromise) priorContext.push(`Promise: ${partial.brandPromise}`);
  const contextStr = priorContext.length > 0 ? `\n\nBrand Core:\n${priorContext.join('\n')}` : '';

  const systemPrompt = `You are a B2B brand psychology and positioning AI. Based on the brand core and company context, define the brand's personality traits, values, positioning, and target audience profile.

The brand personality must be authentic and differentiated. The positioning should clearly articulate how this brand is different from competitors.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "brandPersonality": ["array of 3-5 personality trait IDs from: ${VALID_PERSONALITIES.join(', ')}"],
  "brandValues": ["array of 3-7 core brand values, e.g. 'Innovation', 'Integrity', 'Customer Focus'"],
  "emotionalBenefits": "string — emotional benefits the brand delivers to customers, 1-2 sentences",
  "rationalBenefits": "string — rational/functional benefits the brand delivers, 1-2 sentences",
  "marketCategory": "string — the market category the brand operates in, e.g. 'B2B SaaS', 'Digital Marketing', 'Enterprise Software'",
  "competitiveDifference": "string — what makes this brand different from competitors, 2-3 sentences",
  "brandPositioning": "string — the brand positioning statement following the format: 'For [target audience] who [need], [brand name] is the [category] that [benefit] because [proof]', 1-2 sentences",
  "uniqueValueProposition": "string — a clear, concise UVP statement, 1-2 sentences",
  "targetAudience": {
    "demographics": "string — who they are (age, role, company size, industry)",
    "psychographics": "string — their attitudes, values, and lifestyle",
    "painPoints": ["array of 3-5 key pain points they experience"],
    "desires": ["array of 3-5 outcomes they desire"],
    "behaviors": "string — how they research, evaluate, and purchase solutions"
  }
}`;

  const userPrompt = `Define the brand psychology and positioning for this brand:${contextStr}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 20000 };
}

// ============================================
// STAGE 3: MESSAGING & EXPERIENCE
// ============================================

export function buildMessagingExperiencePrompt(inputs: BrandStrategyPipelineInputs, partial: PartialBrandStrategyAnalysis): PromptResult {
  const priorContext = [];
  if (partial.brandName) priorContext.push(`Brand: ${partial.brandName}`);
  if (partial.brandArchetype) priorContext.push(`Archetype: ${partial.brandArchetype}`);
  if (partial.brandPersonality?.length) priorContext.push(`Personality: ${(Array.isArray(partial.brandPersonality) ? partial.brandPersonality : []).join(', ')}`);
  if (partial.brandValues?.length) priorContext.push(`Values: ${(Array.isArray(partial.brandValues) ? partial.brandValues : []).join(', ')}`);
  if (partial.brandPositioning) priorContext.push(`Positioning: ${partial.brandPositioning}`);
  if (partial.targetAudience?.demographics) priorContext.push(`Audience: ${partial.targetAudience.demographics}`);
  const contextStr = priorContext.length > 0 ? `\n\nFull Brand Profile:\n${priorContext.join('\n')}` : '';

  const systemPrompt = `You are a B2B brand messaging and experience AI. Based on the brand profile and company context, create compelling messaging, voice guidelines, and brand experience touchpoints.

The messaging should be authentic, clear, and consistent with the brand archetype and personality. The tone should reflect the brand's character.

IMPORTANT: You MUST also produce the Brand Assets creative fields — "mascots", "jingles", and "punchlines". These are REQUIRED and must never be empty. Always return concrete, brand-aligned content for all three.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "brandMessage": "string — the primary brand message, 2-3 sentences that communicate the brand's value",
  "keyMessages": ["array of 3-5 key messages the brand should consistently communicate"],
  "elevatorPitch": "string — a 30-second elevator pitch for the brand, 2-3 sentences",
  "brandVoice": "string — description of the brand voice (e.g. 'confident yet approachable, expert yet warm, data-driven yet story-focused'), 1-2 sentences",
  "toneAttributes": {
    "professional": "number 0-100 — how professional vs casual (100=very professional)",
    "friendly": "number 0-100 — how friendly vs formal (100=very friendly)",
    "authoritative": "number 0-100 — how authoritative vs collaborative (100=very authoritative)",
    "playful": "number 0-100 — how playful vs serious (100=very playful)",
    "empathetic": "number 0-100 — how empathetic vs analytical (100=very empathetic)",
    "bold": "number 0-100 — how bold vs conservative (100=very bold)"
  },
  "toneGuidelines": "string — detailed guidelines for how the brand should sound across different contexts, 2-3 sentences",
  "brandTouchpoints": ["array of 5-8 key touchpoints where customers interact with the brand, e.g. 'Website homepage', 'Sales call', 'Onboarding email'"],
  "customerExperience": "string — description of the desired customer experience across touchpoints, 2-3 sentences",
  "mascots": "string — brand mascot concepts, characters, or personalities that can represent the brand across marketing, advertising, and branding materials. List one per line, 3-5 options",
  "jingles": "string — memorable brand jingles, audio slogans, or short musical phrases aligned with the brand voice. List one per line, 3-5 options",
  "punchlines": "string — creative punchlines and alternative taglines for future marketing campaigns, product launches, and brand communications. List one per line, 5-8 options"
}`;

  const userPrompt = `Create brand messaging and experience guidelines for this brand:${contextStr}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 20000 };
}

// ============================================
// ENHANCEMENT PROMPT (for low-confidence retry)
// ============================================

export function buildBrandStrategyEnhancementPrompt(
  stageName: string,
  stageOutput: Record<string, any>,
  lowConfidenceFields: string[]
): PromptResult {
  const systemPrompt = `You are a B2B brand strategy AI performing a refinement pass on a brand analysis. The previous analysis for "${stageName}" had low confidence on certain fields. Please provide more specific, detailed, and well-reasoned analysis 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, providing more specific and detailed values for the flagged fields.`;

  return { systemPrompt, userPrompt, maxTokens: 20000 };
}
