/**
 * AI Prompt Library for Ads Pipeline
 *
 * Generates ad campaign + ads content in 3 stages using company context,
 * ICP data, product info, brand strategy. Generates 1 campaign with 3 ads.
 */

// ============================================
// TYPES
// ============================================

export interface AdsPipelineInputs {
  /**
   * The user's own brief from the "Generate with AI" popup or the AI Chat
   * generation flow — audience, topics, tone, goals and the chosen data
   * sources. Stated as the highest-priority instruction in the prompt.
   */
  customInstructions?: string;

  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[];

  // Pre-formatted context block built from the user's selected data sources
  // (personas, competitors, testimonials, FAQs, case studies, founders, ...)
  linkedRecordsContext?: string;

  targetCount: number;

  // User-provided context (overrides DB-sourced values)
  userCampaignName?: string;
  userCampaignObjective?: string;
  userProductName?: string;
  userBusinessDescription?: string;
  userTargetAudience?: string;
  userTargetLocation?: string;
  userDailyBudget?: number;
  userLifetimeBudget?: number;
  userPreferredPlatform?: string;
  userLandingPageUrl?: string;
  userCallToAction?: string;
  userStartDate?: string;
  userEndDate?: string;
  userCurrency?: string;

  // Meta Ads Creative fields
  userPrimaryText?: string;
  userHeadline?: string;
  userDescription?: string;

  // Meta Ad Set budget fields
  userAdSetBudget?: number;
  userAdSetBudgetPeriod?: string;

  // Google-specific fields
  userBiddingStrategy?: string;
  userTargetCpa?: number;
  userTargetRoas?: number;
  userTargetCpc?: number;
  userTargetImpressionShare?: number;
  userKeywords?: string[];
}

export type PartialAdsAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// HELPERS
// ============================================

function buildCompanyContext(inputs: AdsPipelineInputs): string {
  const parts: string[] = [];
  // The user's brief goes FIRST and is marked authoritative — it is the one
  // part of the context they typed themselves, so it must win over the derived
  // company/ICP/brand material below when the two disagree.
  if (inputs.customInstructions?.trim()) {
    parts.push(
      `USER BRIEF (highest priority — follow this over the general company context below):\n${inputs.customInstructions.trim()}\n`
    );
  }


  // User-provided requirements take priority — prepend them
  if (inputs.userCampaignName) parts.push(`User-Specified Campaign Name: ${inputs.userCampaignName}`);
  if (inputs.userCampaignObjective) parts.push(`User-Specified Campaign Objective: ${inputs.userCampaignObjective}`);
  if (inputs.userProductName) parts.push(`User-Specified Product/Service: ${inputs.userProductName}`);
  if (inputs.userBusinessDescription) parts.push(`User-Specified Business Description: ${inputs.userBusinessDescription}`);
  if (inputs.userTargetAudience) parts.push(`User-Specified Target Audience: ${inputs.userTargetAudience}`);
  if (inputs.userTargetLocation) parts.push(`User-Specified Target Location: ${inputs.userTargetLocation}`);
  if (inputs.userDailyBudget) parts.push(`User-Specified Daily Budget: $${inputs.userDailyBudget}`);
  if (inputs.userLifetimeBudget) parts.push(`User-Specified Lifetime Budget: $${inputs.userLifetimeBudget}`);
  if (inputs.userPreferredPlatform) parts.push(`User-Specified Preferred Platform: ${inputs.userPreferredPlatform}`);
  if (inputs.userLandingPageUrl) parts.push(`User-Specified Landing Page URL: ${inputs.userLandingPageUrl}`);
  if (inputs.userCallToAction) parts.push(`User-Specified Call-to-Action: ${inputs.userCallToAction}`);
  if (inputs.userStartDate) parts.push(`User-Specified Start Date: ${inputs.userStartDate}`);
  if (inputs.userEndDate) parts.push(`User-Specified End Date: ${inputs.userEndDate}`);
  if (inputs.userCurrency) parts.push(`User-Specified Currency: ${inputs.userCurrency}`);

  // Meta Ads Creative fields
  if (inputs.userPrimaryText) parts.push(`User-Specified Primary Text (Ad Copy): ${inputs.userPrimaryText}`);
  if (inputs.userHeadline) parts.push(`User-Specified Headline: ${inputs.userHeadline}`);
  if (inputs.userDescription) parts.push(`User-Specified Description: ${inputs.userDescription}`);

  // Meta Ad Set budget fields
  if (inputs.userAdSetBudget) parts.push(`User-Specified Ad Set Budget: $${inputs.userAdSetBudget}`);
  if (inputs.userAdSetBudgetPeriod) parts.push(`User-Specified Ad Set Budget Period: ${inputs.userAdSetBudgetPeriod}`);

  // Google-specific user inputs
  if (inputs.userBiddingStrategy) parts.push(`User-Specified Bidding Strategy: ${inputs.userBiddingStrategy}`);
  if (inputs.userTargetCpa) parts.push(`User-Specified Target CPA: $${inputs.userTargetCpa}`);
  if (inputs.userTargetRoas) parts.push(`User-Specified Target ROAS: ${inputs.userTargetRoas}`);
  if (inputs.userTargetCpc) parts.push(`User-Specified Target CPC: $${inputs.userTargetCpc}`);
  if (inputs.userTargetImpressionShare) parts.push(`User-Specified Target Impression Share: ${inputs.userTargetImpressionShare}%`);
  if (inputs.userKeywords?.length) parts.push(`User-Specified Keywords: ${inputs.userKeywords.join(', ')}`);

  if (parts.length > 0) parts.push(''); // blank line separator

  // DB-sourced context supplements user requirements
  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}`);
    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.linkedRecordsContext) {
    parts.push(`\nSelected Data Sources (base the campaign on these records):\n${inputs.linkedRecordsContext}`);
  }

  return parts.join('\n');
}

// Number of creative variants the AI is asked to produce per ad. One Ad owns
// many creatives, so this drives the creativeAssets fan-out in stage 2.
export const CREATIVES_PER_AD = 3;

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.';

// ============================================
// STAGE 1: CAMPAIGN & AD IDENTITY
// ============================================

export function buildAdsIdentityPrompt(inputs: AdsPipelineInputs): PromptResult {
  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B digital advertising strategist AI. Generate a complete ad campaign concept for the given company, including the campaign and ${inputs.targetCount} individual ads. The campaign should target the company's ICP, leverage their USPs, and align with their brand voice.

The ads should be practical, high-converting, and directly tied to the company's offerings.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "campaign": {
    "name": "string — compelling campaign name, e.g. 'Q2 SaaS Pipeline Accelerator'",
    "description": "string — 2-3 sentence campaign description",
    "goal": "string — one of: awareness, traffic, leads, conversions, engagement, app-installs, video-views, retargeting",
    "platforms": ["array of 2-3 platforms from: google-search, google-display, google-shopping, facebook, instagram, tiktok, linkedin, youtube, twitter, pinterest, snapchat, reddit, microsoft"],
    "platformType": "string — either 'meta' (for facebook, instagram) or 'google' (for google-search, google-display, google-shopping, youtube)",
    "totalBudget": "number — suggested total budget in USD, e.g. 5000",
    "currency": "string — e.g. 'USD'",
    "budgetType": "string — either 'campaign' (budget at campaign level) or 'adset' (budget at ad set level)",
    "budgetPeriod": "string — either 'daily' or 'lifetime'",
    "buyingType": "string — for Meta: 'AUCTION' or 'RESERVED', for Google: 'AUCTION'",
    "notes": "string — 2-3 sentence campaign strategy notes",
    "tags": ["array of 3-5 tags"],
    "startDate": "string — ISO date for campaign start, e.g. '2026-07-01'",
    "endDate": "string — optional ISO date for campaign end",
    "specialAdCategories": ["array — for Meta: 'CREDIT', 'EMPLOYMENT', 'HOUSING', 'ISSUES_ELECTIONS_POLITICS' or empty array"],
    "googleCampaignChannel": "string — for Google: 'search', 'performance-max', 'display', 'video', 'demand-gen', 'shopping'",
    "googleCampaignObjective": "string — for Google: 'sales', 'leads', 'website-traffic', 'app-promotion', 'awareness', 'local-store-visits'",
    "googleBiddingStrategy": "string — for Google: 'conversions', 'conversion-value', 'clicks', 'impression-share'",
    "googleTargetCpa": "number — optional, target cost per acquisition for Google when biddingStrategy is 'conversions'",
    "googleTargetRoas": "number — optional, target return on ad spend for Google when biddingStrategy is 'conversion-value'",
    "googleTargetCpc": "number — optional, target cost per click for Google when biddingStrategy is 'clicks'",
    "googleTargetImpressionShare": "number — optional, target impression share percentage for Google when biddingStrategy is 'impression-share'",
    "googleNetworks": ["array — for Google: 'google_search', 'search_partners', 'display_network', 'youtube', 'gmail', 'discover'"],
    "googleLocations": ["array — for Google: target locations, e.g. 'United States', 'United Kingdom', 'Germany'"],
    "googleLanguages": ["array — for Google: target language codes, e.g. 'en', 'es', 'de'"],
    "googleEuPoliticalAds": "boolean — for Google: whether campaign contains EU political content",
    "googleBudgetType": "string — for Google: 'average-daily' or 'campaign-total'",
    "googleBudgetAmount": "number — for Google: budget amount",
    "googleFinalUrl": "string — for Google: final destination URL",
    "googleUniqueSellingPoints": ["array — for Google: 2-4 USPs for ad copy"]
  },
  "budgets": [
    {
      "name": "string — budget name, e.g. 'Q2 Pipeline Budget'",
      "dailyBudget": "number — daily budget in USD, e.g. 50",
      "totalBudget": "number — total budget in USD, e.g. 3000",
      "currency": "string — e.g. 'USD'",
      "bidStrategy": "string — one of: manual-cpc, enhanced-cpc, target-cpa, target-roas, maximize-clicks, maximize-conversions",
      "targetCpc": "number — optional, target cost per click",
      "targetCpa": "number — optional, target cost per acquisition",
      "pacing": "string — one of: even, accelerated",
      "periodStart": "string — ISO date, e.g. '2026-07-01'",
      "periodEnd": "string — ISO date, e.g. '2026-09-30'"
    }
  ],
  "ads": [
    {
      "name": "string — ad name, e.g. 'SaaS Pipeline - LinkedIn Lead Gen'",
      "headline": "string — primary headline, 30-40 characters, e.g. 'Stop Burning Out Your SDRs'",
      "platform": "string — one of: google-search, google-display, google-shopping, facebook, instagram, tiktok, linkedin, youtube, twitter, pinterest, snapchat, reddit, microsoft",
      "objective": "string — one of: awareness, traffic, leads, conversions",
      "creativeType": "string — one of: image, video, carousel"
    }
  ]
}

Generate exactly ${inputs.targetCount} ads. Each ad should target a different platform or angle while staying aligned with the campaign goal.`;

  const userPrompt = `Generate an ad campaign with ${inputs.targetCount} ads for:\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 45000 };
}

// ============================================
// STAGE 2: AD CONTENT, TARGETING & AD SETS
// ============================================

export function buildAdsContentPrompt(inputs: AdsPipelineInputs, partial: PartialAdsAnalysis): PromptResult {
  const campaignSummary = [
    partial.campaign?.name ? `Campaign: ${partial.campaign.name}` : '',
    partial.campaign?.goal ? `Goal: ${partial.campaign.goal}` : '',
    partial.campaign?.platforms ? `Platforms: ${partial.campaign.platforms.join(', ')}` : '',
    partial.campaign?.platformType ? `Platform Type: ${partial.campaign.platformType}` : '',
  ].filter(Boolean).join('\n');

  const adsSummary = (partial.ads || []).map((ad: any, i: number) =>
    `Ad ${i + 1}: ${ad.name || 'Untitled'} | Platform: ${ad.platform || 'unknown'} | Objective: ${ad.objective || 'awareness'} | Headline: ${ad.headline || 'N/A'}`
  ).join('\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B ad copywriter and audience strategist AI. For the given campaign and ad concepts, generate complete ad content including headlines, descriptions, CTAs, targeting parameters, ad set (audience) definitions, and Google Ads specific content (keywords, ad assets).

Keep each field concise — shorter valid JSON is better than longer broken JSON.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "ads": [
    {
      "name": "string — same ad name from stage 1",
      "headline": "string — primary headline, same or improved from stage 1",
      "headline2": "string — secondary headline variation, 30-40 characters",
      "primaryText": "string — MAIN BODY TEXT for Meta/Facebook ads. This is the primary ad copy that appears above the headline. Write 125-500 characters of compelling, persuasive copy that tells a story, highlights benefits, and drives action. This is the most visible text in the ad.",
      "description": "string — primary description, 60-90 characters, compelling and action-oriented",
      "description2": "string — secondary description variation, 60-90 characters",
      "cta": "string — call-to-action, one of: Learn More, Sign Up, Get Started, Contact Us, Download, Subscribe, Book Demo, Request Quote, Shop Now, Apply Now, Register, Try Free",
      "destinationUrl": "string — suggested landing page path, e.g. '/demo' or '/pricing'",
      "creativeType": "string — one of: image, video, carousel",
      "targeting": {
        "locations": ["array of 2-3 target locations, e.g. 'United States', 'United Kingdom'"],
        "countries": ["array of country codes, e.g. 'US', 'UK', 'IN'"],
        "states": ["array of states/regions, e.g. 'California', 'New York'"],
        "cities": ["array of cities, e.g. 'Los Angeles', 'London'"],
        "ageMin": "number — minimum age, e.g. 25",
        "ageMax": "number — maximum age, e.g. 55",
        "genders": ["array — e.g. 'male', 'female', or 'all'"],
        "languages": ["array of languages, e.g. 'English', 'Spanish'"],
        "interests": ["array of 4-6 relevant interests"],
        "behaviors": ["array of 2-3 relevant behaviors, e.g. 'B2B software buyer', 'SaaS decision-maker'"],
        "detailedTargeting": ["array of detailed targeting criteria for Meta: interests, behaviors, demographics"]
      },
      "googleKeywords": [
        {
          "text": "string — keyword text, e.g. 'best crm software'",
          "matchType": "string — one of: broad, phrase, exact",
          "isNegative": "boolean — false for positive keywords, true for negative"
        }
      ],
      "googleAdAssets": [
        {
          "finalUrl": "string — final destination URL",
          "displayPath1": "string — display URL path segment 1, max 15 chars",
          "displayPath2": "string — display URL path segment 2, max 15 chars",
          "headlines": [{"text": "string — headline text, max 30 chars", "pinnedPosition": "number — optional 1-4"}],
          "descriptions": [{"text": "string — description text, max 90 chars"}],
          "sitelinks": [{"title": "string — sitelink title", "url": "string — optional URL", "description1": "string — optional", "description2": "string — optional"}],
          "callouts": [{"text": "string — callout text, max 25 chars"}],
          "structuredSnippets": [{"header": "string — e.g. 'Services', 'Features'", "values": ["array of 3-10 values"]}]
        }
      ]
    }
  ],
  "audiences": [
    {
      "name": "string — audience name, e.g. 'B2B SaaS Decision Makers'",
      "description": "string — 1-2 sentence audience description",
      "type": "string — one of: custom, lookalike, saved, retargeting",
      "demographics": {
        "ageMin": "number — e.g. 25",
        "ageMax": "number — e.g. 55",
        "genders": ["array — e.g. 'male', 'female', 'all'"],
        "locations": ["array of 2-4 target locations"],
        "countries": ["array of country codes or names"],
        "states": ["array of states/regions"],
        "cities": ["array of cities"],
        "languages": ["array of languages, e.g. 'English', 'Spanish'"]
      },
      "interests": ["array of 4-8 relevant interests for Meta detailed targeting"],
      "behaviors": ["array of 2-4 relevant behaviors for Meta detailed targeting"],
      "detailedTargeting": ["array of detailed targeting criteria: interests, behaviors, demographics combined"],
      "platforms": ["array of 1-3 platforms from: google-search, google-display, google-shopping, facebook, instagram, tiktok, linkedin, youtube, twitter, pinterest, snapchat, reddit, microsoft"],
      "placementMode": "string — 'automatic' or 'manual'",
      "placements": ["array of placement values if manual mode, e.g. 'facebook_feed', 'instagram_stories'"],
      "estimatedSize": "number — estimated audience size, e.g. 50000",
      "optimizationGoal": "string — for Meta: 'conversions', 'landing_page_views', 'link_clicks', 'impressions', 'reach'",
      "conversionLocation": "string — for Meta sales campaigns: 'website', 'app', 'messenger', 'whatsapp'",
      "pixelId": "string — placeholder for Meta Pixel ID, e.g. 'PIXEL_ID_PLACEHOLDER'",
      "adSetStartDate": "string — ISO date for ad set start, e.g. '2026-07-01'",
      "adSetEndDate": "string — optional ISO date for ad set end",
      "googleAudienceSegments": ["array of Google audience segments, e.g. 'In-market: Software', 'Affinity: Business'"],
      "googleAudienceTargetingMode": "string — 'targeting' or 'observation'"
    }
  ],
  "creativeAssets": [
    {
      "adName": "string — REQUIRED. The exact 'name' value of the ad (from the ads array above) this creative belongs to",
      "name": "string — creative asset name, e.g. 'LinkedIn Lead Gen Hero Image'",
      "headline": "string — primary headline for this creative",
      "description": "string — creative description or primary text, 60-90 characters",
      "type": "string — one of: image, video, carousel, story, banner, headline-variant, description-variant",
      "cta": "string — call-to-action, same options as ad cta",
      "platform": "string — target platform, same as ad platform options",
      "destinationUrl": "string — landing page URL for this creative",
      "imagePrompt": "string — REQUIRED. Detailed AI image generation prompt describing the visual for THIS creative variant. Must be unique per creative."
    }
  ]
}

Generate content for all ${inputs.targetCount} ads and 2-3 distinct ad sets (audiences). Each ad set should represent a different targeting segment (e.g. decision-makers, lookalike, retargeting). Make each ad's copy distinct but on-message with the campaign theme.

IMPORTANT FOR CREATIVES: An ad owns MULTIPLE creatives. Generate ${CREATIVES_PER_AD} creative variants for EVERY one of the ${inputs.targetCount} ads (${inputs.targetCount * CREATIVES_PER_AD} creativeAssets in total). Every creative MUST set "adName" to the exact name of the ad it belongs to, and MUST carry its own distinct "imagePrompt" describing that specific visual. Do not reuse the same imagePrompt across creatives.

IMPORTANT FOR META ADS:
1. ALWAYS include primaryText - this is the MAIN BODY TEXT that appears in the ad. Write 125-500 characters of compelling, persuasive copy that tells a story and drives action.
2. Include detailedTargeting array with interests, behaviors, and demographics.
3. Set placementMode, placements, optimizationGoal, conversionLocation, and pixelId placeholder.

IMPORTANT FOR GOOGLE ADS: Always generate googleKeywords (5-15 keywords per ad) and googleAdAssets with headlines, descriptions, sitelinks, callouts, and structured snippets. Include googleAudienceSegments and googleAudienceTargetingMode.`;

  const userPrompt = `Generate ad content and ad sets for this campaign:\n\n${campaignSummary}\n\nAd concepts:\n${adsSummary}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 65000 };
}

// ============================================
// STAGE 3: AD STRATEGY & TRACKING
// ============================================

export function buildAdsStrategyPrompt(inputs: AdsPipelineInputs, partial: PartialAdsAnalysis): PromptResult {
  const campaignSummary = [
    partial.campaign?.name ? `Campaign: ${partial.campaign.name}` : '',
    partial.campaign?.goal ? `Goal: ${partial.campaign.goal}` : '',
  ].filter(Boolean).join(' ');

  const adsSummary = (partial.ads || []).map((ad: any, i: number) =>
    `Ad ${i + 1}: ${ad.name || 'Untitled'} | ${ad.platform || 'unknown'} | ${ad.headline || 'N/A'}`
  ).join('\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B ad optimization strategist AI. For the given campaign and ads, generate tracking parameters, priority levels, and optimization guidance.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "ads": [
    {
      "name": "string — same ad name",
      "priority": "string — one of: low, medium, high, urgent",
      "tags": ["array of 3-5 relevant tags"],
      "tracking": {
        "utmSource": "string — e.g. 'linkedin', 'google', 'facebook'",
        "utmMedium": "string — e.g. 'cpc', 'paid-social', 'display'",
        "utmCampaign": "string — campaign identifier, e.g. 'q2-pipeline-accelerator'",
        "utmContent": "string — ad variant identifier, e.g. 'headline-v1'",
        "pixelId": "string — placeholder, e.g. 'PIXEL-PLACEHOLDER'"
      }
    }
  ],
  "bestPractices": ["array of 3-5 ad optimization best practices for this campaign type"],
  "optimizationTips": ["array of 2-3 tips for improving ad performance"]
}`;

  const userPrompt = `Generate tracking and optimization strategy for:\n\n${campaignSummary}\n\nAds:\n${adsSummary}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 30000 };
}

// ============================================
// ENHANCEMENT PROMPT
// ============================================

export function buildAdsEnhancementPrompt(
  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 advertising 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 };
}