/**
 * Guerrilla Marketing Content Generation
 *
 * Generates marketing content for guerrilla campaigns across 10 content types:
 * tagline, caption, press-release, whatsapp-message, email, poster-copy,
 * reel-script, social-post, slogan, hashtag-set
 *
 * Follows the Social Media content generation pattern:
 * - Single AI call per content type (or all at once)
 * - Safe JSON parsing with parseJsonFromAI()
 * - Brand guardrails from pipeline inputs
 */

import { generateWithAI } from '../../utils/aiProvider';
import { parseJsonFromAI } from './parseJsonFromAI';
import {
  GuerrillaMarketingPipelineInputs,
  buildGuerrillaStrategyPrompt,
} from './guerrillaMarketingPrompts';

// ============================================
// TYPES
// ============================================

export type GuerrillaContentType =
  | 'tagline'
  | 'caption'
  | 'press-release'
  | 'whatsapp-message'
  | 'email'
  | 'poster-copy'
  | 'reel-script'
  | 'social-post'
  | 'slogan'
  | 'hashtag-set';

export interface GuerrillaContentResult {
  items: {
    id: string;
    contentType: GuerrillaContentType;
    content: string;
    variations?: string[];
    cta?: string;
    tone?: string;
    status: string;
    platform?: string;
  }[];
  contentType: string;
  tokensUsed: number;
  model: string;
  provider: string;
}

// ============================================
// CONTENT TYPE CONFIGS
// ============================================

const CONTENT_TYPE_CONFIG: Record<GuerrillaContentType, {
  label: string;
  count: number;
  maxTokens: number;
}> = {
  'tagline': { label: 'Campaign Taglines', count: 10, maxTokens: 2000 },
  'caption': { label: 'Social Media Captions', count: 15, maxTokens: 3000 },
  'press-release': { label: 'Press Releases', count: 1, maxTokens: 4000 },
  'whatsapp-message': { label: 'WhatsApp Messages', count: 5, maxTokens: 2000 },
  'email': { label: 'Email Content', count: 3, maxTokens: 3000 },
  'poster-copy': { label: 'Poster Copy', count: 5, maxTokens: 2000 },
  'reel-script': { label: 'Reel Scripts', count: 3, maxTokens: 3000 },
  'social-post': { label: 'Social Posts', count: 10, maxTokens: 3000 },
  'slogan': { label: 'Slogans', count: 10, maxTokens: 1500 },
  'hashtag-set': { label: 'Hashtag Sets', count: 5, maxTokens: 1500 },
};

// ============================================
// SAFE GENERATION HELPER
// ============================================

async function safeGenerate(
  prompt: string,
  systemPrompt: string,
  maxTokens: number,
  temperature: number = 0.7,
  userId?: string,
  companyId?: string,
): Promise<{ parsed: Record<string, any> | null; tokensUsed: number; model: string; provider: string } | null> {
  // BUG #98: append a per-call variation token so every (re)generation is a
  // distinct request — this defeats any provider-side prompt caching and nudges
  // the model to produce fresh, non-repeated content on each Regenerate click.
  const variationTag = `\n\n[Generation variation ${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}: produce fresh, original content that does not repeat any previous output.]`;
  // BUG #101: forward userId/companyId so generation uses the organization's
  // configured AI provider/API keys and honours subscription AI-model access.
  // Without these, generation could silently fall through to an unconfigured
  // provider and return empty content ("Generate All Content" did nothing).
  const result = await generateWithAI(prompt + variationTag, systemPrompt, maxTokens, temperature, 'json', undefined, undefined, userId, companyId);

  if (!result || !result.content) {
    console.warn('[GuerrillaMarketing-ContentGen] AI returned empty content');
    return null;
  }

  const parsed = parseJsonFromAI(result.content);

  if (!parsed) {
    console.warn('[GuerrillaMarketing-ContentGen] Failed to parse AI response as JSON');
    return null;
  }

  return {
    parsed,
    tokensUsed: result.tokenUsage?.totalTokens || 0,
    model: result.model || 'unknown',
    provider: result.provider || 'unknown',
  };
}

function findArray(parsed: Record<string, any>, keyNames: string[]): any[] | null {
  for (const key of keyNames) {
    if (Array.isArray(parsed[key]) && parsed[key].length > 0) {
      return parsed[key];
    }
  }
  for (const key of Object.keys(parsed)) {
    const val = parsed[key];
    if (val && typeof val === 'object' && !Array.isArray(val)) {
      for (const innerKey of keyNames) {
        if (Array.isArray(val[innerKey]) && val[innerKey].length > 0) {
          return val[innerKey];
        }
      }
    }
  }
  return null;
}

// ============================================
// CONTENT PROMPT BUILDERS
// ============================================

function buildContentPrompt(
  inputs: GuerrillaMarketingPipelineInputs,
  contentType: GuerrillaContentType | 'all',
  strategy: Record<string, any>,
  selectedIdeas: Record<string, any>[],
): { systemPrompt: string; userPrompt: string; maxTokens: number } {
  const config = contentType === 'all'
    ? { label: 'All Content Types', count: 5, maxTokens: 8000 }
    : CONTENT_TYPE_CONFIG[contentType];

  const JSON_INSTRUCTION = '\n\nIMPORTANT: Return ONLY valid JSON. No markdown code fences, no explanatory text before or after the JSON. The response must start with { and end with }.';

  const brandContext = inputs.brandPersonality?.length
    ? `\nBrand Personality: ${inputs.brandPersonality.join(', ')}`
    : '';
  const brandGuardrails = inputs.brandGuardrails
    ? `\nBrand Guardrails: ${inputs.brandGuardrails}`
    : '';
  const forbiddenWords = inputs.brandForbiddenWords?.length
    ? `\nNEVER use these words: ${inputs.brandForbiddenWords.join(', ')}`
    : '';
  const toneStyle = inputs.toneStyle ? `\nTone: ${inputs.toneStyle}` : '';

  const ideaSummaries = selectedIdeas.slice(0, 5).map((idea, i) =>
    `${i + 1}. ${idea.title || `Idea ${i + 1}`}: ${idea.description || idea.concept || ''}`
  ).join('\n');

  const strategySummary = strategy.summary || strategy.coreConcept || '';

  if (contentType === 'all' || contentType === 'tagline') {
    const systemPrompt = `You are an expert guerrilla marketing content creator AI. Generate creative, impactful marketing content that aligns with the brand and campaign strategy.${toneStyle}${brandContext}${brandGuardrails}${forbiddenWords}

Return a JSON object with content items. Each item must have: id, contentType, content, cta (call-to-action), tone, variations (2-3 alternative versions), status ("draft").${JSON_INSTRUCTION}`;

    const userPrompt = `Generate marketing content for:

Company: ${inputs.companyName}
${inputs.companyDescription ? `Description: ${inputs.companyDescription}` : ''}
${inputs.companyIndustry ? `Industry: ${inputs.companyIndustry}` : ''}
${inputs.companyTargetAudience ? `Target Audience: ${inputs.companyTargetAudience}` : ''}
${inputs.budgetRange ? `Budget: ${inputs.budgetRange}` : ''}

Strategy: ${strategySummary}

Selected Ideas:
${ideaSummaries || 'Various creative guerrilla tactics'}

${contentType === 'all' ? `Generate content for ALL these types: tagline (5), caption (8), press-release (1), whatsapp-message (3), email (2), poster-copy (3), reel-script (2), social-post (5), slogan (5), hashtag-set (3).` : `Generate ${config.count} ${config.label}.`}

Return as: { "items": [ { "id": "content-1", "contentType": "...", "content": "...", "cta": "...", "tone": "...", "variations": ["alt1", "alt2"], "status": "draft" } ] }${JSON_INSTRUCTION}`;

    return { systemPrompt, userPrompt, maxTokens: config.maxTokens };
  }

  // Single content type
  const systemPrompt = `You are an expert guerrilla marketing content creator specializing in ${config.label}. Generate creative, impactful content that aligns with the brand and campaign strategy.${toneStyle}${brandContext}${brandGuardrails}${forbiddenWords}

Generate exactly ${config.count} unique ${config.label}. Each must be creative, on-brand, and actionable.${JSON_INSTRUCTION}`;

  const userPrompt = `Generate ${config.count} ${config.label} for:

Company: ${inputs.companyName}
${inputs.companyDescription ? `Description: ${inputs.companyDescription}` : ''}
${inputs.companyTargetAudience ? `Target Audience: ${inputs.companyTargetAudience}` : ''}

Strategy: ${strategySummary}

Key Ideas:
${ideaSummaries || 'Creative guerrilla marketing tactics'}

Return as: { "items": [ { "id": "content-1", "contentType": "${contentType}", "content": "...", "cta": "Call to action", "tone": "matching tone", "variations": ["variation 1", "variation 2"], "status": "draft" } ] }${JSON_INSTRUCTION}`;

  return { systemPrompt, userPrompt, maxTokens: config.maxTokens };
}

// ============================================
// MAIN GENERATION FUNCTION
// ============================================

export async function generateGuerrillaContent(
  inputs: GuerrillaMarketingPipelineInputs,
  strategy: Record<string, any>,
  selectedIdeas: Record<string, any>[],
  contentType: GuerrillaContentType | 'all' = 'all',
  onProgress?: (progress: number, step: string) => void,
  userId?: string,
  companyId?: string,
): Promise<GuerrillaContentResult> {
  const startTime = Date.now();
  const contentTypes: GuerrillaContentType[] = contentType === 'all'
    ? ['tagline', 'caption', 'social-post', 'slogan', 'hashtag-set', 'whatsapp-message', 'email', 'poster-copy', 'reel-script', 'press-release']
    : [contentType];

  const allItems: GuerrillaContentResult['items'] = [];
  let totalTokens = 0;
  let lastModel = 'unknown';
  let lastProvider = 'unknown';

  if (contentType === 'all') {
    // Generate all content types in batches
    const batchSize = 3;
    for (let i = 0; i < contentTypes.length; i += batchSize) {
      const batch = contentTypes.slice(i, i + batchSize);
      const progress = 10 + (i / contentTypes.length) * 80;
      onProgress?.(progress, `Generating ${batch.map(t => CONTENT_TYPE_CONFIG[t].label).join(', ')}...`);

      for (const ct of batch) {
        try {
          const config = CONTENT_TYPE_CONFIG[ct];
          const { systemPrompt, userPrompt, maxTokens } = buildContentPrompt(inputs, ct, strategy, selectedIdeas);

          const result = await safeGenerate(userPrompt, systemPrompt, maxTokens, 0.8, userId, companyId);

          if (result?.parsed) {
            const items = findArray(result.parsed, ['items', 'content', 'contentItems', ct]) || [];
            for (const item of items) {
              allItems.push({
                id: item.id || `${ct}-${allItems.length + 1}`,
                contentType: ct,
                content: item.content || item.text || item.caption || item.description || '',
                variations: item.variations || [],
                cta: item.cta || item.callToAction || '',
                tone: item.tone || inputs.toneStyle || 'bold',
                status: item.status || 'draft',
                platform: item.platform,
              });
            }
            totalTokens += result.tokensUsed;
            lastModel = result.model;
            lastProvider = result.provider;
          }
        } catch (err: any) {
          console.warn(`[GuerrillaMarketing-ContentGen] Failed to generate ${ct}: ${err.message}`);
        }
      }
    }
  } else {
    // Generate single content type
    onProgress?.(10, `Generating ${CONTENT_TYPE_CONFIG[contentType].label}...`);

    const { systemPrompt, userPrompt, maxTokens } = buildContentPrompt(inputs, contentType, strategy, selectedIdeas);
    const result = await safeGenerate(userPrompt, systemPrompt, maxTokens, 0.8, userId, companyId);

    if (result?.parsed) {
      const items = findArray(result.parsed, ['items', 'content', 'contentItems', contentType]) || [];
      for (const item of items) {
        allItems.push({
          id: item.id || `${contentType}-${allItems.length + 1}`,
          contentType,
          content: item.content || item.text || item.caption || item.description || '',
          variations: item.variations || [],
          cta: item.cta || item.callToAction || '',
          tone: item.tone || inputs.toneStyle || 'bold',
          status: item.status || 'draft',
          platform: item.platform,
        });
      }
      totalTokens = result.tokensUsed;
      lastModel = result.model;
      lastProvider = result.provider;
    }
  }

  onProgress?.(95, `${allItems.length} content items generated`);

  return {
    items: allItems,
    contentType: contentType === 'all' ? 'all' : contentType,
    tokensUsed: totalTokens,
    model: lastModel,
    provider: lastProvider,
  };
}