/**
 * AI Prompt Library for Visual Identity Pipeline
 *
 * Generates visual identity data in 3 stages using company context,
 * ICP data, and brand strategy as seed input.
 * Follows the same pattern as other module prompts.
 */

// ============================================
// TYPES
// ============================================

export interface VisualIdentityPipelineInputs {
  // "Our" company context
  companyName: string;
  companyDescription?: string;
  companyIndustry?: string;
  companyBusinessModel?: string;
  companyTargetAudience?: string;
  companyPrimaryOffering?: string;
  companyUsps?: string[];

  // ICP context
  icpName?: string;
  icpIndustry?: string;
  icpPainPoints?: string[];

  // Brand strategy context (enriches visual identity generation)
  brandArchetype?: string;
  brandPersonality?: string[];
  brandValues?: string[];
  brandVoice?: string;

  // For regenerate: existing visual identity
  existingPrimaryColor?: string;
  existingHeadingFont?: string;

  // User instructions for regeneration
  userInstructions?: string;
}

export type PartialVisualIdentityAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// HELPERS
// ============================================

function buildCompanyContext(inputs: VisualIdentityPipelineInputs): 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.icpPainPoints?.length) icpParts.push(`Pain Points: ${inputs.icpPainPoints.join(', ')}`);
    parts.push(`\nOur ICP Context:\n${icpParts.join('\n')}`);
  }

  if (inputs.brandArchetype || inputs.brandPersonality?.length) {
    const brandParts: string[] = [];
    if (inputs.brandArchetype) brandParts.push(`Brand Archetype: ${inputs.brandArchetype}`);
    if (inputs.brandPersonality?.length) brandParts.push(`Brand Personality: ${inputs.brandPersonality.join(', ')}`);
    if (inputs.brandValues?.length) brandParts.push(`Brand Values: ${inputs.brandValues.join(', ')}`);
    if (inputs.brandVoice) brandParts.push(`Brand Voice: ${inputs.brandVoice}`);
    parts.push(`\nBrand Strategy Context:\n${brandParts.join('\n')}`);
  }

  if (inputs.existingPrimaryColor) {
    parts.push(`\nRegenerating visual identity. Current primary color: ${inputs.existingPrimaryColor}`);
    if (inputs.existingHeadingFont) parts.push(`Current heading font: ${inputs.existingHeadingFont}`);
    parts.push(`Keep the general color direction. Refresh and improve all design values.`);
  }

  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: COLOR PALETTE
// ============================================

export function buildColorPalettePrompt(inputs: VisualIdentityPipelineInputs): PromptResult {
  const userInstructionsClause = inputs.userInstructions
    ? ` The user has provided specific instructions for this generation: "${inputs.userInstructions}". You MUST follow these instructions while preserving the visual identity coherence.`
    : '';

  const systemPrompt = `You are a brand design AI specializing in color theory and visual identity. Given information about our company, brand strategy, and target audience, generate a cohesive, accessible color palette.${userInstructionsClause}

The palette must work as a complete design system. Follow these rules:
- primaryColor: the main brand color, used for CTAs, headers, key UI elements
- secondaryColor: a complementary or supporting color
- accentColor: a highlight color for emphasis and badges
- backgroundColor: the main page background (typically very dark or very light)
- surfaceColor: card/panel background (slightly lighter than background)
- textColor: primary text color (must have high contrast against backgroundColor)
- textMutedColor: secondary/muted text color
- successColor, warningColor, errorColor, infoColor: semantic colors for status indicators
- All colors must be valid hex codes in #RRGGBB format
- textColor must have WCAG AA contrast ratio (≥4.5:1) against backgroundColor
- primaryColor must have WCAG AA contrast ratio against backgroundColor${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "primaryColor": "string — hex color, e.g. '#C8FF2E' or '#3B82F6'",
  "secondaryColor": "string — hex color",
  "accentColor": "string — hex color",
  "backgroundColor": "string — hex color, typically dark (#0D1117) or light (#FFFFFF)",
  "surfaceColor": "string — hex color, slightly lighter than backgroundColor",
  "textColor": "string — hex color, high contrast against backgroundColor",
  "textMutedColor": "string — hex color, softer than textColor but still readable",
  "successColor": "string — hex color, typically green, e.g. '#3FB950'",
  "warningColor": "string — hex color, typically amber/yellow, e.g. '#D29922'",
  "errorColor": "string — hex color, typically red, e.g. '#F85149'",
  "infoColor": "string — hex color, typically blue, e.g. '#58A6FF'"
}`;

  const userPrompt = `Generate a complete color palette for this brand's visual identity:\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 2000 };
}

// ============================================
// STAGE 2: TYPOGRAPHY & SPACING
// ============================================

export function buildTypographySpacingPrompt(inputs: VisualIdentityPipelineInputs, partial: PartialVisualIdentityAnalysis): PromptResult {
  const priorContext = [];
  if (partial.primaryColor) priorContext.push(`Primary Color: ${partial.primaryColor}`);
  if (partial.secondaryColor) priorContext.push(`Secondary Color: ${partial.secondaryColor}`);
  if (partial.accentColor) priorContext.push(`Accent Color: ${partial.accentColor}`);
  if (partial.backgroundColor) priorContext.push(`Background: ${partial.backgroundColor}`);
  if (partial.textColor) priorContext.push(`Text Color: ${partial.textColor}`);
  const contextStr = priorContext.length > 0 ? `\n\nColor Palette:\n${priorContext.join('\n')}` : '';

  const systemPrompt = `You are a brand design AI specializing in typography and layout systems. Given the brand's color palette and context, define the typography, spacing, and border radius system.

Typography should be professional, readable, and aligned with the brand personality. Prefer widely-available Google Fonts or system fonts. Spacing values should use CSS units (rem or px).${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "headingFont": "string — font for headings, e.g. 'Inter', 'Playfair Display', 'Montserrat'",
  "bodyFont": "string — font for body text, e.g. 'Inter', 'Roboto', 'Open Sans'",
  "accentFont": "string — decorative/accent font for special elements, e.g. 'Playfair Display', 'Fira Code'",
  "monoFont": "string — monospace font for code/data, e.g. 'JetBrains Mono', 'Fira Code', 'Source Code Pro'",
  "headingLineHeight": "string — CSS line-height for headings, e.g. '1.2'",
  "bodyLineHeight": "string — CSS line-height for body text, e.g. '1.6'",
  "headingLetterSpacing": "string — CSS letter-spacing for headings, e.g. '-0.02em'",
  "bodyLetterSpacing": "string — CSS letter-spacing for body, e.g. '0'",
  "borderRadiusSm": "string — small border radius, e.g. '0.25rem'",
  "borderRadiusMd": "string — medium border radius, e.g. '0.5rem'",
  "borderRadiusLg": "string — large border radius, e.g. '0.75rem'",
  "borderRadiusXl": "string — extra large border radius, e.g. '1rem'",
  "sectionSpacing": "string — spacing between page sections, e.g. '3rem'",
  "componentSpacing": "string — spacing between components, e.g. '1rem'",
  "elementSpacing": "string — spacing between elements, e.g. '0.5rem'"
}`;

  const userPrompt = `Define typography and spacing for this brand's visual identity:${contextStr}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 2000 };
}

// ============================================
// STAGE 3: VISUAL DIRECTION
// ============================================

export function buildVisualDirectionPrompt(inputs: VisualIdentityPipelineInputs, partial: PartialVisualIdentityAnalysis): PromptResult {
  const priorContext = [];
  if (partial.primaryColor) priorContext.push(`Primary Color: ${partial.primaryColor}`);
  if (partial.headingFont) priorContext.push(`Heading Font: ${partial.headingFont}`);
  if (partial.bodyFont) priorContext.push(`Body Font: ${partial.bodyFont}`);
  if (partial.borderRadiusMd) priorContext.push(`Border Radius: ${partial.borderRadiusMd}`);
  const contextStr = priorContext.length > 0 ? `\n\nDesign System:\n${priorContext.join('\n')}` : '';

  const systemPrompt = `You are a brand design AI specializing in visual direction and iconography. Based on the brand's design system and context, define the icon style and image style guidelines.

The icon and image styles should be cohesive with the brand's personality, colors, and typography.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "iconStyle": {
    "name": "string — descriptive name, e.g. 'Regular Outline', 'Filled Solid', 'Duotone'",
    "style": "string — one of: 'outline', 'filled', 'duotone'",
    "strokeWidth": "number — stroke width for icons, 1-3 range, e.g. 1.5 or 2",
    "defaultSize": "number — default icon size in pixels, 16-32 range, e.g. 24"
  },
  "imageStyle": {
    "name": "string — descriptive name, e.g. 'Modern Rounded', 'Clean Minimalist', 'Bold Editorial'",
    "description": "string — brief description of the image style, how photos/illustrations should look, e.g. 'Clean, well-lit product photography with rounded corners and subtle shadows. Modern, professional feel with warm color grading.'"
  }
}`;

  const userPrompt = `Define the visual direction for this brand's visual identity:${contextStr}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 1500 };
}

// ============================================
// ENHANCEMENT PROMPT (for low-confidence retry)
// ============================================

export function buildVisualIdentityEnhancementPrompt(
  stageName: string,
  stageOutput: Record<string, any>,
  lowConfidenceFields: string[]
): PromptResult {
  const systemPrompt = `You are a brand design AI performing a refinement pass on a visual identity analysis. The previous analysis for "${stageName}" had low confidence on certain fields. Please provide more specific and well-designed values 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 well-designed values for the flagged fields.`;

  return { systemPrompt, userPrompt, maxTokens: 1500 };
}