/**
 * AI Prompt Library for Website Planner Pipeline
 *
 * Generates website planner data in 3 stages using company context, ICP data,
 * and brand strategy as seed input. Follows the same pattern as competitor prompts.
 */

// ============================================
// TYPES
// ============================================

export interface WebsitePlannerPipelineInputs {
  // "Our" company context
  companyName: string;
  companyDescription?: string;
  companyIndustry?: string;
  companyBusinessModel?: string;
  companyTargetAudience?: string;
  companyPrimaryOffering?: string;
  companyUsps?: string[];

  // ICP context
  icpName?: string;
  icpIndustry?: string;
  icpCompanySize?: string;
  icpPainPoints?: string[];
  icpBusinessGoals?: string[];

  // Brand strategy context (enrichment)
  brandArchetype?: string;
  brandPersonality?: string[];
  brandValues?: string[];
  brandPositioning?: string;
  brandVoice?: string;
  primaryColor?: string;

  // Target platform for website generation
  targetPlatform?: string;

  // Language for content generation (ISO code or full name)
  language?: string;

  // User-provided custom instructions / prompt
  customInstructions?: string;

  // Template style context
  templateStyleId?: string;
  templateStyleName?: string;

  // For regenerate: existing planner identity
  existingPlannerName?: string;
  existingPlannerType?: string;
  existingPlannerDomain?: string;
  existingPlannerGoal?: string;
}

export type PartialWebsitePlannerAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// HELPERS
// ============================================

/**
 * Platform-specific guidance for each supported target platform.
 * Used to steer the AI toward generating content, structure, and features
 * that align with the chosen platform's capabilities and conventions.
 */
const PLATFORM_GUIDANCE: Record<string, { label: string; hints: string[] }> = {
  claude: {
    label: 'Claude',
    hints: [
      'The generated website plan will be built using Claude as the AI code assistant.',
      'Claude excels at generating well-structured, comprehensive code in single turns.',
      'Prefer clean, semantic HTML with accessible markup and well-documented CSS.',
      'Structure sections to leverage Claude\'s strength in understanding full-page context.',
      'Include detailed content requirements since Claude can produce rich, contextual copy.',
    ],
  },
  cursor: {
    label: 'Cursor',
    hints: [
      'The website will be built using Cursor IDE with AI-assisted editing.',
      'Prefer a component-based architecture (React/Next.js) since Cursor works best with modular code.',
      'Break features into small, focused components that can be generated and edited independently.',
      'Use TypeScript for better AI-assisted refactoring and type safety.',
      'Structure sections and features so Cursor\'s inline editing can modify them in isolation.',
    ],
  },
  lovable: {
    label: 'Lovable',
    hints: [
      'The website will be built using Lovable, an AI-powered web app builder.',
      'Prefer modern React with Tailwind CSS — Lovable generates React components natively.',
      'Keep the design system consistent: Lovable works best with clear design tokens and a cohesive UI style.',
      'Avoid complex backend integrations in the initial plan — focus on frontend-first features.',
      'Sections should map cleanly to React components with clear prop interfaces.',
    ],
  },
  bolt: {
    label: 'Bolt',
    hints: [
      'The website will be built using Bolt, an AI-powered full-stack web builder.',
      'Bolt generates full-stack applications — plan for both frontend and backend features.',
      'Prefer modern React with a Node.js/Express backend pattern.',
      'Include database schema suggestions for data-driven features.',
      'Plan API endpoints alongside frontend sections for a cohesive full-stack build.',
    ],
  },
  v0: {
    label: 'V0',
    hints: [
      'The website will be built using V0 by Vercel, an AI UI generator.',
      'V0 generates React components with Tailwind CSS and shadcn/ui.',
      'Focus on rich, interactive UI components — V0 excels at visual, animated interfaces.',
      'Prefer server components and Next.js App Router patterns.',
      'Each section should map to a distinct UI component with clear visual hierarchy.',
    ],
  },
  replit: {
    label: 'Replit',
    hints: [
      'The website will be built using Replit, a cloud IDE with AI code generation.',
      'Replit supports full-stack projects — plan for both frontend and backend.',
      'Prefer a simple project structure with minimal configuration overhead.',
      'Include environment variable and deployment considerations.',
      'Sections and features should be buildable incrementally in Replit\'s collaborative environment.',
    ],
  },
  framer: {
    label: 'Framer AI',
    hints: [
      'The website will be built using Framer, a design-focused website builder with AI.',
      'Prioritize visual design, animations, and micro-interactions — Framer excels at these.',
      'Plan for scroll-based animations, hover effects, and page transitions.',
      'Use a content-first approach: each section should have strong visual hierarchy and typography.',
      'Avoid complex dynamic features — focus on marketing-style websites with stunning visuals.',
    ],
  },
  webflow: {
    label: 'Webflow AI',
    hints: [
      'The website will be built using Webflow, a visual website builder with AI features.',
      'Structure the plan around Webflow\'s CMS collections for dynamic content (blogs, case studies, etc.).',
      'Prefer CSS Grid and Flexbox layouts — map sections to Webflow\'s visual layout system.',
      'Plan for Webflow Interactions (scroll animations, hover effects) instead of custom JS.',
      'Include SEO field mapping: meta titles, descriptions, and Open Graph tags per page.',
    ],
  },
};

function buildPlatformContext(platform?: string): string {
  if (!platform || !PLATFORM_GUIDANCE[platform]) return '';
  const guide = PLATFORM_GUIDANCE[platform];
  return `\nTarget Platform: ${guide.label}\n${guide.hints.map(h => `- ${h}`).join('\n')}`;
}

function buildCompanyContext(inputs: WebsitePlannerPipelineInputs): 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.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(`\nICP Context:\n${icpParts.join('\n')}`);
  }

  if (inputs.brandArchetype || inputs.brandPositioning) {
    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.brandPositioning) brandParts.push(`Brand Positioning: ${inputs.brandPositioning}`);
    if (inputs.brandVoice) brandParts.push(`Brand Voice: ${inputs.brandVoice}`);
    if (inputs.primaryColor) brandParts.push(`Primary Color: ${inputs.primaryColor}`);
    parts.push(`\nBrand Strategy:\n${brandParts.join('\n')}`);
  }

  if (inputs.existingPlannerName) {
    parts.push(`\nRegenerating website plan: ${inputs.existingPlannerName}`);
    if (inputs.existingPlannerType) parts.push(`Existing type: ${inputs.existingPlannerType}`);
    if (inputs.existingPlannerDomain) parts.push(`Existing domain: ${inputs.existingPlannerDomain}`);
    if (inputs.existingPlannerGoal) parts.push(`Existing goal: ${inputs.existingPlannerGoal}`);
    parts.push(`Keep the name and identity. Refresh and improve all other data.`);
  }

  const platformCtx = buildPlatformContext(inputs.targetPlatform);
  if (platformCtx) parts.push(platformCtx);

  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.';

/**
 * Quality floor for every free-text field. Mirrors the Landing Page pipeline —
 * without it the model falls back to interchangeable marketing filler, and the
 * generated website ends up saying nothing specific about the business.
 */
const ANTI_GENERIC_INSTRUCTION = `\n\nCRITICAL QUALITY RULES:
- Do NOT use generic placeholder text. Every headline, subheadline, bullet point, and CTA must be specific to THIS company, industry, and offering.
- Do NOT use vague phrases like "Transform Your Business", "Streamline Operations", "Take Your Business to the Next Level". These are banned.
- Headlines MUST include at least one of: a specific benefit, a measurable outcome, a number, or a direct reference to the company's industry/product.
- Bullet points MUST be benefit-driven with specific details — NOT "Easy to use", "Fast results", "Save time". Instead: "Set up in under 5 minutes with our guided wizard", "Reduce manual data entry by 80%".
- CTAs MUST use action verbs and indicate what happens next — NOT "Submit" or "Click Here". Instead: "Start Your Free 14-Day Trial", "Book a 15-Minute Strategy Call".
- All content must reflect the company's actual industry, products, and ICP. Different companies MUST produce different content.`;

// ============================================
// LANGUAGE DIRECTIVE
// ============================================

/**
 * ISO 639-1 code → full language name mapping.
 * Used to resolve short codes (e.g. 'hi') to full names for the AI prompt.
 */
const LANGUAGE_NAME_MAP: Record<string, string> = {
  en: 'English',
  hi: 'Hindi',
  mr: 'Marathi',
  es: 'Spanish',
  fr: 'French',
  de: 'German',
  pt: 'Portuguese',
  zh: 'Chinese',
  ar: 'Arabic',
  ja: 'Japanese',
  ko: 'Korean',
  ru: 'Russian',
  it: 'Italian',
  nl: 'Dutch',
  sv: 'Swedish',
  da: 'Danish',
  fi: 'Finnish',
  no: 'Norwegian',
  pl: 'Polish',
  tr: 'Turkish',
  th: 'Thai',
  vi: 'Vietnamese',
  id: 'Indonesian',
  ms: 'Malay',
  tl: 'Filipino',
  bn: 'Bengali',
  ta: 'Tamil',
  te: 'Telugu',
  kn: 'Kannada',
  ml: 'Malayalam',
  gu: 'Gujarati',
  pa: 'Punjabi',
  ur: 'Urdu',
  he: 'Hebrew',
  uk: 'Ukrainian',
  ro: 'Romanian',
  hu: 'Hungarian',
  cs: 'Czech',
  el: 'Greek',
  'hi-en': 'Hinglish',
  multi: 'Multi-Language',
};

/**
 * Build an explicit language directive for non-English content generation.
 * Returns an empty string for English (the default), so no wasted tokens.
 * Matches the Sales Scripts pattern with special Hindi/Marathi handling.
 */
export function buildLanguageDirective(language?: string): string {
  if (!language) return '';
  const lower = language.toLowerCase().trim();

  // English → no directive needed (AI defaults to English)
  if (lower === 'english' || lower === 'en') return '';

  // Hindi — explicit Devanagari instruction
  if (lower === 'hindi' || lower === 'hi') {
    return '\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content entirely in Hindi using Devanagari script (हिंदी देवनागरी लिपि). Do NOT use English anywhere. All text — including website name, headings, taglines, body copy, CTAs, button labels, navigation items, form labels, placeholder text, footer content, meta titles, meta descriptions, alt text, section names, page names, feature names, and any other generated text — MUST be written in Hindi. Every field value in the JSON response must be in Hindi. The only exception is the "url" field for pages, which should use English/URL-safe paths like /about, /services.';
  }

  // Marathi — explicit Devanagari instruction
  if (lower === 'marathi' || lower === 'mr') {
    return '\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content entirely in Marathi using Devanagari script (मराठी देवनागरी लिपि). Do NOT use English anywhere. All text — including website name, headings, taglines, body copy, CTAs, button labels, navigation items, form labels, placeholder text, footer content, meta titles, meta descriptions, alt text, section names, page names, feature names, and any other generated text — MUST be written in Marathi. Every field value in the JSON response must be in Marathi. The only exception is the "url" field for pages, which should use English/URL-safe paths like /about, /services.';
  }

  // Hinglish — mixed Hindi-English
  if (lower === 'hi-en') {
    return '\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content in Hinglish (Hindi-English mix) — a natural blend of Hindi and English commonly used in Indian business contexts. Technical terms and brand names may stay in English, but headings, descriptions, CTAs, and body copy should blend Hindi and English naturally. Every field value in the JSON response must follow this Hinglish style.';
  }

  // Multi-Language — acknowledge multilingual intent
  if (lower === 'multi' || lower === 'multi-language') {
    return '\n\nIMPORTANT LANGUAGE REQUIREMENT: This website targets a multilingual audience. Generate content primarily in English but include key CTAs, taglines, and headings with multilingual variants where appropriate. Add a note in "uiStyle" or "accessibilityNotes" about implementing a language switcher.';
  }

  // Generic fallback for any other language — resolve code to name
  const langName = LANGUAGE_NAME_MAP[lower] || language;
  return `\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content entirely in ${langName}. Do NOT use English anywhere. All text — including website name, headings, taglines, body copy, CTAs, button labels, navigation items, form labels, placeholder text, footer content, meta titles, meta descriptions, alt text, section names, page names, feature names, and any other generated text — MUST be written in ${langName}. Every field value in the JSON response must be in ${langName}. The only exception is the "url" field for pages, which should use English/URL-safe paths.`;
}

// ============================================
// STAGE 1: WEBSITE CORE & STRATEGY
// ============================================

export function buildWebsiteCorePrompt(inputs: WebsitePlannerPipelineInputs): PromptResult {
  const existingInstruction = inputs.existingPlannerName
    ? ` You MUST keep the website name as "${inputs.existingPlannerName}" and regenerate the plan around that identity.`
    : '';

  const platformInstruction = inputs.targetPlatform && PLATFORM_GUIDANCE[inputs.targetPlatform]
    ? ` The website will be built using ${PLATFORM_GUIDANCE[inputs.targetPlatform].label}. Tailor the plan to leverage this platform's strengths and conventions as described in the context below.`
    : '';

  const languageDirective = buildLanguageDirective(inputs.language);

  const systemPrompt = `You are a B2B website strategy AI. Given information about a company, their ideal customer profile, and brand identity, generate a comprehensive website plan that aligns with their business goals and target audience.${existingInstruction}${platformInstruction}${languageDirective}

The website should be strategically designed to convert visitors into customers, support the brand identity, and effectively communicate the company's value proposition. All fields should be specific and actionable.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "name": "string — the website/project name. If regenerating, keep the existing name.",
  "domain": "string — suggested domain name, e.g. 'example.com' or 'app.example.com'",
  "websiteType": "string — one of: corporate, saas, ecommerce, portfolio, marketplace, landing-page, agency, personal-brand",
  "websiteGoal": "string — primary website goal in 1-2 sentences, e.g. 'Generate qualified leads for our B2B SaaS platform through content marketing and free trial signups'",
  "primaryCTA": "string — primary call-to-action, e.g. 'Start Free Trial' or 'Book a Demo'",
  "secondaryCTA": "string — secondary call-to-action, e.g. 'Watch Demo' or 'Download Guide'",
  "targetAudience": "string — detailed target audience description, e.g. 'Mid-market B2B SaaS companies with 50-500 employees looking to streamline operations'",
  "country": "string — primary country/region, e.g. 'United States' or 'Global'",
  "language": "string — primary language, e.g. 'English' or 'Spanish'",
  "seoTargetRegion": "string — SEO target region, e.g. 'North America' or 'Europe'",
  "status": "string — one of: planning, requirements, design, development, review, live, maintenance",
  "uiStyle": "string — brief UI style direction, e.g. 'Clean, modern, professional with bold typography and generous whitespace'"
}`;

  const userPrompt = `Generate a comprehensive website plan for:\n\n${buildCompanyContext(inputs)}${inputs.customInstructions ? `\n\nUSER INSTRUCTIONS:\n${inputs.customInstructions.trim()}` : ''}`;

  // Matches the Landing Page pipeline's budget. The old 2000 could not hold a
  // full core-strategy object, so the reply was cut mid-JSON and the parser fell
  // back to a regex scrape that only recovers flat strings.
  return { systemPrompt, userPrompt, maxTokens: 20000 };
}

// ============================================
// STAGE 2: SECTIONS & PAGES
// ============================================

export function buildStructurePrompt(inputs: WebsitePlannerPipelineInputs, partial: PartialWebsitePlannerAnalysis): PromptResult {
  const priorContext = [];
  if (partial.name) priorContext.push(`Website Name: ${partial.name}`);
  if (partial.websiteType) priorContext.push(`Type: ${partial.websiteType}`);
  if (partial.websiteGoal) priorContext.push(`Goal: ${partial.websiteGoal}`);
  if (partial.primaryCTA) priorContext.push(`Primary CTA: ${partial.primaryCTA}`);
  if (partial.secondaryCTA) priorContext.push(`Secondary CTA: ${partial.secondaryCTA}`);
  if (partial.targetAudience) priorContext.push(`Target Audience: ${partial.targetAudience}`);
  if (partial.uiStyle) priorContext.push(`UI Style: ${partial.uiStyle}`);
  const contextStr = priorContext.length > 0 ? `\n\nWebsite Core:\n${priorContext.join('\n')}` : '';

  const platformHint = inputs.targetPlatform && PLATFORM_GUIDANCE[inputs.targetPlatform]
    ? ` The website will be built on ${PLATFORM_GUIDANCE[inputs.targetPlatform].label} — structure sections and pages to leverage this platform's strengths.`
    : '';

  const languageDirective = buildLanguageDirective(inputs.language);

  const systemPrompt = `You are a B2B website architecture AI. Based on the website core strategy, generate the sections and pages structure that will best achieve the website's goals.${platformHint}${languageDirective}

Each section should have a clear purpose aligned with the conversion funnel. Sections should cover the essential parts of a ${partial.websiteType || 'corporate'} website. Generate 8-15 sections that are relevant and specific to this business.

CRITICAL: Write the ACTUAL COPY for every section, not just a brief for it. Each section must arrive complete — headline, subheadline, description, CTA, bullet points and trust statements — so the site can be built straight from this plan without a second pass. A section that carries only a purpose and a content requirement is incomplete.
- Each section MUST have a different headline. No two sections may share the same or substantially similar headline.
- Write copy the visitor will read, in the finished tone — never instructions to a writer.

Each page should serve a distinct purpose in the user journey. Generate 4-8 pages.${JSON_INSTRUCTION}${ANTI_GENERIC_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "sections": [
    {
      "name": "string — section name, e.g. 'Hero Section', 'About Us', 'Services'",
      "enabled": "boolean — whether this section should be visible by default",
      "order": "number — display order starting from 0",
      "purpose": "string — what this section should achieve, e.g. 'Capture attention and communicate the value proposition within 5 seconds'",
      "contentRequirement": "string — what content should go here, e.g. 'Headline, subheadline, primary CTA button, and hero image'",
      "headline": "string — the ACTUAL section headline with a specific benefit or curiosity hook. Ready to publish.",
      "subheadline": "string — the ACTUAL supporting subheadline that elaborates with concrete details",
      "description": "string — the ACTUAL body copy for this section (2-4 persuasive, specific sentences)",
      "bulletPoints": ["array of 3-6 bullet points. Each benefit-driven with specific details — e.g. 'Automated follow-up sequences — nurture leads 24/7 without manual effort'"],
      "trustStatements": ["array of 2-4 trust/credibility statements using specific numbers, names or outcomes — e.g. 'Trusted by 2,000+ SaaS companies'"],
      "uiNotes": "string — UI/UX guidance, e.g. 'Full-width hero with gradient overlay, centered text, CTA below'",
      "conversionNotes": "string — specific conversion guidance for this section, e.g. 'Repeat the primary CTA after the third bullet; keep the form to 3 fields'",
      "cta": "string — call-to-action for this section, e.g. 'Start Free Trial'",
      "seoNotes": "string — SEO guidance, e.g. 'Include primary keyword in H1, use structured data for organization'",
      "priority": "string — one of: critical, high, medium, low"
    }
  ],
  "pages": [
    {
      "name": "string — page name, e.g. 'Home', 'About', 'Services'",
      "url": "string — URL path, e.g. '/', '/about', '/services'",
      "pageType": "string — one of: main, landing, dynamic, legal, seo",
      "goal": "string — page goal, e.g. 'Convert visitors to sign up for free trial'",
      "metaTitle": "string — SEO meta title, e.g. 'Company Name | B2B SaaS Solution'",
      "metaDescription": "string — SEO meta description, e.g. 'Discover how Company Name helps businesses streamline operations...'",
      "keywords": ["array of 3-5 SEO keywords for this page"],
      "conversionGoal": "string — what constitutes a conversion, e.g. 'Free trial signup' or 'Contact form submission'"
    }
  ]
}`;

  const userPrompt = `Design the sections and pages structure for this website:${contextStr}\n\n${buildCompanyContext(inputs)}`;

  // 8-15 sections with full copy plus 4-8 pages with meta cannot fit in 3000
  // output tokens — that truncation is why sections arrived empty or missing.
  // Matches the Landing Page sections stage.
  return { systemPrompt, userPrompt, maxTokens: 30000 };
}

// ============================================
// STAGE 3: FEATURES & SEO
// ============================================

export function buildFeaturesSeoPrompt(inputs: WebsitePlannerPipelineInputs, partial: PartialWebsitePlannerAnalysis): PromptResult {
  const priorContext = [];
  if (partial.name) priorContext.push(`Website: ${partial.name}`);
  if (partial.websiteType) priorContext.push(`Type: ${partial.websiteType}`);
  if (partial.websiteGoal) priorContext.push(`Goal: ${partial.websiteGoal}`);
  if (partial.targetAudience) priorContext.push(`Audience: ${partial.targetAudience}`);
  if (partial.primaryCTA) priorContext.push(`CTA: ${partial.primaryCTA}`);
  const sectionNames = Array.isArray(partial.sections) ? partial.sections.map((s: any) => s.name).join(', ') : '';
  if (sectionNames) priorContext.push(`Sections: ${sectionNames}`);
  const contextStr = priorContext.length > 0 ? `\n\nWebsite Plan:\n${priorContext.join('\n')}` : '';

  const platformHint = inputs.targetPlatform && PLATFORM_GUIDANCE[inputs.targetPlatform]
    ? ` The website will be built on ${PLATFORM_GUIDANCE[inputs.targetPlatform].label} — choose features and design guidelines that align with this platform's capabilities and conventions.`
    : '';

  const languageDirective = buildLanguageDirective(inputs.language);

  const systemPrompt = `You are a B2B website features and SEO AI. Based on the website strategy and structure, generate the features the website should have and the SEO strategy to maximize organic traffic.${platformHint}${languageDirective}

Generate 8-16 features that are relevant for a ${partial.websiteType || 'corporate'} website. Prioritize features that directly support the website's conversion goals.

CRITICAL: Each feature MUST have a specific, descriptive name that reflects what the feature actually is (e.g. "User Authentication", "Contact Form", "Live Chat", "Portfolio Gallery", "Testimonials Section", "Newsletter Signup", "Social Media Integration"). Do NOT use generic placeholder names like "Feature 1", "Feature 2", "Feature 3", etc. Every feature name must be meaningful and self-explanatory.

For SEO, generate 5-8 target keywords and 2-4 content clusters that align with the company's offerings and search intent.

Also generate 6-10 FAQs — the real questions this company's buyers ask before converting, each with a direct answer. These populate the website's FAQ section and its FAQ schema markup, so they must be specific to this business, not generic web-hosting questions.${JSON_INSTRUCTION}${ANTI_GENERIC_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "features": [
    {
      "name": "string — specific feature name, e.g. 'User Authentication', 'Contact Form', 'Live Chat', 'Portfolio Gallery'",
      "enabled": "boolean — whether this feature should be enabled by default",
      "priority": "string — one of: critical, high, medium, low",
      "notes": "string — brief description and implementation notes, e.g. 'OAuth2 + email/password login with MFA support'",
      "complexity": "string — one of: simple, medium, complex, enterprise",
      "estimatedTimeline": "string — estimated implementation time, e.g. '2-3 weeks' or '1 week'"
    }
  ],
  "targetKeywords": ["array of 5-8 primary SEO keywords the website should target"],
  "seoClusters": [
    {
      "topic": "string — cluster topic, e.g. 'Project Management Best Practices'",
      "pillarPage": "string — pillar page title, e.g. 'Complete Guide to Project Management'",
      "clusterPages": ["array of 2-4 supporting page titles"],
      "keywords": ["array of 3-5 keywords for this cluster"],
      "contentGap": "string — brief description of the content gap this cluster fills"
    }
  ],
  "faqs": [
    {
      "question": "string — a real question this company's buyers ask before converting",
      "answer": "string — a direct, specific 2-4 sentence answer. No hedging, no marketing filler.",
      "category": "string — short grouping label, e.g. 'Pricing', 'Onboarding', 'Security'",
      "seoImportance": "string — one of: critical, high, medium, low"
    }
  ],
  "designReferences": ["array of 2-4 design reference URLs or descriptions, e.g. 'Stripe.com — clean checkout flow'"],
  "animationNotes": "string — animation and interaction guidelines, e.g. 'Subtle fade-in animations on scroll, smooth page transitions'",
  "responsiveNotes": "string — responsive design notes, e.g. 'Mobile-first approach, breakpoints at 640px, 768px, 1024px, 1280px'",
  "accessibilityNotes": "string — accessibility requirements, e.g. 'WCAG 2.1 AA compliance, all images need alt text, keyboard navigation support'"
}`;

  const userPrompt = `Generate features, SEO strategy, and design guidelines for this website:${contextStr}\n\n${buildCompanyContext(inputs)}`;

  // Matches the Landing Page SEO stage.
  return { systemPrompt, userPrompt, maxTokens: 25000 };
}

// ============================================
// ENHANCEMENT PROMPT (for low-confidence retry)
// ============================================

export function buildWebsitePlannerEnhancementPrompt(
  stageName: string,
  stageOutput: Record<string, any>,
  lowConfidenceFields: string[]
): PromptResult {
  const systemPrompt = `You are a B2B website strategy AI performing a refinement pass on a website plan. 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.`;

  // Matches the Landing Page enhancement pass.
  return { systemPrompt, userPrompt, maxTokens: 15000 };
}