// backend/src/jobs/agents.js
// All 10 AI agents — server version (same logic as CLI, works with any provider object)

export class IntelAgent {
  constructor(ai, config, voice) { this.ai = ai; this.config = config; this.voice = voice; }
  async run() {
    const system = `You are a content intelligence analyst specializing in ${this.config.niche}. Identify compelling, timely topics for the target audience: ${this.config.targetAudience || 'general audience'}.`;
    const prompt = `Today is ${new Date().toDateString()}. Generate a daily intelligence report for the niche: ${this.config.niche}

TRENDING TOPICS (5 topics):
1. [Topic] — [Why trending now] — [Content angle]
...

PAIN POINTS (3 problems the audience faces):
1. [Problem] — [Emotional context] — [Solution angle]
...

CONTENT OPPORTUNITIES (3 underserved angles):
1. [Angle] — [Why competitors miss this] — [Hook]
...

WEEKLY THEME: [One overarching theme]

VIRAL HOOK IDEAS (5 hooks):
1. [Hook]
...`;
    return this.ai.complete(system, prompt, 2000);
  }
}

export class TopicGeneratorAgent {
  constructor(ai, config, voice) { this.ai = ai; this.config = config; this.voice = voice; }
  async run(intelReport, count = 5) {
    const system = `You are a content strategy expert for ${this.config.niche}. Generate YouTube video topics that are SEO-friendly, timely, and match the creator's voice.`;
    const prompt = `Based on this intel, generate ${count} YouTube video topics.

INTEL:
${intelReport}

Niche: ${this.config.niche}
Audience: ${this.config.targetAudience || 'general'}

For each topic:
1. VIDEO TITLE: [SEO-optimized title]
ANGLE: [what makes it different]
KEY POINTS: [3 bullets]

Generate ${count} topics now:`;
    const raw = await this.ai.complete(system, prompt, 2000);
    const topics = [];
    for (const line of raw.split('\n')) {
      const match = line.match(/^(?:\d+\.\s+)?VIDEO TITLE[:\s]+(.+)/i);
      if (match) topics.push(match[1].trim());
    }
    if (topics.length < count) {
      const numbered = raw.match(/^\d+\.\s+([^\n]{15,})/gm) || [];
      for (const m of numbered) {
        const t = m.replace(/^\d+\.\s+/, '').trim();
        if (t && !topics.includes(t)) topics.push(t);
        if (topics.length >= count) break;
      }
    }
    return { raw, topics: topics.slice(0, count) };
  }
}

export class ScriptWriterAgent {
  constructor(ai, config, voice) { this.ai = ai; this.config = config; this.voice = voice; }
  async run(topic, intelReport = '') {
    const system = `You are a world-class YouTube scriptwriter for ${this.config.brand || 'a content creator'} in the ${this.config.niche} niche.

VOICE:
- Tone: ${this.voice.tone || 'conversational, direct'}
- Style: ${this.voice.writingStyle || 'educational yet entertaining'}
- Personality: ${this.voice.personality || 'expert friend'}
- Avoid: ${(this.voice.avoidWords || []).join(', ') || 'corporate speak, clichés'}
- CTA: ${this.voice.cta || 'like and subscribe'}

RULES:
- Spoken words ONLY. No stage directions or parentheticals.
- Minimum 1,800 spoken words.
- Hook in first 30 seconds.
- Every paragraph earns the next.`;
    const prompt = `Write a full YouTube script on: "${topic}"

Niche: ${this.config.niche} | Audience: ${this.config.targetAudience || 'general'}
${intelReport ? `\nINTEL CONTEXT:\n${intelReport.substring(0, 400)}` : ''}

Structure:
- TITLE: [SEO title]
- HOOK (0–30s)
- INTRO (30s–2min)
- MAIN CONTENT (2–12min, 3–5 sections)
- CONCLUSION (12–14min)
- CTA (final 30s)

Write the full script now:`;
    return this.ai.complete(system, prompt, 4096);
  }
}

export class XPostAgent {
  constructor(ai, config, voice) { this.ai = ai; this.config = config; this.voice = voice; }
  async run(intelReport, scripts = []) {
    const topics = scripts.slice(0, 2).map(s => s.topic).join(', ');
    const system = `You are a viral X (Twitter) strategist for ${this.config.niche}. Voice: ${this.voice.tone || 'direct, punchy'}.`;
    const prompt = `Write exactly 5 X posts. Each must:
- Start with a killer hook (no "I" as first word)
- Under 280 chars OR a well-structured thread
- Clear point of view
- Drive replies or shares

Niche: ${this.config.niche} | Today's topics: ${topics || this.config.niche}

FORMAT:
---POST 1---
[content]
---POST 2---
...`;
    return this.ai.complete(system, prompt, 1500);
  }
}

export class ThumbnailAgent {
  constructor(ai, config, voice) { this.ai = ai; this.config = config; this.voice = voice; }
  async run(scripts) {
    const topics = scripts.map(s => s.topic).join('\n- ');
    const system = `You are a YouTube thumbnail strategist. Design thumbnails that get clicked.`;
    const prompt = `For each topic, design 3 thumbnail concepts.

Topics:
- ${topics}

For each:
TITLE: [topic]
VARIANT A: [main text (max 4 words)] | [background] | [emotion] | [visual element]
VARIANT B: [same]
VARIANT C: [same]
BEST: [A/B/C] — [why] | AI image prompt: [prompt]`;
    return this.ai.complete(system, prompt, 2500);
  }
}

export class BlogAgent {
  constructor(ai, config, voice) { this.ai = ai; this.config = config; this.voice = voice; }
  async run(bestScript) {
    const system = `You are an SEO blog writer for ${this.config.niche}. Voice: ${this.voice.tone || 'expert, accessible'}. No keyword stuffing.`;
    const prompt = `Write a full SEO blog post from this script concept.

Topic: ${bestScript.topic}
Script excerpt: ${(bestScript.script || '').substring(0, 800)}...

Include:
- SEO Title + meta description (155 chars)
- H1/H2/H3 structure
- Introduction with hook
- 4–6 main sections
- FAQ (3–5 questions)
- Conclusion + CTA
- Min 1,500 words
Target: ${this.config.targetAudience || 'general audience'}`;
    return this.ai.complete(system, prompt, 4096);
  }
}

export class NewsletterAgent {
  constructor(ai, config, voice) { this.ai = ai; this.config = config; this.voice = voice; }
  async run(intelReport, scripts) {
    const topics = scripts.map(s => s.topic).join(', ');
    const system = `You write email newsletters for ${this.config.brand || 'a content creator'} in ${this.config.niche}. Voice: ${this.voice.tone || 'friendly expert'}. Feels personal, not corporate.`;
    const prompt = `Write today's newsletter.

Topics: ${topics}
Niche: ${this.config.niche}

Structure:
SUBJECT: [under 50 chars]
PREVIEW: [35 chars]

---
[Personal opener - 2-3 sentences]

THIS WEEK: [Best insight from today's content]

QUICK WINS (3 tips):
1.
2.
3.

WHAT I'M THINKING: [One original opinion]

TODAY'S CONTENT: [List with 1-sentence descriptions]

[Warm sign-off + CTA]`;
    return this.ai.complete(system, prompt, 1500);
  }
}

export class OutreachAgent {
  constructor(ai, config, voice) { this.ai = ai; this.config = config; this.voice = voice; }
  async run() {
    const system = `You are a strategic partnerships coordinator for content creators. Identify high-value collaboration opportunities.`;
    const prompt = `Find 5 collaboration opportunities for a ${this.config.niche} creator targeting ${this.config.targetAudience || 'general audience'}.

For each:
TYPE: [Podcast / YouTube collab / Newsletter swap / Brand deal / Guest post]
TARGET: [Specific type of creator/brand]
PITCH: [Value you bring]
SUBJECT: [Email subject]
EMAIL:
---
[Short pitch email, max 150 words]
---
WIN: [What success looks like]`;
    return this.ai.complete(system, prompt, 2000);
  }
}

export class ClipFactoryAgent {
  constructor(ai, config, voice) { this.ai = ai; this.config = config; this.voice = voice; }
  async run(scripts) {
    const topics = scripts.map(s => `"${s.topic}": ${(s.script || '').substring(0, 250)}...`).join('\n\n');
    const system = `You are a short-form video strategist. Identify the best clips from long content for Shorts/Reels/TikToks.`;
    const prompt = `From these scripts, identify the best clips for short-form.

${topics}

For each script, 2 clip opportunities:

VIDEO: [topic]
CLIP 1:
  Hook (first 3s): [exact words]
  Why it works: [reason]
  Caption: [under 100 chars]
  Platform: [TikTok / Reels / Shorts / All]
CLIP 2: [same]`;
    return this.ai.complete(system, prompt, 2000);
  }
}

export class PerformanceEvalAgent {
  constructor(ai, config, voice) { this.ai = ai; this.config = config; this.voice = voice; }
  async run(perfData) {
    const system = `You are a content performance analyst. Find patterns and generate actionable recommendations.`;
    const prompt = `Analyze this performance data and generate a Weekly Report.

Data:
${JSON.stringify(perfData, null, 2)}

Report:
WHAT WORKED: [3-5 observations with data]
WHAT DIDN'T: [3-5 observations]
TOPIC INSIGHTS: [best/worst types, recommendations]
HOOK ANALYSIS: [best hook style, next week recommendation]
NEXT WEEK STRATEGY: [5 specific actions]
TEST TOPICS (5): [topic suggestions based on data]`;
    return this.ai.complete(system, prompt, 2000);
  }
}
