/**
 * AI Prompt Library for Guerrilla Marketing Pipeline
 *
 * Generates a complete guerrilla marketing campaign in 4 stages:
 * 1. Strategy — campaign direction, audience analysis, initial scoring
 * 2. Ideas — creative campaign ideas with scoring (20/50/100)
 * 3. Execution Plan — phased plan with tasks, timeline, budget
 * 4. Scoring — 6-dimension scoring with recommendations
 *
 * Follows the proven Social Media pipeline pattern.
 */

// ============================================
// TYPES
// ============================================

export interface GuerrillaMarketingPipelineInputs {
  /**
   * The user's own brief from the "Generate with AI" popup or the AI Chat
   * generation flow — audience, topics, tone, goals and the chosen data
   * sources. Stated as the highest-priority instruction in the prompt.
   */
  customInstructions?: string;

  companyName: string;
  companyDescription?: string;
  companyIndustry?: string;
  companyBusinessModel?: string;
  companyTargetAudience?: string;
  companyPrimaryOffering?: string;
  companyUsps?: string[];

  // Campaign specifics
  campaignCategory?: string;
  campaignGoals?: string[];
  targetAudienceType?: string;
  budgetRange?: string;
  locationType?: string;
  campaignDuration?: string;
  toneStyle?: string;

  // Data sources
  productNames?: string[];
  productDescriptions?: string[];
  icpNames?: string[];
  icpDescriptions?: string[];
  personaNames?: string[];
  personaDescriptions?: string[];
  competitorNames?: string[];
  competitorDescriptions?: string[];

  // Harmony: Cross-module brand context
  brandVoice?: string;
  brandPersonality?: string[];
  brandArchetype?: string;
  brandValues?: string | string[];
  brandPromise?: string;
  brandGuardrails?: string;
  brandForbiddenWords?: string[];
  brandVoiceDos?: string[];
  brandVoiceDonts?: string[];
  brandSymbols?: string[];
  brandSignatureExpressions?: string[];
  brandColors?: string[];
  brandFonts?: { heading?: string; body?: string };
  visualDescription?: string;
  businessMission?: string;
  businessVision?: string;
  businessCoreValues?: string;
  icpDescription?: string;
  icpPainPoints?: string[];
  personaJobTitles?: string[];
  personaPainPoints?: string[];

  // Linked data from other modules
  linkedData?: Record<string, any>;
}

export type PartialGuerrillaAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// SHARED HELPERS
// ============================================

function buildCompanyContext(inputs: GuerrillaMarketingPipelineInputs): string {
  const parts: string[] = [];
  // The user's brief goes FIRST and is marked authoritative — it is the one
  // part of the context they typed themselves, so it must win over the derived
  // company/ICP/brand material below when the two disagree.
  if (inputs.customInstructions?.trim()) {
    parts.push(
      `USER BRIEF (highest priority — follow this over the general company context below):\n${inputs.customInstructions.trim()}\n`
    );
  }


  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(`USPs: ${inputs.companyUsps.join(', ')}`);

  if (inputs.productNames?.length) parts.push(`Products: ${inputs.productNames.join(', ')}`);
  if (inputs.productDescriptions?.length) parts.push(`Product Details: ${inputs.productDescriptions.join('; ')}`);
  if (inputs.icpNames?.length) parts.push(`ICPs: ${inputs.icpNames.join(', ')}`);
  if (inputs.icpDescriptions?.length) parts.push(`ICP Details: ${inputs.icpDescriptions.join('; ')}`);
  if (inputs.personaNames?.length) parts.push(`Personas: ${inputs.personaNames.join(', ')}`);
  if (inputs.personaDescriptions?.length) parts.push(`Persona Details: ${inputs.personaDescriptions.join('; ')}`);
  if (inputs.competitorNames?.length) parts.push(`Competitors: ${inputs.competitorNames.join(', ')}`);

  if (inputs.businessMission) parts.push(`Mission: ${inputs.businessMission}`);
  if (inputs.businessVision) parts.push(`Vision: ${inputs.businessVision}`);
  if (inputs.businessCoreValues) parts.push(`Core Values: ${inputs.businessCoreValues}`);

  return parts.join('\n');
}

function buildBrandGuardrails(inputs: GuerrillaMarketingPipelineInputs): string {
  const guardrails: string[] = [];

  if (inputs.brandPersonality?.length) guardrails.push(`Brand Personality: ${inputs.brandPersonality.join(', ')}`);
  if (inputs.brandArchetype) guardrails.push(`Brand Archetype: ${inputs.brandArchetype}`);
  if (inputs.brandValues) guardrails.push(`Brand Values: ${Array.isArray(inputs.brandValues) ? inputs.brandValues.join(', ') : inputs.brandValues}`);
  if (inputs.brandPromise) guardrails.push(`Brand Promise: ${inputs.brandPromise}`);
  if (inputs.brandGuardrails) guardrails.push(`Brand Guardrails: ${inputs.brandGuardrails}`);
  if (inputs.brandForbiddenWords?.length) guardrails.push(`NEVER use these words: ${inputs.brandForbiddenWords.join(', ')}`);
  if (inputs.brandVoiceDos?.length) guardrails.push(`Voice DOs: ${inputs.brandVoiceDos.join(', ')}`);
  if (inputs.brandVoiceDonts?.length) guardrails.push(`Voice DON'Ts: ${inputs.brandVoiceDonts.join(', ')}`);
  if (inputs.brandSymbols?.length) guardrails.push(`Brand Symbols: ${inputs.brandSymbols.join(', ')}`);
  if (inputs.brandSignatureExpressions?.length) guardrails.push(`Signature Expressions: ${inputs.brandSignatureExpressions.join(', ')}`);

  return guardrails.length > 0
    ? `\n\nBRAND GUARDRAILS (MUST follow):\n${guardrails.join('\n')}`
    : '';
}

function buildCampaignContext(inputs: GuerrillaMarketingPipelineInputs): string {
  const parts: string[] = [];

  if (inputs.campaignCategory) parts.push(`Campaign Type: ${inputs.campaignCategory.replace(/-/g, ' ')}`);
  if (inputs.campaignGoals?.length) parts.push(`Goals: ${inputs.campaignGoals.join(', ')}`);
  if (inputs.targetAudienceType) parts.push(`Target Audience: ${inputs.targetAudienceType.replace(/-/g, ' ')}`);
  if (inputs.budgetRange) parts.push(`Budget: ${inputs.budgetRange}`);
  if (inputs.locationType) parts.push(`Location Scope: ${inputs.locationType.replace(/-/g, ' ')}`);
  if (inputs.campaignDuration) parts.push(`Duration: ${inputs.campaignDuration}`);
  if (inputs.toneStyle) parts.push(`Tone Style: ${inputs.toneStyle}`);

  return parts.join('\n');
}

const JSON_INSTRUCTION = `\n\nIMPORTANT: Return ONLY valid JSON. No markdown code fences, no explanatory text before or after the JSON. The response must start with { and end with }.`;

const UNIQUENESS_INSTRUCTION = `\n\nUNIQUENESS REQUIREMENT: Each item must be meaningfully different. Vary the approach, target audience angle, location type, emotional hook, and execution style. Do not repeat the same concept with minor word changes. Think creatively and generate genuinely diverse ideas.`;

// ============================================
// STAGE 1: STRATEGY
// ============================================

export function buildGuerrillaStrategyPrompt(inputs: GuerrillaMarketingPipelineInputs): PromptResult {
  const systemPrompt = `You are an expert guerrilla marketing strategist AI. You create bold, unconventional marketing strategies that generate buzz, create memorable experiences, and maximize impact within budget constraints.

Your strategies must be:
- Creative and unconventional (this is guerrilla marketing, not traditional advertising)
- Practical and executable within the stated budget
- Tailored to the specific company, audience, and goals
- Memorable and shareable (designed for organic amplification)
- Culturally sensitive and community-respectful
${inputs.toneStyle ? `- Match the tone: ${inputs.toneStyle}` : ''}
${buildBrandGuardrails(inputs)}

Return a JSON object with this exact structure:
{
  "strategy": {
    "name": "Strategy Name (creative, memorable)",
    "summary": "2-3 sentence executive summary of the campaign strategy",
    "coreConcept": "The central creative concept that ties everything together",
    "targetAnalysis": {
      "primaryAudience": "Description of primary target audience",
      "secondaryAudience": "Description of secondary audience",
      "psychographics": ["Key psychographic traits"],
      "behaviorPatterns": ["How the audience discovers and shares content"],
      "painPoints": ["Audience pain points this campaign addresses"]
    },
    "pillars": [
      {
        "name": "Pillar Name",
        "description": "What this pillar focuses on",
        "tactics": ["3-5 specific tactics"]
      }
    ],
    "toneAndVoice": {
      "primaryTone": "${inputs.toneStyle || 'bold'}",
      "personalityTraits": ["3-5 traits"],
      "doSay": ["What to say/communicate"],
      "dontSay": ["What to avoid"]
    },
    "budgetAllocation": {
      "total": "${inputs.budgetRange || 'not specified'}",
      "breakdown": [
        {"category": "Category Name", "percentage": 25, "description": "What this covers"}
      ]
    },
    "riskMitigation": ["3-5 risk mitigation strategies"],
    "successMetrics": ["5-7 measurable success indicators"]
  }
}`;

  const userPrompt = `Create a guerrilla marketing strategy for the following business:

${buildCompanyContext(inputs)}

${buildCampaignContext(inputs)}

${inputs.linkedData ? `\nAdditional Context: ${JSON.stringify(inputs.linkedData).substring(0, 2000)}` : ''}

Generate a comprehensive guerrilla marketing strategy that leverages unconventional tactics, creates buzz, and maximizes impact within the stated budget. The strategy should be bold, memorable, and actionable.${JSON_INSTRUCTION}`;

  return { systemPrompt, userPrompt, maxTokens: 4000 };
}

// ============================================
// STAGE 2: IDEAS
// ============================================

export function buildGuerrillaIdeasPrompt(
  inputs: GuerrillaMarketingPipelineInputs,
  partial: PartialGuerrillaAnalysis,
  count: number = 20,
): PromptResult {
  const strategy = partial.strategy || {};
  const strategySummary = strategy.summary || strategy.coreConcept || '';

  const systemPrompt = `You are an expert guerrilla marketing ideator AI. You generate creative, unconventional campaign ideas that are bold, memorable, and designed to generate organic buzz and engagement.

Your ideas must be:
- Genuinely creative and unconventional
- Practical within the stated budget
- Varied in approach (don't repeat the same concept)
- Culturally appropriate and community-respectful
- Designed for viral potential and organic sharing
${inputs.toneStyle ? `- Match the tone: ${inputs.toneStyle}` : ''}
${buildBrandGuardrails(inputs)}

For each idea, provide a score from 1-10 for these dimensions:
- creativity: How creative and unconventional is this idea?
- feasibility: How practical is it within the stated budget?
- impact: How much buzz/engagement will it generate?
- viralPotential: How likely is it to be shared organically?
- brandAlignment: How well does it align with the brand?
- communityValue: Does it provide genuine value to the community?

Return a JSON object with this exact structure:
{
  "ideas": [
    {
      "id": "idea-1",
      "title": "Idea Title (5-8 words, catchy)",
      "description": "2-3 sentence description of the idea",
      "concept": "The core concept in one sentence",
      "category": "${inputs.campaignCategory || 'guerrilla-marketing'}",
      "targetAudience": "Who this specifically targets",
      "estimatedReach": "Estimated reach (e.g., '5,000-10,000 people')",
      "estimatedCost": "Estimated cost range",
      "executionComplexity": "simple|moderate|complex",
      "timeToExecute": "Time needed (e.g., '2-3 weeks')",
      "location": "Where this would take place",
      "scoring": {
        "creativity": 8,
        "feasibility": 7,
        "impact": 9,
        "viralPotential": 8,
        "brandAlignment": 7,
        "communityValue": 6,
        "overallScore": 7.5
      },
      "keyElements": ["3-5 key elements of the idea"],
      "risks": ["1-2 potential risks"],
      "tags": ["3-5 relevant tags"]
    }
  ]
}

Generate exactly ${count} unique ideas.${UNIQUENESS_INSTRUCTION}${JSON_INSTRUCTION}`;

  const userPrompt = `Generate ${count} creative guerrilla marketing ideas for:

${buildCompanyContext(inputs)}

${buildCampaignContext(inputs)}

Strategy Context: ${strategySummary}

${inputs.linkedData ? `\nAdditional Context: ${JSON.stringify(inputs.linkedData).substring(0, 2000)}` : ''}

Generate ${count} diverse, creative guerrilla marketing campaign ideas. Each idea should be meaningfully different in approach, audience angle, and execution. Think outside the box!${JSON_INSTRUCTION}`;

  return { systemPrompt, userPrompt, maxTokens: count > 50 ? 12000 : 8000 };
}

// ============================================
// STAGE 3: EXECUTION PLAN
// ============================================

export function buildGuerrillaExecutionPlanPrompt(
  inputs: GuerrillaMarketingPipelineInputs,
  partial: PartialGuerrillaAnalysis,
): PromptResult {
  const strategy = partial.strategy || {};
  const ideas = partial.ideas || [];
  const ideaSummaries = ideas.slice(0, 10).map((idea: any) =>
    `"${idea.title}" (${idea.executionComplexity || 'moderate'} complexity, est. cost: ${idea.estimatedCost || 'TBD'})`
  ).join(', ');

  const systemPrompt = `You are an expert guerrilla marketing execution planner AI. You create detailed, phased execution plans that are practical, timeline-driven, and budget-aware.

Your execution plans must be:
- Practical and actionable with clear steps
- Timeline-driven with specific phases
- Budget-conscious with cost breakdowns
- Risk-aware with mitigation strategies
- Community-respectful and ethical
${buildBrandGuardrails(inputs)}

Return a JSON object with this exact structure:
{
  "executionPlan": [
    {
      "id": "phase-1",
      "phase": "Phase Name (e.g., Pre-launch, Launch, Amplification)",
      "duration": "Duration (e.g., 'Week 1-2')",
      "description": "What this phase accomplishes",
      "tasks": [
        {
          "id": "task-1-1",
          "title": "Task title",
          "description": "Detailed task description",
          "assignedRole": "Suggested role (e.g., Creative Director, Field Team)",
          "estimatedHours": 8,
          "deadline": "Relative deadline (e.g., 'Day 3')",
          "dependencies": ["task ids this depends on"],
          "status": "pending"
        }
      ],
      "milestones": ["Key milestones for this phase"],
      "budgetAllocation": {
        "amount": "Estimated amount",
        "percentage": 25,
        "items": ["What this budget covers"]
      }
    }
  ],
  "timeline": {
    "totalDuration": "${inputs.campaignDuration || '4-6 weeks'}",
    "keyDates": [
      {"date": "Relative date", "event": "Key event or milestone"}
    ]
  },
  "budgetSummary": {
    "total": "${inputs.budgetRange || 'Flexible'}",
    "breakdown": [
      {"category": "Category", "amount": "Amount or percentage", "description": "What this covers"}
    ],
    "contingencyPercentage": 10
  },
  "riskAssessment": [
    {"risk": "Risk description", "probability": "low|medium|high", "impact": "low|medium|high", "mitigation": "How to mitigate"}
  ]
}`;

  const userPrompt = `Create a detailed execution plan for these guerrilla marketing ideas:

${buildCompanyContext(inputs)}

${buildCampaignContext(inputs)}

Strategy: ${strategy.summary || strategy.coreConcept || 'Creative guerrilla marketing campaign'}

Selected Ideas: ${ideaSummaries || 'Various creative guerrilla tactics'}

Create a phased execution plan with specific tasks, timelines, and budget allocations. Make it practical and actionable.${JSON_INSTRUCTION}`;

  return { systemPrompt, userPrompt, maxTokens: 8000 };
}

// ============================================
// STAGE 4: SCORING
// ============================================

export function buildGuerrillaScoringPrompt(
  inputs: GuerrillaMarketingPipelineInputs,
  partial: PartialGuerrillaAnalysis,
): PromptResult {
  const strategy = partial.strategy || {};
  const ideas = partial.ideas || [];
  const executionPlan = partial.executionPlan || [];

  const systemPrompt = `You are an expert guerrilla marketing scoring and analytics AI. You evaluate campaigns across 6 dimensions and provide actionable recommendations.

Score each dimension from 0-100 and provide specific, actionable recommendations.

Return a JSON object with this exact structure:
{
  "scoring": {
    "creativity": {
      "score": 0-100,
      "label": "Low|Moderate|Good|Excellent|Outstanding",
      "analysis": "2-3 sentence analysis of creativity",
      "recommendations": ["2-3 specific recommendations"]
    },
    "feasibility": {
      "score": 0-100,
      "label": "Low|Moderate|Good|Excellent|Outstanding",
      "analysis": "2-3 sentence analysis of feasibility within budget",
      "recommendations": ["2-3 specific recommendations"]
    },
    "impact": {
      "score": 0-100,
      "label": "Low|Moderate|Good|Excellent|Outstanding",
      "analysis": "2-3 sentence analysis of potential impact and reach",
      "recommendations": ["2-3 specific recommendations"]
    },
    "viralPotential": {
      "score": 0-100,
      "label": "Low|Moderate|Good|Excellent|Outstanding",
      "analysis": "2-3 sentence analysis of viral sharing potential",
      "recommendations": ["2-3 specific recommendations"]
    },
    "brandAlignment": {
      "score": 0-100,
      "label": "Low|Moderate|Good|Excellent|Outstanding",
      "analysis": "2-3 sentence analysis of brand alignment",
      "recommendations": ["2-3 specific recommendations"]
    },
    "communityValue": {
      "score": 0-100,
      "label": "Low|Moderate|Good|Excellent|Outstanding",
      "analysis": "2-3 sentence analysis of community benefit",
      "recommendations": ["2-3 specific recommendations"]
    },
    "overallScore": 0-100,
    "overallLabel": "Low|Moderate|Good|Excellent|Outstanding",
    "topRecommendations": ["5 top recommendations to improve the campaign"]
  }
}`;

  const userPrompt = `Evaluate this guerrilla marketing campaign across 6 dimensions:

${buildCompanyContext(inputs)}

${buildCampaignContext(inputs)}

Strategy Summary: ${strategy.summary || strategy.coreConcept || 'N/A'}
Number of Ideas: ${ideas.length}
Execution Phases: ${Array.isArray(executionPlan) ? executionPlan.length : 0}

Provide detailed scoring with specific recommendations for improvement.${JSON_INSTRUCTION}`;

  return { systemPrompt, userPrompt, maxTokens: 3000 };
}