/**
 * AI Prompt Library for Book Pipeline
 *
 * Generates book content data in 3 stages using company context, ICP data,
 * product info, brand strategy, and founder details. Generates a single
 * complete book concept with chapters.
 */

// ============================================
// TYPES
// ============================================

export interface BookPipelineInputs {
  companyName: string;
  companyDescription?: string;
  companyIndustry?: string;
  companyBusinessModel?: string;
  companyTargetAudience?: string;
  companyPrimaryOffering?: string;
  companyUsps?: string[];

  icpName?: string;
  icpIndustry?: string;
  icpCompanySize?: string;
  icpPainPoints?: string[];
  icpBusinessGoals?: string[];

  brandArchetype?: string;
  brandPersonality?: string[];
  brandValues?: string[];
  brandPositioning?: string;
  brandVoice?: string;

  productNames?: string[];
  productDescriptions?: string[];

  // Founder details
  founderName?: string;
  founderBio?: string;
  founderExpertise?: string[];

  // Custom user instructions for AI generation
  customInstructions?: string;

  // Language for generated content
  language?: string; // 'English', 'Hindi', 'Marathi' - default is 'English'

  targetCount: number;
}

export type PartialBookAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// HELPERS
// ============================================

function buildCompanyContext(inputs: BookPipelineInputs): 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.customInstructions) parts.push(`\nUser Instructions: ${inputs.customInstructions}`);

  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}`);
    parts.push(`\nBrand Strategy:\n${brandParts.join('\n')}`);
  }

  if (inputs.productNames?.length) {
    const productParts: string[] = [];
    inputs.productNames.forEach((name, i) => {
      const desc = inputs.productDescriptions?.[i];
      productParts.push(desc ? `${name}: ${desc}` : name);
    });
    parts.push(`\nProducts:\n${productParts.join('\n')}`);
  }

  if (inputs.founderName) {
    const founderParts: string[] = [];
    founderParts.push(`Name: ${inputs.founderName}`);
    if (inputs.founderBio) founderParts.push(`Bio: ${inputs.founderBio}`);
    if (inputs.founderExpertise?.length) founderParts.push(`Expertise: ${inputs.founderExpertise.join(', ')}`);
    parts.push(`\nFounder:\n${founderParts.join('\n')}`);
  }

  return parts.join('\n');
}

const JSON_INSTRUCTION = '\n\nCRITICAL OUTPUT FORMAT RULES:\n1. Respond with ONLY a single valid JSON object.\n2. Do NOT wrap in markdown code fences (no ```json``` or ``` blocks).\n3. Do NOT include any text, explanation, or commentary before or after the JSON.\n4. Ensure all strings are properly escaped. Ensure all arrays and objects are properly closed.\n5. If the response is too long, reduce detail per item rather than producing broken JSON.';

function buildLanguageInstruction(language?: string): string {
  if (!language || language.toLowerCase() === 'english') {
    return '';
  }
  const langLower = language.toLowerCase();
  if (langLower === 'hindi') {
    return '\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content (titles, subtitles, descriptions, executive summaries, chapter titles, chapter descriptions, learning objectives, key takeaways, outlines, marketing notes, launch strategies, SEO metadata, and any other text) entirely in Hindi using Devanagari script (हिंदी देवनागरी लिपि). Do NOT use English anywhere except for JSON field names. All text values must be natural, fluent Hindi appropriate for B2B book contexts in India.';
  }
  if (langLower === 'marathi') {
    return '\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content (titles, subtitles, descriptions, executive summaries, chapter titles, chapter descriptions, learning objectives, key takeaways, outlines, marketing notes, launch strategies, SEO metadata, and any other text) entirely in Marathi using Devanagari script (मराठी देवनागरी लिपि). Do NOT use English anywhere except for JSON field names. All text values must be natural, fluent Marathi appropriate for B2B book contexts in Maharashtra, India.';
  }
  return `\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content in ${language}. All text values (titles, descriptions, chapters, strategies, etc.) must be in the specified language. Only JSON field names should remain in English.`;
}

// ============================================
// STAGE 1: BOOK IDENTITY & CONCEPT
// ============================================

export function buildBookIdentityPrompt(inputs: BookPipelineInputs): PromptResult {
  const languageInstruction = buildLanguageInstruction(inputs.language);
  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B book strategist AI. Generate a complete book concept for the given company. The book should establish thought leadership, address the target audience's pain points, and align with the company's brand and expertise.

The book must be practical, authoritative, and directly tied to the company's domain.${languageInstruction}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "title": "string — compelling book title, e.g. 'The Definitive Guide to Cloud Communications'",
  "subtitle": "string — descriptive subtitle that clarifies the value proposition",
  "slug": "string — URL-friendly slug, e.g. 'definitive-guide-cloud-communications'",
  "description": "string — 2-3 sentence book description covering what the reader will learn",
  "longDescription": "string — 4-6 sentence expanded description with more detail on scope and takeaways",
  "executiveSummary": "string — 3-4 sentence executive summary highlighting the book's unique angle",
  "type": "string — one of: book, ebook, whitepaper, guide, manual, handbook, textbook, reference, workbook, case-study-collection, research-report, manifesto",
  "targetAudience": "string — specific audience description, e.g. 'SaaS founders and product leaders at growth-stage companies'",
  "keywords": ["array of 8-12 relevant keywords and phrases"],
  "tags": ["array of 5-8 tags"],
  "language": "string — full language name, e.g. 'English', 'Hindi', 'Marathi'",
  "estimatedReadTime": "number — estimated reading time in minutes, e.g. 300 (for 5 hours)",
  "suggestedTopic": "string — a concise topic phrase that captures the book's core theme",
  "authorRole": "string — one of: author, co-author, contributor, editor"
}`;

  const userPrompt = `Generate a book concept for:\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 40000 };
}

// ============================================
// STAGE 2: BOOK STRUCTURE & CHAPTERS
// ============================================

export function buildBookStructurePrompt(inputs: BookPipelineInputs, partial: PartialBookAnalysis): PromptResult {
  const languageInstruction = buildLanguageInstruction(inputs.language);
  const identitySummary = [
    partial.title ? `Title: ${partial.title}` : '',
    partial.subtitle ? `Subtitle: ${partial.subtitle}` : '',
    partial.type ? `Type: ${partial.type}` : '',
    partial.targetAudience ? `Audience: ${partial.targetAudience}` : '',
    partial.suggestedTopic ? `Topic: ${partial.suggestedTopic}` : '',
  ].filter(Boolean).join('\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B book architect AI. For the given book concept, generate a complete chapter structure with 5-8 chapters.

Keep each field concise — shorter valid JSON is better than longer broken JSON.${languageInstruction}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "title": "string — same title from stage 1",
  "outline": "string — 3-5 sentence overview of the book's narrative arc and logical flow",
  "chapters": [
    {
      "title": "string — chapter title, e.g. 'Understanding the Modern Communication Landscape'",
      "description": "string — 2-3 sentence chapter description",
      "learningObjectives": ["array of 2-3 learning objectives"],
      "keyTakeaways": ["array of 2-3 key takeaways"],
      "estimatedWordCount": "number — estimated word count for this chapter, e.g. 3000",
      "order": "number — display order starting from 0"
    }
  ]
}

Generate 5-8 chapters. Each chapter should build logically on the previous one.`;

  const userPrompt = `Generate chapter structure for this book:\n\n${identitySummary}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 50000 };
}

// ============================================
// STAGE 3: BOOK STRATEGY & METADATA
// ============================================

export function buildBookStrategyPrompt(inputs: BookPipelineInputs, partial: PartialBookAnalysis): PromptResult {
  const languageInstruction = buildLanguageInstruction(inputs.language);
  const identitySummary = [
    partial.title ? `${partial.title}` : '',
    partial.subtitle ? `— ${partial.subtitle}` : '',
    partial.type ? `Type: ${partial.type}` : '',
    partial.targetAudience ? `For: ${partial.targetAudience}` : '',
  ].filter(Boolean).join(' ');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B publishing strategist AI. For the given book, generate launch strategy, pricing, distribution, SEO, and marketing guidance.${languageInstruction}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "seoTitle": "string — SEO-optimized title, 50-60 characters",
  "seoDescription": "string — SEO meta description, 150-160 characters",
  "seoKeywords": ["array of 5-8 SEO keywords"],
  "priceEbook": "number — suggested ebook price in USD, e.g. 29.99",
  "pricePrint": "number — suggested print price in USD, e.g. 39.99",
  "currency": "string — e.g. 'USD'",
  "formats": ["array of 2-3 formats from: pdf, epub, mobi, hardcover, paperback, audiobook"],
  "distributionLinks": ["array of 3-5 distribution channels, each must be one of: amazon, apple-books, google-books, kobo, barnes-noble, smashwords, gumroad, website, linkedin, medium, substack, researchgate, ssrn, other"],
  "launchStrategy": "string — 3-4 sentence launch strategy recommendation",
  "marketingNotes": "string — 2-3 sentence marketing guidance tied to the company's brand",
  "bestPractices": ["array of 3-5 best practices for promoting this type of book"],
  "effectivenessTips": ["array of 2-3 tips for maximizing the book's impact on the business"]
}`;

  const userPrompt = `Generate publishing strategy for this book:\n\n${identitySummary}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 30000 };
}

// ============================================
// ENHANCEMENT PROMPT
// ============================================

export function buildBookEnhancementPrompt(
  stageName: string,
  stageOutput: Record<string, any>,
  lowConfidenceFields: string[]
): PromptResult {
  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B book strategist AI performing a refinement pass. The previous analysis for "${stageName}" had low confidence on certain fields. Provide more specific, detailed content 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.`;

  return { systemPrompt, userPrompt, maxTokens: 20000 };
}

// ============================================
// TRANSLATION PROMPT
// ============================================

export function buildTranslateContentPrompt(
  fields: Record<string, string>,
  targetLanguage: string
): { systemPrompt: string; userPrompt: string; maxTokens: number } {
  // Always include an explicit language instruction for translation, even for English
  let languageInstruction: string;
  const langLower = targetLanguage.toLowerCase();
  if (langLower === 'hindi') {
    languageInstruction = '\n\nIMPORTANT LANGUAGE REQUIREMENT: Translate ALL text values into Hindi using Devanagari script (हिंदी देवनागरी लिपि). Do NOT use English anywhere except for JSON field names. All translated text values must be natural, fluent Hindi appropriate for B2B book contexts in India.';
  } else if (langLower === 'marathi') {
    languageInstruction = '\n\nIMPORTANT LANGUAGE REQUIREMENT: Translate ALL text values into Marathi using Devanagari script (मराठी देवनागरी लिपि). Do NOT use English anywhere except for JSON field names. All translated text values must be natural, fluent Marathi appropriate for B2B book contexts in Maharashtra, India.';
  } else if (langLower === 'english') {
    languageInstruction = '\n\nIMPORTANT LANGUAGE REQUIREMENT: Translate ALL text values into natural, fluent English. If the source text is in a non-English language (e.g., Hindi, Marathi), translate it to professional B2B English. Do NOT use any non-English script in the translated values.';
  } else {
    languageInstruction = `\n\nIMPORTANT LANGUAGE REQUIREMENT: Translate ALL text values into ${targetLanguage}. Only JSON field names should remain in English.`;
  }

  const systemPrompt = `You are a professional translator specializing in B2B business and technical content. Translate all provided text fields into the specified target language. Preserve the original meaning, tone, formatting, and structure exactly. Do NOT add, remove, or rewrite any content — only translate. Do NOT translate JSON field names — only translate the values.${languageInstruction}${JSON_INSTRUCTION}`;

  const fieldEntries = Object.entries(fields)
    .filter(([, value]) => value && typeof value === 'string' && value.trim())
    .map(([key, value]) => `**${key}:** ${value}`)
    .join('\n');

  const fieldNames = Object.keys(fields).filter(k => fields[k] && typeof fields[k] === 'string' && fields[k].trim());

  const userPrompt = `Translate the following book content fields to ${targetLanguage}. Keep the same meaning and structure — only change the language.\n\n${fieldEntries}\n\nReturn a JSON object with these exact keys and their translated values:\n{ "${fieldNames.join('", "')}" }`;

  return { systemPrompt, userPrompt, maxTokens: 16000 };
}
