/**
 * AI Prompt Library for PR Content Engine
 *
 * Generates expert columns, press releases, bios, and media kits
 * using company context as seed data.
 */

// ============================================
// TYPES
// ============================================

export interface PRContentInputs {
  companyName: string;
  companyDescription?: string;
  companyIndustry?: string;
  companyBusinessModel?: string;
  companyTargetAudience?: string;
  companyPrimaryOffering?: string;
  companyUsps?: string[];
  companyWebsite?: string;

  founderName?: string;
  founderTitle?: string;
  founderBio?: string;
  founderAchievements?: string[];

  icpName?: string;
  icpIndustry?: string;
  icpPainPoints?: string[];

  brandArchetype?: string;
  brandPersonality?: string[];
  brandVoice?: string;

  productNames?: string[];
  productDescriptions?: string[];

  // Expert column specific
  format?: 'article' | 'qa' | 'thought-leadership' | 'industry-insights';
  /** Primary tone. Kept as a single value for backwards compatibility. */
  tone?: string;
  /** Every predefined tone the user selected (superset of `tone`). */
  tones?: string[];
  /** Free-text tone supplied via the "Custom" tone option. */
  customTone?: string;
  wordCount?: number;
  weekNumber?: number;
  topic?: string;
  numberOfWeeks?: number;
  contentStrategy?: string; // Overall content strategy for the column series

  // Uniqueness seed for generating different content each time
  uniquenessSeed?: string;

  // Press release specific
  title?: string;
  eventType?: string;
  keyAnnouncement?: string;
  customNotes?: string;

  // Bio specific
  bioType?: string;
  personName?: string;

  // Thought leadership specific
  contentType?: string;

  // Wikipedia specific
  wikiArticleTopic?: string;
  wikiSectionNames?: string[];
  wikiExistingContent?: string;

  // Wikipedia notability
  competitorContext?: string;

  // Wikipedia citations
  claims?: string[];
  articleContent?: string;

  // Knowledge Panel specific
  kpPanelType?: string;
  kpCurrentData?: string;
  kpDesiredFields?: string[];

  // Language for content generation
  language?: string; // ISO code or name, e.g. 'en', 'hi', 'mr', 'English', 'Hindi', 'Marathi'
}

// ============================================
// LANGUAGE INSTRUCTION HELPER
// ============================================

/**
 * Builds a language instruction string to append to AI prompts.
 * Matches the pattern used in salesScriptPrompts.ts.
 * For English (or missing), returns empty string (default behaviour).
 */
export function buildLanguageInstruction(language?: string): string {
  if (!language || language.toLowerCase() === 'english' || language === 'en') return '';
  const lower = language.toLowerCase();
  if (lower === 'hindi' || lower === 'hi') {
    return '\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content (title, headline, subheadline, key announcement, introduction, main content, conclusion, body, quotes, background, boilerplate, call-to-action, and any other text) entirely in Hindi using Devanagari script (हिंदी देवनागरी लिपि). Do NOT use English anywhere. All text must be natural, fluent Hindi appropriate for professional B2B contexts in India.';
  }
  if (lower === 'marathi' || lower === 'mr') {
    return '\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content (title, headline, subheadline, key announcement, introduction, main content, conclusion, body, quotes, background, boilerplate, call-to-action, and any other text) entirely in Marathi using Devanagari script (मराठी देवनागरी लिपि). Do NOT use English anywhere. All text must be natural, fluent Marathi appropriate for professional B2B contexts in Maharashtra, India.';
  }
  // Generic language instruction for other languages
  const languageNames: Record<string, string> = {
    es: 'Spanish', fr: 'French', de: 'German', pt: 'Portuguese', it: 'Italian',
    nl: 'Dutch', ru: 'Russian', ja: 'Japanese', ko: 'Korean', zh: 'Chinese (Mandarin)',
    ar: 'Arabic', tr: 'Turkish', pl: 'Polish', sv: 'Swedish', no: 'Norwegian',
    da: 'Danish', fi: 'Finnish', cs: 'Czech', el: 'Greek', he: 'Hebrew',
    th: 'Thai', vi: 'Vietnamese', id: 'Indonesian', ms: 'Malay', fil: 'Filipino',
    bn: 'Bengali', ur: 'Urdu', ta: 'Tamil', te: 'Telugu', kn: 'Kannada',
    ml: 'Malayalam', pa: 'Punjabi', gu: 'Gujarati', sw: 'Swahili', am: 'Amharic',
  };
  const langName = languageNames[language] || languageNames[lower] || language;
  return `\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content entirely in ${langName}. All text (title, headline, body, quotes, and any other content) must be in the specified language. Do NOT mix languages.`;
}

export type PartialPRAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// HELPERS
// ============================================

function buildCompanyContext(inputs: PRContentInputs): 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.companyWebsite) parts.push(`Website: ${inputs.companyWebsite}`);

  if (inputs.founderName) {
    const founderParts: string[] = [];
    founderParts.push(`Founder/Leader: ${inputs.founderName}`);
    if (inputs.founderTitle) founderParts.push(`Title: ${inputs.founderTitle}`);
    if (inputs.founderBio) founderParts.push(`Background: ${inputs.founderBio}`);
    if (inputs.founderAchievements?.length) founderParts.push(`Achievements: ${inputs.founderAchievements.join(', ')}`);
    parts.push(`\nFounder/Leader Context:\n${founderParts.join('\n')}`);
  }

  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(`\nICP Context:\n${icpParts.join('\n')}`);
  }

  if (inputs.brandArchetype || inputs.brandVoice) {
    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.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.competitorContext) {
    parts.push(`\nCompetitor Context:\n${inputs.competitorContext}`);
  }

  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.';

// ============================================
// TONE
// ============================================

const TONE_LABELS: Record<string, string> = {
  professional: 'Professional',
  educational: 'Educational',
  authoritative: 'Authoritative',
  conversational: 'Conversational',
  inspiring: 'Inspiring',
};

function toTitleCase(value: string): string {
  return value.replace(/[-_]/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
}

/**
 * Human-readable description of the requested tone(s).
 *
 * Content can be generated with several tones at once plus an optional
 * free-text "custom" tone. `tones`/`customTone` are optional, so a request that
 * only sends the legacy single `tone` produces exactly the string it always
 * did — existing callers are unaffected.
 *
 * e.g. "Professional, Persuasive, and Luxury Brand Voice"
 */
/** The individual tone labels a request asks for, in display order. */
function toneParts(inputs: PRContentInputs, fallback: string): string[] {
  const custom = (inputs.customTone || '').trim();
  // An explicitly empty `tones` with a custom tone means "custom only" — do not
  // fold the default tone back in, or the request reads "Professional and X"
  // when the user asked for X alone.
  const selected = inputs.tones?.length
    ? inputs.tones
    : (Array.isArray(inputs.tones) && custom ? [] : [inputs.tone || fallback]);

  const predefined = selected
    .filter((t): t is string => typeof t === 'string' && !!t.trim())
    .map((t) => TONE_LABELS[t] || toTitleCase(t));

  const parts = custom ? [...predefined, custom] : predefined;
  return parts.length ? parts : [TONE_LABELS[fallback] || toTitleCase(fallback)];
}

export function buildToneDescription(inputs: PRContentInputs, fallback = 'professional'): string {
  const parts = toneParts(inputs, fallback);
  if (parts.length === 1) return parts[0];
  if (parts.length === 2) return `${parts[0]} and ${parts[1]}`;
  return `${parts.slice(0, -1).join(', ')}, and ${parts[parts.length - 1]}`;
}

/** Instruction block telling the model how to apply several tones at once. */
export function buildToneInstruction(inputs: PRContentInputs, fallback = 'professional'): string {
  const description = buildToneDescription(inputs, fallback);
  // Count the parts rather than sniffing for " and " — a custom tone can
  // legitimately contain the word ("Bold and Playful").
  return toneParts(inputs, fallback).length > 1
    ? `Tone: ${description} — blend these tones consistently throughout, rather than alternating between them.`
    : `Tone: ${description}`;
}

// ============================================
// EXPERT COLUMN PLAN GENERATOR
// ============================================

export function buildExpertColumnPlanPrompt(inputs: PRContentInputs): PromptResult {
  const formatLabel: Record<string, string> = {
    'article': 'Article',
    'qa': 'Question & Answer',
    'thought-leadership': 'Thought Leadership',
    'industry-insights': 'Industry Insights',
  };
  const toneLabel: Record<string, string> = {
    'professional': 'Professional',
    'educational': 'Educational',
    'authoritative': 'Authoritative',
    'conversational': 'Conversational',
  };

  const format = inputs.format || 'article';
  const primaryTone = inputs.tone || 'professional';
  const tone = buildToneDescription(inputs);
  const numberOfWeeks = (inputs as any).numberOfWeeks || 52;
  const uniquenessSeed = inputs.uniquenessSeed || `session-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;

  // Generate random angle suggestions for uniqueness
  const angles = [
    'industry trends and future predictions',
    'practical how-to guides and tutorials',
    'case studies and success stories',
    'thought leadership and expert opinions',
    'behind-the-scenes and company culture',
    'customer stories and testimonials',
    'product deep-dives and innovations',
    'market analysis and competitive insights',
    'leadership and management insights',
    'technology and innovation updates',
    'sustainability and social impact',
    'industry challenges and solutions',
    'team expertise and specialised knowledge',
    'partnerships and collaboration stories',
    'research and data-driven insights'
  ];

  // Pick 3-5 random angles based on the uniqueness seed
  const seedNum = uniquenessSeed.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
  const selectedAngles = angles.sort(() => 0.5 - Math.sin(seedNum) * 0.5).slice(0, 4 + (seedNum % 2));

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a PR content strategist AI. Generate a ${numberOfWeeks}-week expert column content plan for the given company. The plan should position the founder/business as an industry authority through consistent, high-value content.

**CRITICAL UNIQUENESS REQUIREMENT:**
This is generation session "${uniquenessSeed}". You MUST create a COMPLETELY UNIQUE set of topics that would NOT be generated by any other session.
- DO NOT use generic topics that could appear in any content calendar
- Each topic must be specific to THIS company's context and unique value proposition
- Vary the angle, depth, and perspective across weeks
- Use these suggested unique angles as inspiration (but create ORIGINAL topics): ${selectedAngles.join(', ')}
- Current timestamp context: ${new Date().toISOString()}
- Randomness factor: ${Math.random().toString(36).substring(2, 10)}

Format: ${formatLabel[format] || format}
Tone: ${tone}

Generate exactly ${numberOfWeeks} unique weekly topics, each with a compelling headline and brief description. Topics should:
- Be SPECIFIC and UNIQUE - not generic topics that could apply to any company
- Cover the company's industry, expertise areas, and thought leadership angles
- Address ICP pain points and business challenges
- Mix evergreen topics with trending industry themes
- Progress from foundational to advanced topics across the ${numberOfWeeks} weeks
- Vary significantly from what any other AI would generate for the same company
- Be actionable and specific, not generic
- Include a mix of different content approaches across weeks (some weeks focus on problems, others on solutions, trends, stories, data, etc.)${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "name": "string — name for this content plan, e.g. '${numberOfWeeks}-Week Thought Leadership Series'",
  "numberOfWeeks": ${numberOfWeeks},
  "format": "${format}",
  "tone": "${primaryTone}",
  "topics": [
    {
      "week": "number — week number 1-${numberOfWeeks}",
      "topic": "string — the specific topic/angle for this week (MUST BE UNIQUE)",
      "headline": "string — a compelling, publication-ready headline (MUST BE UNIQUE)",
      "description": "string — 1-2 sentence description of what the column will cover"
    }
  ]
}`;

  const userPrompt = `Generate a ${numberOfWeeks}-week expert column content plan (${formatLabel[format]} format, ${tone} tone) for:

UNIQUENESS SEED: ${uniquenessSeed}
GENERATION SESSION ID: ${Date.now()}-${Math.random().toString(36).substring(2, 10)}

IMPORTANT: Create COMPLETELY UNIQUE topics. Do NOT use generic headlines. Each topic must be specific to this company and different from what you would generate in any other session.

${buildCompanyContext(inputs)}`;

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 12000 };
}

// ============================================
// SINGLE EXPERT COLUMN GENERATOR
// ============================================

export function buildExpertColumnPrompt(inputs: PRContentInputs): PromptResult {
  const formatLabel: Record<string, string> = {
    'article': 'Article',
    'qa': 'Question & Answer',
    'thought-leadership': 'Thought Leadership',
    'industry-insights': 'Industry Insights',
  };
  const toneLabel: Record<string, string> = {
    'professional': 'Professional',
    'educational': 'Educational',
    'authoritative': 'Authoritative',
    'conversational': 'Conversational',
  };

  const format = inputs.format || 'article';
  const primaryTone = inputs.tone || 'professional';
  const tone = buildToneDescription(inputs);
  const wordCount = inputs.wordCount || 800;

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are an expert column writer AI. Write a complete, publication-ready expert column article for the given topic and company context.

Format: ${formatLabel[format] || format}
Tone: ${tone}
Target word count: approximately ${wordCount} words

The column should:
- Position the founder/business as an industry authority
- Provide actionable insights and real value to the reader
- Be written in a ${tone} tone appropriate for professional publication
- Include data-backed arguments where possible
- Be self-contained and publication-ready${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "weekNumber": ${inputs.weekNumber || 1},
  "format": "${format}",
  "tone": "${primaryTone}",
  "wordCount": ${wordCount},
  "headline": "string — compelling, publication-ready headline",
  "introduction": "string — 2-3 paragraph introduction that hooks the reader and establishes the thesis",
  "mainContent": "string — the full body of the column with detailed arguments, examples, and insights (this should be the longest section)",
  "conclusion": "string — strong conclusion with key takeaways and call-to-action",
  "authorBio": "string — a brief author bio positioning the writer as an expert",
  "mediaSubmissionNotes": "string — notes on where and how to submit this column for publication"
}`;

  const weekInfo = inputs.weekNumber ? `Week ${inputs.weekNumber}` : '';
  const topicInfo = inputs.topic ? `Topic: ${inputs.topic}` : '';

  const userPrompt = `Write an expert column article (${formatLabel[format]} format, ${tone} tone, ~${wordCount} words)${weekInfo ? ` for ${weekInfo}` : ''}${topicInfo ? ` — ${topicInfo}` : ''}:\n\n${buildCompanyContext(inputs)}`;

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}

// ============================================
// PRESS RELEASE GENERATOR
// ============================================

export function buildPressReleasePrompt(inputs: PRContentInputs): PromptResult {
  const eventTypeLabel: Record<string, string> = {
    'product-launch': 'Product Launch',
    'company-announcement': 'Company Announcement',
    'business-milestone': 'Business Milestone',
    'award': 'Award & Recognition',
    'event': 'Event',
    'partnership': 'Partnership',
    'expansion': 'Expansion News',
    'achievement': 'Achievement Announcement',
  };

  const eventType = inputs.eventType || 'company-announcement';
  const wordCount = inputs.wordCount || 800;
  const toneDescription = buildToneDescription(inputs);

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a professional press release writer AI. Write a complete, publication-ready press release for the given company and event type.

Event Type: ${eventTypeLabel[eventType] || eventType}
${buildToneInstruction(inputs)}
Target word count: approximately ${wordCount} words

The press release should:
- Follow standard press release format (FOR IMMEDIATE RELEASE, dateline, ### end mark)
- Be written in third person, journalistic style
- Include a strong, attention-grabbing headline
- Have a compelling subheadline
- Include a quote from the founder/CEO
- Provide relevant company background
- End with a proper boilerplate and call-to-action
- Be newsworthy and factual, written in a ${toneDescription} tone
- Target approximately ${wordCount} words
- Structure the output as a NEWSPAPER FRONT PAGE, not a single continuous essay.
- Break the story into 4-6 SEPARATE sub-stories. Each gets its own short headline (3-7 words, title case, no full stop) and 2-4 short paragraphs of 40-70 words.
- The first sub-story is the lead; each later one covers a distinct angle — market impact, customer benefit, technology, expansion, what happens next.
- Never write one long block. A reader must be able to read any sub-story on its own.
- Supply 2-3 short, punchy quotes (under 25 words each) suitable for newspaper pull quotes.
- Write in tight journalistic prose: short sentences, active voice, concrete facts and numbers. No marketing adjectives, no bullet lists inside sections.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "headline": "string — strong, attention-grabbing headline",
  "subheadline": "string — secondary headline adding context",
  "keyAnnouncement": "string — a concise 1-2 sentence summary of the main announcement",
  "introduction": "string — the opening paragraph(s) with dateline and lead paragraph that hooks the reader",
  "mainContent": "string — the core body of the press release with key details, facts, and supporting information",
  "conclusion": "string — the closing paragraph(s) with summary and call-to-action",
  "sections": [
    {
      "sectionTitle": "string — short newspaper headline for this sub-story, 3-7 words, title case, no full stop",
      "content": "string — 2-4 short paragraphs of 40-70 words each, journalistic style"
    }
  ],
  "pullQuotes": [
    {
      "text": "string — a punchy quote under 25 words",
      "attribution": "string — Name, Role"
    }
  ],
  "body": "string — the complete press release body text including dateline, lead paragraph, supporting paragraphs, and quotes (full text)",
  "founderQuotes": "string — 1-2 direct quotes from the founder/CEO that add authority and human interest",
  "companyBackground": "string — brief company background paragraph (boilerplate-style)",
  "boilerplate": "string — standard boilerplate paragraph about the company for media use",
  "callToAction": "string — clear call-to-action with contact information and next steps"
}`;

  const userPrompt = `Write a ${eventTypeLabel[eventType]} press release (${toneDescription} tone, ~${wordCount} words) for:\n\nTitle: ${inputs.title || 'Press Release'}\nKey Announcement: ${inputs.keyAnnouncement || 'To be determined'}${inputs.customNotes ? `\nAdditional Notes: ${inputs.customNotes}` : ''}\n\n${buildCompanyContext(inputs)}`;

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}

// ============================================
// BIO GENERATOR
// ============================================

export function buildBioPrompt(inputs: PRContentInputs): PromptResult {
  const bioTypeLabel: Record<string, string> = {
    'founder-bio': 'Founder Bio',
    'executive-bio': 'Executive Bio',
    'speaker-bio': 'Speaker Bio',
    'short-bio': 'Short Bio (50-100 words)',
    'long-bio': 'Long Bio (300-500 words)',
    'event-introduction-bio': 'Event Introduction Bio',
  };

  const bioType = inputs.bioType || 'founder-bio';
  const primaryTone = inputs.tone || 'professional';
  const tone = buildToneDescription(inputs);
  const wordCount = inputs.wordCount || 500;

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a professional bio writer AI. Write a compelling, publication-ready bio for the given person and company context.

Bio Type: ${bioTypeLabel[bioType] || bioType}
Tone: ${tone}
Target word count: approximately ${wordCount} words — you MUST write at least ${Math.floor(wordCount * 0.8)} words and aim for ${wordCount} words. Do NOT write a short or abbreviated bio.

The bio should:
- Position the person as an authority in their field
- Highlight relevant achievements and expertise
- Be written in third person
- Match the ${tone} tone specified
- Be appropriate for the bio type (${bioTypeLabel[bioType]})
- Include measurable achievements where possible
- Feel natural and authentic, not generic
- Be DETAILED and COMPREHENSIVE — write the full ${wordCount}-word bio, not a summary${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "content": "string — the complete bio text, ready for publication. Must be at least ${Math.floor(wordCount * 0.8)} words.",
  "title": "string — the person's title/role as it should appear",
  "bioType": "string — the bio type, one of: founder-bio, executive-bio, speaker-bio, short-bio, long-bio, event-introduction-bio",
  "personName": "string — the person's name",
  "tone": "${primaryTone}",
  "wordCount": "number — the target word count",
  "tags": ["array of 3-5 relevant tags/categories"]
}`;

  const personName = inputs.personName || inputs.founderName || 'the founder';

  let userPrompt = `Write a ${bioTypeLabel[bioType]} (${tone} tone, approximately ${wordCount} words) for ${personName}. The bio MUST be at least ${Math.floor(wordCount * 0.8)} words — do not write a short version.\n\n${buildCompanyContext(inputs)}`;

  if (inputs.customNotes?.trim()) {
    userPrompt += `\n\nAdditional context from the user (use this as the primary source for writing the bio):\n${inputs.customNotes.trim()}`;
  }

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}

// ============================================
// MEDIA KIT GENERATOR
// ============================================

export function buildMediaKitPrompt(inputs: PRContentInputs): PromptResult {
  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a media kit content writer AI. Generate comprehensive, detailed media kit content for the given company, including all standard media kit sections.

The media kit should:
- Be professional, comprehensive, and DETAILED
- Position the company as a credible, newsworthy organisation
- Include all standard media kit sections with substantial content in each
- Be ready for use in press kits, partnership proposals, and investor materials
- Use facts from the company context to make it specific and credible
- Each section MUST contain at least 2-3 full paragraphs of detailed content — do NOT write brief or abbreviated sections${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "name": "string — name for this media kit, e.g. '[Company Name] Media Kit'",
  "companyOverview": "string — comprehensive company overview (3-4 detailed paragraphs covering mission, history, market position, growth trajectory)",
  "founderOverview": "string — detailed founder/leadership overview (2-3 paragraphs highlighting qualifications, achievements, and vision)",
  "keyAchievements": "string — detailed bullet-point list of major achievements, milestones, and growth metrics with specific numbers",
  "awardsRecognition": "string — awards, certifications, press mentions, and industry recognition with context",
  "contactLayout": "string — formatted contact information section with media inquiry details"
}`;

  let userPrompt = `Generate a comprehensive, detailed media kit for:\n\n${buildCompanyContext(inputs)}`;

  if (inputs.customNotes?.trim()) {
    userPrompt += `\n\nAdditional direction from the user (use this as the primary focus for the media kit):\n${inputs.customNotes.trim()}`;
  }

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 12000 };
}

// ============================================
// NEWS STORY GENERATOR
// ============================================

export function buildNewsStoryPrompt(inputs: PRContentInputs & {
  eventType?: string;
  keyAnnouncement?: string;
  customNotes?: string;
  wordCount?: number;
  tone?: string;
}): PromptResult {
  const eventType = inputs.eventType || 'company-growth';
  const keyAnnouncement = inputs.keyAnnouncement || '';
  const customNotes = inputs.customNotes || '';
  const wordCount = inputs.wordCount || 800;
  const primaryTone = inputs.tone || 'professional';
  const tone = buildToneDescription(inputs);

  const eventTypeLabel: Record<string, string> = {
    'product-launch': 'Product Launch',
    'company-growth': 'Company Growth',
    'award': 'Award & Recognition',
    'milestone': 'Business Milestone',
    'event-announcement': 'Event Announcement',
    'partnership': 'Partnership',
    'funding': 'Funding & Investment',
    'leadership-change': 'Leadership Change',
  };

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a news story writer AI. Generate a compelling, publication-ready news story for the given company and event type.

Event Type: ${eventTypeLabel[eventType] || eventType}
Tone: ${tone}
Target word count: approximately ${wordCount} words

The news story should:
- Have a compelling, newsworthy headline
- Include a concise news summary (2-3 sentences)
- Feature a well-structured article body with clear paragraphs
- Include a media-ready quote
- Include a founder/executive quote
- End with a strong call-to-action
- List 3-5 key facts as bullet points
- Match the ${tone} tone
- Be suitable for immediate distribution to media outlets${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "title": "string — story title",
  "headline": "string — compelling news headline",
  "newsSummary": "string — 2-3 sentence news summary",
  "articleBody": "string — full article body (${wordCount} words)",
  "mediaQuote": "string — media-ready quote from company spokesperson",
  "founderQuote": "string — quote attributed to the founder/CEO",
  "callToAction": "string — clear call-to-action for readers",
  "keyFacts": ["array of 3-5 key facts as bullet points"],
  "wordCount": number,
  "tone": "${primaryTone}",
  "tags": ["array of 3-5 relevant tags"]
}`;

  const contextParts = [buildCompanyContext(inputs)];
  if (keyAnnouncement) contextParts.push(`\nKey Announcement: ${keyAnnouncement}`);
  if (customNotes) contextParts.push(`\nAdditional Notes: ${customNotes}`);

  const userPrompt = `Write a ${eventTypeLabel[eventType]} news story (${tone} tone, ~${wordCount} words) for:\n\n${contextParts.join('\n')}`;

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}

// ============================================
// THOUGHT LEADERSHIP GENERATOR
// ============================================

export function buildThoughtLeadershipPrompt(inputs: PRContentInputs & {
  contentType?: string;
  topic?: string;
  tone?: string;
  wordCount?: number;
}): PromptResult {
  const contentType = inputs.contentType || 'industry-opinion';
  const topic = inputs.topic || '';
  const primaryTone = inputs.tone || 'professional';
  const tone = buildToneDescription(inputs);
  const wordCount = inputs.wordCount || 1000;

  const contentTypeLabel: Record<string, string> = {
    'industry-opinion': 'Industry Opinion',
    'market-trends': 'Market Trends Analysis',
    'predictions': 'Industry Predictions',
    'business-insights': 'Business Insights',
    'founder-perspective': 'Founder Perspective',
    'innovation-story': 'Innovation Story',
  };

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a thought leadership content writer AI. Generate a compelling thought leadership piece that positions the company/founder as an industry authority.

Content Type: ${contentTypeLabel[contentType] || contentType}
Tone: ${tone}
Target word count: approximately ${wordCount} words

The thought leadership piece should:
- Have a powerful, attention-grabbing headline
- Include a compelling introduction that hooks the reader
- Feature well-structured main content with data points and insights
- Include a strong conclusion with key takeaways
- Position the company/founder as a thought leader
- Be written in the ${tone} tone
- Include 3-5 key takeaways${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "title": "string — content title",
  "headline": "string — attention-grabbing headline",
  "introduction": "string — compelling introduction paragraph",
  "mainContent": "string — main body content (${wordCount} words)",
  "conclusion": "string — strong conclusion",
  "keyTakeaways": ["array of 3-5 key takeaways"],
  "wordCount": number,
  "tone": "${primaryTone}",
  "tags": ["array of 3-5 relevant tags"]
}`;

  const topicLine = topic ? `\nSpecific Topic: ${topic}` : '';
  const userPrompt = `Write a ${contentTypeLabel[contentType]} article (${tone} tone, ~${wordCount} words) for:\n\n${buildCompanyContext(inputs)}${topicLine}`;

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}

// ============================================
// HEADLINE LABORATORY
// ============================================

export function buildHeadlinePrompt(inputs: PRContentInputs & {
  contentTitle?: string;
  contentSummary?: string;
  contentType?: string;
  categories?: string[];
}): PromptResult {
  const contentTitle = inputs.contentTitle || '';
  const contentSummary = inputs.contentSummary || '';
  const contentType = inputs.contentType || 'press-release';
  const categories = inputs.categories || ['corporate', 'news', 'viral', 'authority', 'media-friendly'];

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a headline optimisation AI. Generate 5 different headline options for the given content, each targeting a different category. Score each headline on a 0-100 scale.

Categories: ${categories.join(', ')}

For each headline, provide:
- The headline text (concise, compelling, under 100 characters)
- The category it targets
- A quality score (0-100) based on clarity, impact, and engagement potential
- Brief reasoning for the score${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "headlines": [
    {
      "headline": "string — the headline text",
      "category": "string — one of: ${categories.join(', ')}",
      "score": number — quality score 0-100,
      "reasoning": "string — brief explanation of the score"
    }
  ]
}

Generate exactly 5 headlines, one for each of these categories: ${categories.join(', ')}.`;

  const userPrompt = `Generate 5 headline options for a ${contentType} titled "${contentTitle}":\n\nContent Summary: ${contentSummary}\n\nCompany Context:\n${buildCompanyContext(inputs)}`;

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 4000 };
}

// ============================================
// QUOTE GENERATOR
// ============================================

export function buildQuotePrompt(inputs: PRContentInputs & {
  contentId?: string;
  contentText?: string;
  quoteType?: string;
  tone?: string;
}): PromptResult {
  const contentText = inputs.contentText || '';
  const quoteType = inputs.quoteType || 'founder-quote';
  const primaryTone = inputs.tone || 'professional';
  const tone = buildToneDescription(inputs);

  const quoteTypeLabel: Record<string, string> = {
    'founder-quote': 'Founder Quote',
    'ceo-quote': 'CEO Quote',
    'leadership-quote': 'Leadership Quote',
    'expert-quote': 'Expert Quote',
  };

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a quote writer AI. Generate 3 compelling, media-ready quotes for the given content context.

Quote Type: ${quoteTypeLabel[quoteType] || quoteType}
Tone: ${tone}

Each quote should:
- Be concise (1-2 sentences)
- Sound authentic and natural
- Be suitable for media publications
- Include proper attribution
- Match the ${tone} tone${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "quotes": [
    {
      "quoteText": "string — the full quote text",
      "attribution": "string — who said it (e.g., 'John Smith, CEO of Company')",
      "context": "string — brief context for when to use this quote",
      "quoteType": "string",
      "tone": "${primaryTone}"
    }
  ]
}

Generate exactly 3 quotes of type "${quoteTypeLabel[quoteType]}" in a ${tone} tone.`;

  const userPrompt = `Generate 3 ${quoteTypeLabel[quoteType]}s (${tone} tone) based on this content:\n\n${contentText}\n\nCompany Context:\n${buildCompanyContext(inputs)}`;

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 4000 };
}

// ============================================
// MEDIA OUTREACH GENERATOR
// ============================================

export function buildMediaOutreachPrompt(inputs: PRContentInputs & {
  outreachType?: string;
  linkedContentTitle?: string;
  linkedContentSummary?: string;
  recipientName?: string;
  recipientOrganization?: string;
}): PromptResult {
  const outreachType = inputs.outreachType || 'journalist-email';
  const recipientName = inputs.recipientName || '';
  const recipientOrganization = inputs.recipientOrganization || '';

  const outreachTypeLabel: Record<string, string> = {
    'journalist-email': 'Journalist Outreach Email',
    'publication-pitch': 'Publication Pitch Email',
    'podcast-pitch': 'Podcast Pitch Email',
    'speaking-opportunity': 'Speaking Opportunity Application',
    'event-participation': 'Event Participation Request',
  };

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a media outreach specialist AI. Generate a professional outreach email for the given type.

Outreach Type: ${outreachTypeLabel[outreachType] || outreachType}

The outreach should:
- Have a compelling subject line
- Be professionally written and personalised
- Include a clear call-to-action
- Be concise but impactful
- Follow best practices for ${outreachTypeLabel[outreachType]} outreach${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "title": "string — brief title/description of this outreach",
  "subjectLine": "string — email subject line",
  "body": "string — full email body text",
  "callToAction": "string — clear next step for the recipient",
  "outreachType": "string — MUST be exactly one of: journalist-email, publication-pitch, podcast-pitch, speaking-opportunity, event-participation. Use the enum value, NOT a human-readable label.",
  "recipientName": "string — personalised recipient name (use provided name or 'Editor')",
  "recipientOrganization": "string — recipient organisation",
  "description": "string — brief 1-2 sentence description of this outreach purpose and context"
}`;

  const personalisation = [];
  if (recipientName) personalisation.push(`Recipient Name: ${recipientName}`);
  if (recipientOrganization) personalisation.push(`Recipient Organisation: ${recipientOrganization}`);
  const personalisationLine = personalisation.length ? `\n${personalisation.join('\n')}` : '';

  const userPrompt = `Generate a ${outreachTypeLabel[outreachType]} for:\n\n${buildCompanyContext(inputs)}${personalisationLine}`;

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}

// ============================================
// CALENDAR SUGGESTION GENERATOR
// ============================================

export function buildCalendarSuggestionPrompt(inputs: PRContentInputs & {
  frequency?: string;
  focusAreas?: string[];
}): PromptResult {
  const frequency = inputs.frequency || 'monthly';
  const focusAreas = inputs.focusAreas || [];

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a PR content calendar strategist AI. Generate a strategic PR content calendar with specific content suggestions for the given time period.

Frequency: ${frequency}
${focusAreas.length ? `Focus Areas: ${focusAreas.join(', ')}` : ''}

The calendar should:
- Suggest specific content topics for each time slot
- Mix content types: press releases, expert columns, news stories, thought leadership, media outreach
- Include seasonal and industry-relevant opportunities
- Assign priority levels
- Be realistic and actionable${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "entries": [
    {
      "title": "string — content title/topic",
      "entryType": "string — one of: press-release, expert-column, news-story, thought-leadership, media-outreach, pr-campaign",
      "scheduledDate": "string — ISO date (YYYY-MM-DD)",
      "description": "string — brief description of what to create",
      "priority": "string — one of: low, medium, high, urgent",
      "tags": ["array of relevant tags"]
    }
  ]
}

Generate 8-12 calendar entries for a ${frequency} content plan.`;

  const userPrompt = `Generate a ${frequency} PR content calendar for:\n\n${buildCompanyContext(inputs)}`;

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}

// ============================================
// CONTENT REPURPOSING
// ============================================

export function buildRepurposePrompt(inputs: PRContentInputs & {
  sourceId?: string;
  sourceType?: string;
  sourceContent?: string;
  targetFormat?: string;
}): PromptResult {
  const sourceType = inputs.sourceType || 'press-release';
  const sourceContent = inputs.sourceContent || '';
  const targetFormat = inputs.targetFormat || 'linkedin-post';

  const targetFormatLabel: Record<string, string> = {
    'linkedin-post': 'LinkedIn Post',
    'twitter-thread': 'Twitter/X Thread',
    'newsletter': 'Newsletter',
    'blog-article': 'Blog Article',
    'executive-summary': 'Executive Summary',
    'press-summary': 'Press Summary',
  };

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a content repurposing specialist AI. Transform the given ${sourceType} content into a ${targetFormatLabel[targetFormat]}.

Target Format: ${targetFormatLabel[targetFormat]}

The repurposed content should:
- Be optimised for the ${targetFormatLabel[targetFormat]} format
- Maintain the core message and key information
- Follow best practices for ${targetFormatLabel[targetFormat]}
- Include a headline/title appropriate for the format
- Be ready for immediate publication${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "headline": "string — title appropriate for the target format",
  "generatedContent": "string — the full repurposed content",
  "wordCount": number,
  "targetFormat": "string",
  "sourceType": "string",
  "tags": ["array of 3-5 relevant tags"]
}`;

  const userPrompt = `Transform the following ${sourceType} content into a ${targetFormatLabel[targetFormat]}:\n\n${sourceContent}\n\nCompany Context:\n${buildCompanyContext(inputs)}`;

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}

// ============================================
// WIKIPEDIA ARTICLE GENERATOR
// ============================================

export function buildWikipediaArticlePrompt(inputs: PRContentInputs & {
  wikiArticleTopic?: string;
  wikiSectionNames?: string[];
  wikiExistingContent?: string;
}): PromptResult {
  const topic = inputs.wikiArticleTopic || inputs.companyName || '';
  const sectionNames = inputs.wikiSectionNames || ['Introduction', 'History', 'Products and Services', 'Market Position', 'Achievements', 'See Also'];
  const existingContent = inputs.wikiExistingContent || '';

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a Wikipedia article writer AI. Generate a Wikipedia-style article draft following Wikipedia's content policies and notability guidelines.

The article should:
- Follow Wikipedia's Manual of Style (neutral point of view, verifiability, no original research)
- Be written in an encyclopaedic, neutral tone
- Include properly structured sections with headers
- Reference factual claims that would need citations
- Include a Conflict of Interest (COI) disclosure assessment
- Be comprehensive but not promotional${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "title": "string — the proposed article title",
  "summary": "string — a concise 2-3 paragraph lead section summarising the subject in Wikipedia style (the article's introduction before the first section header)",
  "sections": [
    {
      "sectionTitle": "string — section heading",
      "content": "string — full section content in Wikipedia style",
      "citations": ["string — citation placeholders like [1], [2] referencing claims that need sources"],
      "status": "string — one of: draft, needs-citations, review-ready"
    }
  ],
  "coiDisclosure": "string — COI assessment explaining whether the subject has a conflict of interest and what disclosures are needed",
  "notabilityAssessment": "string — brief assessment of whether the subject meets Wikipedia's notability guidelines",
  "suggestedCategories": ["array of suggested Wikipedia categories"],
  "infobox": {
    "name": "string — organisation name",
    "type": "string — organisation type",
    "industry": "string — industry",
    "founded": "string — founding year",
    "headquarters": "string — headquarters location",
    "website": "string — website URL"
  }
}`;

  let userPrompt = `Generate a Wikipedia-style article about "${topic}" with the following sections: ${sectionNames.join(', ')}.\n\n${buildCompanyContext(inputs)}`;
  if (existingContent) {
    userPrompt += `\n\nExisting content to improve/expand:\n${existingContent}`;
  }

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 12000 };
}

// ============================================
// WIKIPEDIA NOTABILITY CHECK GENERATOR
// ============================================

export function buildWikipediaNotabilityPrompt(inputs: PRContentInputs): PromptResult {
  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a Wikipedia notability assessment AI. Evaluate whether the given company meets Wikipedia's notability criteria for organisations (WP:ORG).

Assess the company against ALL of Wikipedia's notability criteria for organisations:
1. WP:ORGCRIT — The organisation has been the subject of significant coverage in multiple independent, reliable secondary sources
2. WP:NOTABLE — The organisation's actions have had a significant impact outside its own field
3. WP:INHERITED — Notability is not inherited from parent/child organisations
4. WP:LOCAL — Local organisations may be notable if they meet specific criteria
5. WP:GNG — The General Notability Guideline: significant coverage in reliable sources independent of the subject

For each criterion, assess whether it is met and provide evidence reasoning.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "overallScore": "number — notability score 0-100",
  "summary": "string — brief overall notability assessment",
  "criteria": [
    {
      "criterion": "string — the Wikipedia notability criterion name/ID",
      "met": "boolean — whether the criterion is met",
      "evidence": "string — detailed reasoning for the assessment",
      "score": "number — confidence score 0-100 for this criterion"
    }
  ],
  "strengths": ["array of factors that support notability"],
  "weaknesses": ["array of factors that may challenge notability"],
  "recommendations": ["array of specific actions to strengthen notability"],
  "sourceQualityAssessment": "string — overall assessment of available source quality"
}`;

  const userPrompt = `Assess the Wikipedia notability of the following organisation. Evaluate against all relevant notability criteria for organisations:\n\n${buildCompanyContext(inputs)}`;

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}

// ============================================
// WIKIPEDIA CITATION SUGGESTION GENERATOR
// ============================================

export function buildWikipediaCitationPrompt(inputs: PRContentInputs & {
  claims?: string[];
  articleContent?: string;
}): PromptResult {
  const claims = inputs.claims || [];
  const articleContent = inputs.articleContent || '';

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a Wikipedia citation specialist AI. Suggest reliable, independent sources that could support the claims made in a Wikipedia article.

For each source suggestion, assess:
- Type: primary (direct from subject), secondary (independent reporting), tertiary (encyclopaedic/aggregator)
- Reliability: high (established publications), medium (trade publications, blogs), low (self-published)
- Independence: independent (no affiliation), affiliated (partner/related), self-published (by the subject)

Wikipedia requires sources that are:
1. Reliable — published by reputable publishers with editorial oversight
2. Independent — not affiliated with the subject
3. Secondary — reporting about the subject, not by the subject${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "citations": [
    {
      "url": "string — suggested URL or source description if URL not available",
      "title": "string — source title",
      "type": "string — one of: primary, secondary, tertiary",
      "reliability": "string — one of: high, medium, low",
      "independence": "string — one of: independent, affiliated, self-published",
      "excerpt": "string — brief excerpt or description of what this source supports",
      "suggestedArchivedUrl": "string — suggested archive.org URL or empty string",
      "suggestedArchivedDate": "string — suggested archive date in YYYY-MM-DD format or empty string",
      "status": "string — one of: pending, verified, failed",
      "claimsSupported": ["array of claim descriptions this source could support"]
    }
  ],
  "overallAssessment": "string — brief assessment of the citation landscape",
  "recommendedActions": ["array of specific actions to improve source quality"]
}`;

  let userPrompt = `Suggest reliable sources for a Wikipedia article about the following organisation:\n\n${buildCompanyContext(inputs)}`;
  if (claims.length) {
    userPrompt += `\n\nSpecific claims that need citations:\n${claims.map((c, i) => `${i + 1}. ${c}`).join('\n')}`;
  }
  if (articleContent) {
    userPrompt += `\n\nArticle content to cite:\n${articleContent.substring(0, 3000)}`;
  }

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}

// ============================================
// KNOWLEDGE PANEL GENERATOR
// ============================================

export function buildKnowledgePanelPrompt(inputs: PRContentInputs & {
  kpPanelType?: string;
  kpCurrentData?: string;
  kpDesiredFields?: string[];
}): PromptResult {
  const panelType = inputs.kpPanelType || 'Organization';
  const currentData = inputs.kpCurrentData || '';
  const desiredFields = inputs.kpDesiredFields || [];

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a Google Knowledge Panel optimisation AI. Generate the ideal "What We Want" data for a Knowledge Panel based on the company's information.

A Google Knowledge Panel shows key facts about an entity in search results. Generate comprehensive, accurate data that should appear in the panel.

Panel Type: ${panelType}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "whatWeWant": {
    "name": "string — the entity name as it should appear",
    "description": "string — concise description for the Knowledge Panel (2-3 sentences)",
    "type": "string — entity type (${panelType})",
    "attributes": [
      {
        "key": "string — attribute name (e.g., 'Founded', 'Headquarters', 'Industry', 'CEO', 'Website', 'Employees', 'Revenue')",
        "value": "string — attribute value",
        "priority": "string — one of: critical, high, medium, low"
      }
    ]
  },
  "completenessScore": "number — estimated completeness percentage 0-100",
  "topActions": [
    {
      "action": "string — specific action to improve the panel",
      "priority": "string — one of: critical, high, medium, low",
      "completed": false
    }
  ]
}`;

  let userPrompt = `Generate the ideal Knowledge Panel data for:\n\n${buildCompanyContext(inputs)}`;
  if (currentData) {
    userPrompt += `\n\nCurrent Knowledge Panel data (what Google currently shows):\n${currentData}`;
  }
  if (desiredFields.length) {
    userPrompt += `\n\nDesired fields to include: ${desiredFields.join(', ')}`;
  }

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}

// ============================================
// KNOWLEDGE PANEL OPTIMISATION GENERATOR
// ============================================

export function buildKnowledgePanelOptimisationPrompt(inputs: PRContentInputs & {
  kpCurrentData?: string;
  kpPanelType?: string;
}): PromptResult {
  const currentData = inputs.kpCurrentData || '';
  const panelType = inputs.kpPanelType || 'Organization';

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a Google Knowledge Panel optimisation specialist AI. Generate prioritised suggestions for improving a company's Knowledge Panel presence and accuracy.

Panel Type: ${panelType}

Analyse the gap between what Google currently shows and what the company wants, then provide actionable suggestions prioritised by impact.

Categories: Schema markup, Content accuracy, Entity verification, Source coverage, Rich results${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "optimisations": [
    {
      "category": "string — one of: Schema markup, Content accuracy, Entity verification, Source coverage, Rich results",
      "suggestion": "string — specific, actionable suggestion",
      "priority": "string — one of: critical, high, medium, low",
      "status": "string — one of: pending, in-progress, completed",
      "impact": "string — expected impact description",
      "action": "string — specific action to take"
    }
  ],
  "overallScore": "number — estimated Knowledge Panel optimisation score 0-100",
  "criticalActions": "number — count of critical priority items"
}`;

  let userPrompt = `Generate prioritised Knowledge Panel optimisation suggestions for:\n\n${buildCompanyContext(inputs)}`;
  if (currentData) {
    userPrompt += `\n\nCurrent Knowledge Panel data:\n${currentData}`;
  }

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}

// ============================================
// KNOWLEDGE PANEL SCHEMA MARKUP GENERATOR
// ============================================

export function buildKnowledgePanelSchemaPrompt(inputs: PRContentInputs & {
  kpPanelType?: string;
}): PromptResult {
  const panelType = inputs.kpPanelType || 'Organization';

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a structured data / Schema.org specialist AI. Generate comprehensive JSON-LD structured data markup for a company's Knowledge Panel.

Schema Type: ${panelType}

Generate valid Schema.org JSON-LD that:
1. Follows Google's structured data guidelines
2. Includes all recommended properties for the schema type
3. Is syntactically valid JSON-LD
4. Maximises the chance of Google displaying a rich Knowledge Panel${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "schemaMarkup": "string — the complete JSON-LD markup (as a JSON string, properly escaped)",
  "schemaType": "string — the Schema.org type (e.g., 'Organization', 'LocalBusiness', 'Corporation')",
  "validation": {
    "isValid": true,
    "errors": ["array of validation errors, empty if valid"],
    "warnings": ["array of validation warnings, empty if none"],
    "propertiesIncluded": "number — count of Schema.org properties included"
  },
  "recommendedAdditions": ["array of additional properties that could be added for better coverage"]
}`;

  const userPrompt = `Generate ${panelType} Schema.org JSON-LD structured data markup for:\n\n${buildCompanyContext(inputs)}`;

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}

// ============================================
// KNOWLEDGE PANEL SUMMARY GENERATOR
// ============================================

export function buildKPSummaryPrompt(inputs: PRContentInputs & {
  kpTitle?: string;
  kpCategory?: string;
}): PromptResult {
  const title = inputs.kpTitle || '';
  const category = inputs.kpCategory || 'other';

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a Knowledge Panel content specialist AI. Generate a concise, authoritative summary for a Knowledge Panel entry.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "summary": "string — a concise 2-3 sentence executive summary suitable for a Knowledge Panel",
  "description": "string — a detailed 1-2 paragraph description providing comprehensive information"
}`;

  let userPrompt = `Generate a Knowledge Panel summary and description for:\n\n${buildCompanyContext(inputs)}`;
  if (title) userPrompt += `\n\nEntry Title: ${title}`;
  if (category) userPrompt += `\nCategory: ${category}`;

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}

// ============================================
// KNOWLEDGE PANEL SECTION CONTENT GENERATOR
// ============================================

export function buildKPSectionContentPrompt(inputs: PRContentInputs & {
  kpTitle?: string;
  sectionType?: string;
  sectionTitle?: string;
  existingContent?: string;
}): PromptResult {
  const sectionType = inputs.sectionType || 'overview';
  const sectionTitle = inputs.sectionTitle || sectionType;
  const existingContent = inputs.existingContent || '';

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a Knowledge Panel content specialist AI. Generate content for a specific section of a Knowledge Panel entry.

Section Type: ${sectionType}
Section Title: ${sectionTitle}

Generate informative, factual, and well-structured content appropriate for this section type.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "sectionType": "string — the section type provided",
  "title": "string — the section title (can be improved from the provided title)",
  "content": "string — the full content for this section (well-structured, factual, 2-5 paragraphs)"
}`;

  let userPrompt = `Generate Knowledge Panel section content for:\n\n${buildCompanyContext(inputs)}`;
  if (inputs.kpTitle) userPrompt += `\n\nEntry Title: ${inputs.kpTitle}`;
  if (existingContent) userPrompt += `\n\nExisting content to improve:\n${existingContent}`;

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}

// ============================================
// KNOWLEDGE PANEL INSIGHTS GENERATOR
// ============================================

export function buildKPInsightsPrompt(inputs: PRContentInputs & {
  kpTitle?: string;
  kpCategory?: string;
}): PromptResult {
  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a Knowledge Panel insights analyst AI. Generate actionable insights and recommendations for improving a Knowledge Panel entry.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "insights": [
    {
      "id": "string — unique identifier",
      "generatedType": "insight",
      "content": "string — the insight or recommendation",
      "applied": false
    }
  ],
  "overallAssessment": "string — brief overall assessment of the Knowledge Panel quality"
}`;

  let userPrompt = `Generate Knowledge Panel insights for:\n\n${buildCompanyContext(inputs)}`;
  if (inputs.kpTitle) userPrompt += `\n\nEntry: ${inputs.kpTitle}`;

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}

// ============================================
// KNOWLEDGE PANEL FAQ GENERATOR
// ============================================

export function buildKPFAQsPrompt(inputs: PRContentInputs & {
  kpTitle?: string;
  kpCategory?: string;
}): PromptResult {
  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a Knowledge Panel FAQ specialist AI. Generate frequently asked questions and answers relevant to a Knowledge Panel entry.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "faqs": [
    {
      "id": "string — unique identifier",
      "generatedType": "faq",
      "content": "string — question and answer in format: Q: [question]\\nA: [answer]",
      "applied": false
    }
  ]
}`;

  let userPrompt = `Generate Knowledge Panel FAQs for:\n\n${buildCompanyContext(inputs)}`;
  if (inputs.kpTitle) userPrompt += `\n\nEntry: ${inputs.kpTitle}`;

  const languageInstruction = buildLanguageInstruction(inputs.language);
  return { systemPrompt: systemPrompt + languageInstruction, userPrompt, maxTokens: 8000 };
}