/**
 * AI Prompt Library for Company Creation Pipeline
 *
 * Each prompt function returns a structured object with systemPrompt, userPrompt, and maxTokens.
 * Prompts are composable — each stage receives accumulated context from prior stages.
 * All prompts enforce JSON-only output with explicit schemas matching IAiAnalysisResult.
 */

// ============================================
// TYPES
// ============================================

export interface PipelineInputs {
  companyName: string;
  websiteUrl?: string;
  description?: string;
  rawText?: string;
  pdfText?: string;
  externalLinks?: string[];
  businessNotes?: string;
}

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// Partial analysis result from previous stages
export type PartialAnalysis = Record<string, any>;

// ============================================
// HELPERS
// ============================================

function buildInputContext(inputs: PipelineInputs): string {
  const parts: string[] = [];

  if (inputs.companyName) parts.push(`Company Name: ${inputs.companyName}`);
  if (inputs.websiteUrl) parts.push(`Website: ${inputs.websiteUrl}`);
  if (inputs.description) parts.push(`Description: ${inputs.description}`);
  if (inputs.rawText) parts.push(`Raw Text: ${inputs.rawText}`);
  if (inputs.pdfText) parts.push(`PDF Content: ${inputs.pdfText}`);
  if (inputs.externalLinks?.length) parts.push(`External Links: ${inputs.externalLinks.join(', ')}`);
  if (inputs.businessNotes) parts.push(`Business Notes: ${inputs.businessNotes}`);

  return parts.join('\n\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: INDUSTRY DETECTION
// ============================================

export function buildIndustryDetectionPrompt(inputs: PipelineInputs): PromptResult {
  const systemPrompt = `You are a business analysis AI specialising in industry classification and business model identification. Your task is to analyse company information and determine the most likely industry, business type, and business model.

Analyse the provided company information carefully. Be specific rather than generic — if the company could fit multiple industries, choose the primary one and list others as categories. Assign confidence scores from 0-100 reflecting how certain you are about each classification.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "industryType": "string — the primary industry classification",
  "industryConfidence": "number 0-100 — confidence in the industry classification",
  "businessModel": "string — one of: b2b, b2c, b2b2c, saas, marketplace, d2c, freemium, subscription, hybrid",
  "businessModelConfidence": "number 0-100 — confidence in the business model classification",
  "businessType": "string — description of the business type (e.g. 'Product Company', 'Service Provider', 'Platform', 'Agency')",
  "businessTypeConfidence": "number 0-100 — confidence in the business type classification",
  "categories": ["array of relevant industry category tags"],
  "serviceCategories": ["array of service categories if applicable"],
  "productCategories": ["array of product categories if applicable"]
}`;

  const userPrompt = `Analyse the following company information and detect its industry, business model, and business type:\n\n${buildInputContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 1200 };
}

// ============================================
// STAGE 2: CONTENT GENERATION
// ============================================

export function buildContentGenerationPrompt(inputs: PipelineInputs, partial: PartialAnalysis): PromptResult {
  const priorContext = partial.industryType ? `\n\nDetected Industry Context:\n- Industry: ${partial.industryType} (confidence: ${partial.industryConfidence || 'N/A'}%)\n- Business Model: ${partial.businessModel || 'Unknown'}\n- Business Type: ${partial.businessType || 'Unknown'}\n- Categories: ${partial.categories?.join(', ') || 'N/A'}` : '';

  const systemPrompt = `You are a business content strategist AI. Given company information and detected industry context, generate compelling business descriptions and tagline suggestions.

Create content that is authentic, specific, and avoids generic marketing buzzwords.

IMPORTANT: You MUST generate ALL FOUR fields. Each field serves a distinct purpose:
- businessSummary: A concise 2-3 sentence overview (for internal strategy and brief descriptions)
- description: A detailed, rich 3-5 paragraph narrative (for the company About page, covering purpose, offerings, market position, and value proposition — this must be SUBSTANTIALLY longer and more detailed than businessSummary)
- shortDescription: A punchy one-liner under 100 characters (for profile taglines and hero sections — this must be SHORTER and more concise than businessSummary)
- taglineSuggestions: Creative tagline options

Do NOT repeat the same text across fields. Each field must contain unique, purpose-appropriate content.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "businessSummary": "A clear 2-3 sentence business summary that captures what the company does, who it serves, and what makes it unique",
  "description": "A detailed 3-5 paragraph business description suitable for an About page, covering the company's purpose, offerings, and value proposition. This must be significantly longer and more detailed than businessSummary.",
  "shortDescription": "A one-line description under 100 characters suitable for a profile tagline. Must be concise and different from businessSummary.",
  "taglineSuggestions": ["5 alternative tagline options, each under 10 words, ranging from professional to creative"]
}`;

  const userPrompt = `Generate business content for the following company:${priorContext}\n\n${buildInputContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 2500 };
}

// ============================================
// STAGE 3: STRATEGIC ANALYSIS
// ============================================

export function buildStrategicAnalysisPrompt(inputs: PipelineInputs, partial: PartialAnalysis): PromptResult {
  const priorContext = [];
  if (partial.industryType) priorContext.push(`Industry: ${partial.industryType}`);
  if (partial.businessModel) priorContext.push(`Business Model: ${partial.businessModel}`);
  if (partial.businessType) priorContext.push(`Business Type: ${partial.businessType}`);
  if (partial.categories?.length) priorContext.push(`Categories: ${partial.categories.join(', ')}`);
  if (partial.businessSummary) priorContext.push(`Summary: ${partial.businessSummary}`);
  const contextStr = priorContext.length > 0 ? `\n\nPrior Analysis Context:\n${priorContext.join('\n')}` : '';

  const systemPrompt = `You are a strategic business advisor AI. Based on all accumulated company context, produce strategic business documents including vision, mission, values, and goals.

Each USP should be specific and defensible, not generic. Goals should be achievable within 1-3 years. Core values should reflect genuine business principles, not aspirational platitudes.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "businessGoals": ["3-5 specific, measurable business goals appropriate for the company's stage and industry"],
  "vision": "A forward-looking vision statement describing the company's long-term aspirations and impact",
  "mission": "A mission statement explaining why the company exists and what it does for its customers",
  "coreValues": ["4-6 core values that reflect the company's principles and culture"],
  "uspSuggestions": ["3-5 unique selling proposition options, each explaining a specific competitive advantage"]
}`;

  const userPrompt = `Generate strategic analysis for the following company:${contextStr}\n\n${buildInputContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 2000 };
}

// ============================================
// STAGE 4: MARKET & AUDIENCE
// ============================================

export function buildMarketAudiencePrompt(inputs: PipelineInputs, partial: PartialAnalysis): PromptResult {
  const priorContext = [];
  if (partial.industryType) priorContext.push(`Industry: ${partial.industryType}`);
  if (partial.businessModel) priorContext.push(`Business Model: ${partial.businessModel}`);
  if (partial.businessSummary) priorContext.push(`Summary: ${partial.businessSummary}`);
  if (partial.primaryOffering) priorContext.push(`Primary Offering: ${partial.primaryOffering}`);
  if (partial.businessGoals?.length) priorContext.push(`Goals: ${partial.businessGoals.join(', ')}`);
  const contextStr = priorContext.length > 0 ? `\n\nPrior Analysis Context:\n${priorContext.join('\n')}` : '';

  const systemPrompt = `You are a market research and audience analysis AI. Based on all accumulated company context, analyse the target market and audience.

Be specific and data-informed where possible. Target audience descriptions should include both firmographic and behavioural characteristics. Demographics should be actionable (age range, role, income level, etc.).${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "targetAudience": {
    "primary": "Detailed description of the primary target audience segment including role, company type, and needs",
    "secondary": "Description of a secondary audience segment that could also benefit",
    "demographics": "Key demographic characteristics — age range, income level, education, location, job role",
    "psychographics": "Psychographic profile including values, interests, lifestyle, attitudes, pain points"
  },
  "targetGeography": "Primary geographic market (e.g. 'North America', 'Global', 'South Asia', 'UK & Europe')",
  "positioning": "Market positioning statement explaining how the company differentiates from competitors"
}`;

  const userPrompt = `Analyse market and audience for the following company:${contextStr}\n\n${buildInputContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 1500 };
}

// ============================================
// STAGE 5: BRAND DIRECTION & OFFERINGS
// ============================================

export function buildBrandDirectionPrompt(inputs: PipelineInputs, partial: PartialAnalysis): PromptResult {
  const priorContext = [];
  if (partial.industryType) priorContext.push(`Industry: ${partial.industryType}`);
  if (partial.businessModel) priorContext.push(`Business Model: ${partial.businessModel}`);
  if (partial.businessSummary) priorContext.push(`Summary: ${partial.businessSummary}`);
  if (partial.vision) priorContext.push(`Vision: ${partial.vision}`);
  if (partial.mission) priorContext.push(`Mission: ${partial.mission}`);
  if (partial.coreValues?.length) priorContext.push(`Core Values: ${partial.coreValues.join(', ')}`);
  if (partial.positioning) priorContext.push(`Positioning: ${partial.positioning}`);
  if (partial.targetAudience?.primary) priorContext.push(`Primary Audience: ${partial.targetAudience.primary}`);
  const contextStr = priorContext.length > 0 ? `\n\nPrior Analysis Context:\n${priorContext.join('\n')}` : '';

  const systemPrompt = `You are a brand strategy and product analysis AI. Based on all accumulated company context, determine the brand direction, primary offerings, and generate downstream context seeds for future module analysis.

Brand direction should be authentic and differentiated, not generic. Personality traits should be specific descriptors (e.g. 'Authoritative yet Warm' not 'Professional'). Colour palette suggestions should include hex codes and brief rationale. The downstream context seeds (founder, ICP, competitor) will be consumed by future AI modules, so be detailed and specific.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "brandTone": "A description of the brand tone (e.g. 'Professional yet approachable', 'Bold and innovative', 'Warm and nurturing')",
  "brandKeywords": ["8-12 brand keywords capturing the brand personality essence"],
  "brandIdentityDirection": {
    "personalityTraits": ["5-8 specific personality trait descriptors for the brand"],
    "colourPaletteSuggestions": ["4-6 colour suggestions with hex codes and rationale, e.g. '#2D5BFF - Trust & Reliability'"],
    "typographyStyle": "Suggested typography style (e.g. 'Modern sans-serif for headers, clean serif for body')"
  },
  "primaryOffering": "Clear description of the main product or service offering",
  "secondaryOfferings": ["3-5 secondary or complementary offerings"],
  "pricingModelSuggestion": "Suggested pricing model: one-time, subscription, freemium, usage-based, tiered, custom-quote, commission, hybrid",
  "founderContext": {
    "likelyExpertise": ["3-5 areas of expertise likely needed from founders"],
    "suggestedResponsibilities": ["3-5 key responsibility areas for founders"]
  },
  "icpContext": {
    "firmographicIndicators": ["4-6 firmographic characteristics of ideal customers"],
    "painPoints": ["4-6 key pain points the offering addresses"],
    "buyingTriggers": ["3-5 triggers that would motivate purchase"]
  },
  "competitorContext": {
    "likelyCompetitorTypes": ["3-5 types of companies that would be direct or indirect competitors"],
    "marketPosition": "Brief description of where this company likely sits in the competitive landscape"
  }
}`;

  const userPrompt = `Generate brand direction and offerings for the following company:${contextStr}\n\n${buildInputContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 2500 };
}

// ============================================
// ENHANCEMENT PROMPT (for low-confidence retry)
// ============================================

export function buildEnhancementPrompt(
  stageName: string,
  stageOutput: Record<string, any>,
  lowConfidenceFields: string[]
): PromptResult {
  const systemPrompt = `You are a business analysis AI performing a refinement pass. 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: 2000 };
}