/**
 * RMP Content Pipeline — Article Generation Engine
 *
 * Handles article generation for all 4 RMP sites:
 * - AV Beat (15-25/day)
 * - AV Beat (10-15/day)
 * - Backlot Beat (10-15/day)
 * - BroadcastEngineering.com (10-15/day)
 */

import { generateContent } from '../ai/aiNodeRouter';

export type RMPSite = 'broadcast-beat' | 'av-beat' | 'backlot-beat' | 'broadcast-engineering';

export interface SiteConfig {
  name: string;
  displayName: string;
  dailyTarget: { min: number; max: number };
  topics: string[];
  voice: string;
  penNames: string[];
}

export interface GeneratedArticle {
  title: string;
  metaTitle: string;
  metaDescription: string;
  content: string;
  excerpt: string;
  site: RMPSite;
  author: string;
  generatedAt: string;
  wordCount: number;
  node: string;
}

export interface PressReleaseRewrite {
  originalId: string;
  originalTitle: string;
  newTitle: string;
  metaTitle: string;
  metaDescription: string;
  content: string;
  node: string;
}

export const SITE_CONFIGS: Record<RMPSite, SiteConfig> = {
  'broadcast-beat': {
    name: 'broadcast-beat',
    displayName: 'AV Beat',
    dailyTarget: { min: 15, max: 25 },
    topics: [
      'broadcast technology', 'production gear', 'industry news', 'NAB Show coverage',
      'streaming infrastructure', 'live production', 'broadcast engineering',
      'media technology trends', 'IP video', 'cloud production',
    ],
    voice: 'professional, authoritative, technical, B2B broadcast industry trade publication',
    penNames: ['Michael Strand', 'James Mercer'],
  },
  'av-beat': {
    name: 'av-beat',
    displayName: 'AV Beat',
    dailyTarget: { min: 10, max: 15 },
    topics: [
      'audiovisual technology', 'AV integration', 'digital signage', 'commercial AV',
      'unified communications', 'conference room technology', 'AV/IT convergence',
      'AVIXA news', 'pro AV', 'display technology',
    ],
    voice: 'professional, technical, AV industry trade publication',
    penNames: ['Michael Strand', 'James Mercer'],
  },
  'backlot-beat': {
    name: 'backlot-beat',
    displayName: 'Backlot Beat',
    dailyTarget: { min: 10, max: 15 },
    topics: [
      'film production', 'TV production', 'studio news', 'Hollywood deals',
      'streaming platform news', 'production technology', 'talent news',
      'above-the-line industry news', 'below-the-line industry news',
      'location scouting', 'post-production',
    ],
    voice: 'entertainment industry trade, professional, insider knowledge',
    penNames: ['Michael Strand', 'James Mercer'],
  },
  'broadcast-engineering': {
    name: 'broadcast-engineering',
    displayName: 'BroadcastEngineering.com',
    dailyTarget: { min: 10, max: 15 },
    topics: [
      'broadcast engineering', 'RF technology', 'transmission systems', 'ATSC 3.0',
      'IP broadcasting', 'signal processing', 'broadcast infrastructure',
      'FCC regulations', 'technical standards', 'NextGen TV',
    ],
    voice: 'deeply technical, engineering-focused, authoritative',
    penNames: ['Michael Strand', 'James Mercer'],
  },
};

function pickRandom<T>(arr: T[]): T {
  return arr[Math.floor(Math.random() * arr.length)];
}

function pickRandomTopic(site: RMPSite): string {
  const topics = SITE_CONFIGS[site].topics;
  return pickRandom(topics);
}

export async function generateArticle(site: RMPSite, topicHint?: string): Promise<GeneratedArticle> {
  const config = SITE_CONFIGS[site];
  const topic = topicHint || pickRandomTopic(site);
  const author = pickRandom(config.penNames);

  const systemPrompt = `You are a senior editor at ${config.displayName}, a leading ${config.voice} publication. 
Write original, well-researched editorial articles for industry professionals.
Always write in active voice, use specific technical details, and provide genuine industry insight.
Never use generic filler content. Every article must provide real value to the reader.`;

  const userPrompt = `Write a complete editorial article about: ${topic}

Requirements:
- Headline: compelling, SEO-optimized, 60-80 characters
- Body: minimum 700 words, professional trade publication style
- Voice: ${config.voice}
- Include industry context, technical details, and expert perspective
- Add 2-3 relevant internal link placeholders as [INTERNAL_LINK: topic]
- End with a strong conclusion

Also provide:
- META_TITLE: (max 60 chars, include primary keyword)
- META_DESCRIPTION: (max 155 chars, include call to action)
- EXCERPT: (2-3 sentence summary, 50-80 words)

Format your response exactly as:
HEADLINE: [headline here]
META_TITLE: [meta title here]
META_DESCRIPTION: [meta description here]
EXCERPT: [excerpt here]
BODY:
[full article body here]`;

  const result = await generateContent(
    [
      { role: 'system', content: systemPrompt },
      { role: 'user', content: userPrompt },
    ],
    { model: 'llama3.1:70b', maxTokens: 4000, temperature: 0.75 }
  );

  // Parse structured response
  const lines = result.text.split('\n');
  let headline = '';
  let metaTitle = '';
  let metaDescription = '';
  let excerpt = '';
  let bodyLines: string[] = [];
  let inBody = false;

  for (const line of lines) {
    if (line.startsWith('HEADLINE:')) headline = line.replace('HEADLINE:', '').trim();
    else if (line.startsWith('META_TITLE:')) metaTitle = line.replace('META_TITLE:', '').trim();
    else if (line.startsWith('META_DESCRIPTION:')) metaDescription = line.replace('META_DESCRIPTION:', '').trim();
    else if (line.startsWith('EXCERPT:')) excerpt = line.replace('EXCERPT:', '').trim();
    else if (line.startsWith('BODY:')) inBody = true;
    else if (inBody) bodyLines.push(line);
  }

  const body = bodyLines.join('\n').trim();
  const wordCount = body.split(/\s+/).filter(Boolean).length;

  return {
    title: headline || `${topic} — ${config.displayName}`,
    metaTitle: metaTitle.slice(0, 60) || headline.slice(0, 60),
    metaDescription: metaDescription.slice(0, 155),
    content: body || result.text,
    excerpt,
    site,
    author,
    generatedAt: new Date().toISOString(),
    wordCount,
    node: result.node,
  };
}

export async function rewritePressRelease(
  originalId: string,
  originalTitle: string,
  originalContent: string,
  site: RMPSite
): Promise<PressReleaseRewrite> {
  const config = SITE_CONFIGS[site];

  const systemPrompt = `You are a senior editor at ${config.displayName}. 
Your job is to rewrite press releases into original editorial articles.
Preserve all factual data, product names, specs, companies, and dates.
Transform the corporate voice into ${config.voice} editorial style.`;

  const userPrompt = `Rewrite this press release into an original editorial article:

ORIGINAL TITLE: ${originalTitle}

ORIGINAL CONTENT:
${originalContent.slice(0, 3000)}

Requirements:
- New editorial headline (not a press release headline)
- Remove all press release language ("announced today", "is pleased to announce", "for immediate release", etc.)
- Add editorial angle and industry context
- Keep all facts, specs, product names, company names, dates
- Minimum 600 words
- Voice: ${config.voice}

Format:
HEADLINE: [new headline]
META_TITLE: [max 60 chars]
META_DESCRIPTION: [max 155 chars, include CTA]
BODY:
[full rewritten article]`;

  const result = await generateContent(
    [
      { role: 'system', content: systemPrompt },
      { role: 'user', content: userPrompt },
    ],
    { model: 'llama3.1:70b', maxTokens: 4000, temperature: 0.7 }
  );

  const lines = result.text.split('\n');
  let headline = '';
  let metaTitle = '';
  let metaDescription = '';
  let bodyLines: string[] = [];
  let inBody = false;

  for (const line of lines) {
    if (line.startsWith('HEADLINE:')) headline = line.replace('HEADLINE:', '').trim();
    else if (line.startsWith('META_TITLE:')) metaTitle = line.replace('META_TITLE:', '').trim();
    else if (line.startsWith('META_DESCRIPTION:')) metaDescription = line.replace('META_DESCRIPTION:', '').trim();
    else if (line.startsWith('BODY:')) inBody = true;
    else if (inBody) bodyLines.push(line);
  }

  return {
    originalId,
    originalTitle,
    newTitle: headline || `Editorial: ${originalTitle}`,
    metaTitle: metaTitle.slice(0, 60),
    metaDescription: metaDescription.slice(0, 155),
    content: bodyLines.join('\n').trim() || result.text,
    node: result.node,
  };
}

export async function generateSEOMeta(
  title: string,
  content: string,
  site: RMPSite
): Promise<{ metaTitle: string; metaDescription: string }> {
  const config = SITE_CONFIGS[site];

  const result = await generateContent(
    [
      {
        role: 'system',
        content: `You are an SEO specialist for ${config.displayName}. Generate concise, keyword-rich meta tags.`,
      },
      {
        role: 'user',
        content: `Generate SEO meta tags for this article:

TITLE: ${title}
CONTENT EXCERPT: ${content.slice(0, 500)}

Requirements:
- META_TITLE: max 60 characters, include primary keyword
- META_DESCRIPTION: max 155 characters, include call to action

Format:
META_TITLE: [title here]
META_DESCRIPTION: [description here]`,
      },
    ],
    { model: 'llama3.1:70b', maxTokens: 200, temperature: 0.5 }
  );

  const lines = result.text.split('\n');
  let metaTitle = '';
  let metaDescription = '';

  for (const line of lines) {
    if (line.startsWith('META_TITLE:')) metaTitle = line.replace('META_TITLE:', '').trim().slice(0, 60);
    if (line.startsWith('META_DESCRIPTION:')) metaDescription = line.replace('META_DESCRIPTION:', '').trim().slice(0, 155);
  }

  return {
    metaTitle: metaTitle || title.slice(0, 60),
    metaDescription: metaDescription || `Read the latest from ${config.displayName}.`,
  };
}
