from flask import Flask, render_template, request, Response, stream_with_context
from groq import Groq
import json

app = Flask(__name__)

GROQ_API_KEY = "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"
GROQ_MODEL   = "llama-3.3-70b-versatile"


# ── System Prompts ─────────────────────────────────────────────────────────────

def scraper_prompt(niche):
    return f"""You are Agent 1 — the Content Scraper.
Niche: {niche}

Your job: Research the given topic and produce a structured intelligence report.

Output EXACTLY this structure in markdown:

## 📊 10 Trending Topics
A numbered table: | # | Topic | Why Trending | Momentum |

## 😤 Top 7 Pain Points
Bullet list — each pain point is ONE punchy line max.

## 🔥 5 Proven Viral Angles
For each angle: Name it, explain why it works in one sentence, give an example hook.

Keep everything sharp. No fluff. Numbers and specifics always beat vague statements."""


def validator_prompt():
    return """You are Agent 2 — the Content Validator.

You receive the scraper's output. Your job: rank every topic by viral potential and pick ONE winner.

Output EXACTLY this structure:

## 🏆 Viral Potential Rankings
A markdown table with columns: | Rank | Topic | Pain Score /10 | Hook Score /10 | Trend Score /10 | TOTAL /30 | Verdict |

## ✅ WINNING TOPIC
State the winner in bold. Then write 3 bullet points explaining WHY it wins (pain intensity, audience fit, hook-ability, timing).

## 🎯 Winning Viral Angle
One sentence: the exact angle to take on this topic for maximum virality.

Be decisive. Pick one winner. No hedging."""


def script_prompt(voice):
    guides = {
        "Hinglish — Bade Bhai (Calm)": "Calm Hinglish. Bade bhai tone. Short punchy lines. Mix Hindi and English naturally. No shouting. Authoritative but approachable.",
        "English — Direct & Punchy":    "Direct English. No filler. Short sentences. Data-backed claims. Professional but conversational.",
        "Hinglish — Energetic":         "Energetic Hinglish. High energy. Fast punches. Motivational. Mix of Hindi and English. Short bursts."
    }
    vg = guides.get(voice, guides["Hinglish — Bade Bhai (Calm)"])
    return f"""You are Agent 3 — the Script Writer.
Voice style: {vg}

You receive the winning topic and angle. Write a complete 45-second reel package.

Output EXACTLY this structure:

## 🎬 45-Second Reel Script

### BEAT 1 — Hook Drop (0–10 sec)
[3-4 lines max. Drop the core pain or claim. Make them stop scrolling.]

### BEAT 2 — Value Delivery (10–35 sec)
[The meat. Specific facts, steps, or proof. 5-7 punchy lines. NO filler.]

### BEAT 3 — Proof Punch (35–42 sec)
[One powerful closing statement that lands the message. 2-3 lines max.]

### CTA (42–45 sec)
[One clear action. Comment trigger preferred. Max 2 lines.]

---

## 📱 Caption
[3-4 lines of caption copy. Include a save-hook. End with comment trigger.]

[Blank line]

[8-10 relevant hashtags]

---

## ⏱ Timing Guide
| Beat | Duration | Word Count | Key Goal |
|------|----------|-----------|----------|

Keep every line speakable. Nothing that sounds like it was written by AI."""


def hook_prompt():
    return """You are Agent 4 — the Hook Generator.

You receive the winning topic, script, and caption. Generate 10 hooks using these 5 proven patterns (2 hooks per pattern):

Patterns:
1. PAIN POINT — Open with the exact thing that hurts
2. ASPIRATIONAL — Paint the life they want
3. EXCLUSIVITY — "Most people don't know this"
4. TIME/MONEY CLAIM — Specific number, specific result
5. CURIOSITY GAP — Incomplete information that demands completion

Output EXACTLY this structure:

## 🎣 10 Hooks

| # | Hook | Pattern | Confidence % | Why It Works |
|---|------|---------|-------------|--------------|

(Each hook: max 2 lines. Must be speakable in under 4 seconds.)

---

## 🏆 BEST HOOK

**Winner:** [The hook text in bold]

**Pattern:** [Which pattern]

**Why this wins:** [2-3 sentences on scroll-stop power, audience fit, specificity]

**Closest viral match:** [Describe a similar hook that went viral — format, angle, result]"""


# ── Routes ─────────────────────────────────────────────────────────────────────

@app.route('/')
def index():
    return render_template('index.html')


@app.route('/run', methods=['POST'])
def run_pipeline():
    data  = request.get_json(force=True)
    topic = (data.get('topic') or '').strip()
    niche = data.get('niche', 'Canada Finance + AI Tools')
    voice = data.get('voice', 'Hinglish — Bade Bhai (Calm)')

    if not topic:
        def err():
            yield f"data: {json.dumps({'type':'error','msg':'Topic is required'})}\n\n"
        return Response(err(), content_type='text/event-stream')

    def generate():
        try:
            client = Groq(api_key=GROQ_API_KEY)

            def stream_groq(system, user_msg):
                return client.chat.completions.create(
                    model=GROQ_MODEL, max_tokens=2048, stream=True,
                    messages=[
                        {"role": "system", "content": system},
                        {"role": "user",   "content": user_msg}
                    ]
                )

            # Agent 1 — Scraper
            yield f"data: {json.dumps({'type':'agent_start','agent':1})}\n\n"
            r1 = ""
            for chunk in stream_groq(
                scraper_prompt(niche),
                f"Research this topic and produce the full intelligence report:\n\nTopic: {topic}\nNiche: {niche}"
            ):
                d = chunk.choices[0].delta.content
                if d:
                    r1 += d
                    yield f"data: {json.dumps({'type':'chunk','agent':1,'text':d})}\n\n"
            yield f"data: {json.dumps({'type':'agent_done','agent':1})}\n\n"

            # Agent 2 — Validator
            yield f"data: {json.dumps({'type':'agent_start','agent':2})}\n\n"
            r2 = ""
            for chunk in stream_groq(
                validator_prompt(),
                f"Scraper output:\n\n{r1}\n\nOriginal topic: {topic}"
            ):
                d = chunk.choices[0].delta.content
                if d:
                    r2 += d
                    yield f"data: {json.dumps({'type':'chunk','agent':2,'text':d})}\n\n"
            yield f"data: {json.dumps({'type':'agent_done','agent':2})}\n\n"

            # Agent 3 — Script Writer
            yield f"data: {json.dumps({'type':'agent_start','agent':3})}\n\n"
            r3 = ""
            for chunk in stream_groq(
                script_prompt(voice),
                f"Winning topic and angle from Validator:\n\n{r2}\n\nOriginal topic: {topic}\nVoice: {voice}"
            ):
                d = chunk.choices[0].delta.content
                if d:
                    r3 += d
                    yield f"data: {json.dumps({'type':'chunk','agent':3,'text':d})}\n\n"
            yield f"data: {json.dumps({'type':'agent_done','agent':3})}\n\n"

            # Agent 4 — Hook Generator
            yield f"data: {json.dumps({'type':'agent_start','agent':4})}\n\n"
            r4 = ""
            for chunk in stream_groq(
                hook_prompt(),
                f"Topic: {topic}\n\nWinning angle:\n{r2}\n\nScript:\n{r3}"
            ):
                d = chunk.choices[0].delta.content
                if d:
                    r4 += d
                    yield f"data: {json.dumps({'type':'chunk','agent':4,'text':d})}\n\n"
            yield f"data: {json.dumps({'type':'agent_done','agent':4})}\n\n"

            yield f"data: {json.dumps({'type':'done','r1':r1,'r2':r2,'r3':r3,'r4':r4})}\n\n"

        except Exception as e:
            yield f"data: {json.dumps({'type':'error','msg':str(e)})}\n\n"

    return Response(
        stream_with_context(generate()),
        content_type='text/event-stream',
        headers={
            'Cache-Control':      'no-cache',
            'X-Accel-Buffering':  'no',
        }
    )


if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0', port=5000)
