import streamlit as st
from groq import Groq
from datetime import datetime

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

# ─── Page Config ──────────────────────────────────────────────────────────────
st.set_page_config(
    page_title="4-Agent Content System",
    page_icon="⚡",
    layout="wide",
    initial_sidebar_state="expanded"
)

# ─── CSS ──────────────────────────────────────────────────────────────────────
st.markdown("""
<style>
[data-testid="stAppViewContainer"] { background: #0e0e14; }
[data-testid="stSidebar"] { background: #13131f; border-right: 1px solid #2a2a40; }
section.main > div { padding-top: 1.5rem; }

.pipeline-bar {
    display: flex; align-items: center; justify-content: center;
    gap: 0; padding: 18px 0 22px;
}
.agent-node {
    display: flex; flex-direction: column; align-items: center;
    background: #1a1a2e; border: 1px solid #2e2e50;
    border-radius: 12px; padding: 12px 20px; min-width: 120px;
    transition: all .25s;
}
.agent-node.active  { border-color: #7c3aed; box-shadow: 0 0 18px #7c3aed55; }
.agent-node.done    { border-color: #10b981; box-shadow: 0 0 12px #10b98133; }
.agent-node .icon   { font-size: 1.6rem; }
.agent-node .label  { font-size: .72rem; color: #9ca3af; margin-top: 4px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; }
.agent-node .status { font-size: .68rem; margin-top: 2px; }
.arrow { color: #4b5563; font-size: 1.5rem; padding: 0 6px; margin-top: -12px; }

.agent-card {
    background: #13131f; border: 1px solid #2a2a40;
    border-radius: 14px; padding: 20px 24px; margin-bottom: 18px;
}
.agent-card.active  { border-color: #7c3aed; }
.agent-card.done    { border-color: #10b981; }
.agent-header {
    display: flex; align-items: center; gap: 10px;
    font-size: 1rem; font-weight: 700; color: #e5e7eb; margin-bottom: 14px;
}
.badge {
    font-size: .65rem; font-weight: 700; padding: 3px 10px;
    border-radius: 20px; letter-spacing: .06em; text-transform: uppercase;
}
.badge-pending { background: #1f2937; color: #6b7280; }
.badge-running { background: #4c1d95; color: #c4b5fd; }
.badge-done    { background: #064e3b; color: #6ee7b7; }

.final-box {
    background: linear-gradient(135deg, #1a1a2e, #16213e);
    border: 1px solid #7c3aed; border-radius: 16px; padding: 24px;
    margin-top: 10px;
}
.final-title { font-size: 1.1rem; font-weight: 800; color: #a78bfa; margin-bottom: 16px; }

h1, h2, h3 { color: #f3f4f6 !important; }
.stTextInput > label, .stTextArea > label { color: #9ca3af !important; font-size: .85rem; }
.stButton > button {
    background: linear-gradient(135deg, #7c3aed, #4f46e5);
    color: white; border: none; border-radius: 10px;
    padding: 12px 28px; font-weight: 700; font-size: .95rem;
    width: 100%; transition: opacity .2s;
}
.stButton > button:hover { opacity: .88; }
.stSpinner > div { border-top-color: #7c3aed !important; }
code { color: #a78bfa !important; }
.stMarkdown p { color: #d1d5db; line-height: 1.7; }
</style>
""", unsafe_allow_html=True)

# ─── Sidebar ──────────────────────────────────────────────────────────────────
with st.sidebar:
    st.markdown("## ⚡ 4-Agent Content System")
    st.markdown("<p style='color:#6b7280;font-size:.82rem;'>Topic → Scrape → Validate → Script → Hooks</p>", unsafe_allow_html=True)
    st.divider()

    topic = st.text_area(
        "Your Topic",
        placeholder="e.g. AI automation for Canada immigrants\ne.g. N8N workflow for content creators\ne.g. CRA benefits most people miss",
        height=100
    )

    niche = st.selectbox(
        "Content Niche",
        [
            "Canada Finance + AI Tools",
            "AI Automation",
            "Immigration & Money",
            "Tech for Non-Coders",
            "Creator Economy",
            "Mortgage Broker Canada",
            "Real Estate Agent / Realtor",
            "Real Estate Investing Canada",
            "First-Time Home Buyer Canada",
            "Mortgage Rates & Renewal Tips",
            "Pre-Construction & New Builds",
            "Commercial Real Estate Canada",
        ]
    )

    voice = st.selectbox(
        "Script Voice",
        ["Hinglish — Bade Bhai (Calm)", "English — Direct & Punchy", "Hinglish — Energetic"]
    )

    st.divider()
    run_btn = st.button("🚀 Run All 4 Agents", use_container_width=True)

    st.markdown("""
    <div style='margin-top:24px;padding:14px;background:#0e0e14;border-radius:10px;border:1px solid #1f2937;'>
    <p style='color:#6b7280;font-size:.75rem;margin:0;line-height:1.6;'>
    <b style='color:#9ca3af;'>Agent 1</b> — Scraper: finds 10 trending topics + pain points<br>
    <b style='color:#9ca3af;'>Agent 2</b> — Validator: ranks + picks the winner<br>
    <b style='color:#9ca3af;'>Agent 3</b> — Script Writer: 45-sec reel + caption<br>
    <b style='color:#9ca3af;'>Agent 4</b> — Hook Generator: 10 hooks + best pick
    </p>
    </div>
    """, unsafe_allow_html=True)

# ─── Title ─────────────────────────────────────────────────────────────────────
st.markdown("# ⚡ 4-Agent Content Pipeline")
st.markdown("<p style='color:#6b7280;margin-top:-10px;'>Enter a topic → watch 4 AI agents build your complete reel package.</p>", unsafe_allow_html=True)

# ─── Pipeline Visual ───────────────────────────────────────────────────────────
def pipeline_bar(states):
    icons  = ["🔍", "✅", "✍️", "🎣"]
    labels = ["Scraper", "Validator", "Script Writer", "Hook Gen"]
    nodes  = []
    for i, (icon, label) in enumerate(zip(icons, labels)):
        state = states[i]
        css   = f"agent-node {state}"
        badge = {"pending": "⏳ Pending", "active": "🔄 Running", "done": "✅ Done"}[state]
        color = {"pending": "#6b7280", "active": "#c4b5fd", "done": "#6ee7b7"}[state]
        nodes.append(f"""
        <div class="{css}">
        <span class="icon">{icon}</span>
        <span class="label">{label}</span>
        <span class="status" style="color:{color};">{badge}</span>
        </div>""")
    arrows = '<span class="arrow">→</span>'.join(nodes)
    st.markdown(f'<div class="pipeline-bar">{arrows}</div>', unsafe_allow_html=True)

# ─── Agent runner ──────────────────────────────────────────────────────────────
def stream_agent(client, system_prompt: str, user_msg: str, placeholder) -> str:
    full = ""
    stream = client.chat.completions.create(
        model=GROQ_MODEL,
        max_tokens=2048,
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user",   "content": user_msg}
        ],
        stream=True
    )
    for chunk in stream:
        delta = chunk.choices[0].delta.content
        if delta:
            full += delta
            placeholder.markdown(full + "▌")
    placeholder.markdown(full)
    return full

# ─── System Prompts ────────────────────────────────────────────────────────────
def scraper_prompt(niche: str) -> str:
    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() -> str:
    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: str) -> str:
    voice_guide = {
        "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."
    }
    return f"""You are Agent 3 — the Script Writer.
Voice style: {voice_guide.get(voice, voice_guide['Hinglish — Bade Bhai (Calm)'])}

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() -> str:
    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]"""

# ─── Session State Init ────────────────────────────────────────────────────────
for key in ["s1", "s2", "s3", "s4", "ran"]:
    if key not in st.session_state:
        st.session_state[key] = ""
if "ran" not in st.session_state:
    st.session_state.ran = False

# ─── Pipeline Status Placeholder ──────────────────────────────────────────────
pipe_placeholder = st.empty()
pipe_placeholder.markdown(
    '<div class="pipeline-bar"><em style="color:#4b5563;">Enter a topic and click Run to start the pipeline.</em></div>',
    unsafe_allow_html=True
)

st.divider()

# ─── Output Sections ───────────────────────────────────────────────────────────
col1, col2 = st.columns(2)

with col1:
    st.markdown("### 🔍 Agent 1 — Scraper")
    out1 = st.empty()
    if st.session_state.s1:
        out1.markdown(st.session_state.s1)
    else:
        out1.markdown("<p style='color:#4b5563;font-style:italic;'>Waiting to run...</p>", unsafe_allow_html=True)

with col2:
    st.markdown("### ✅ Agent 2 — Validator")
    out2 = st.empty()
    if st.session_state.s2:
        out2.markdown(st.session_state.s2)
    else:
        out2.markdown("<p style='color:#4b5563;font-style:italic;'>Waiting for Agent 1...</p>", unsafe_allow_html=True)

st.divider()

col3, col4 = st.columns(2)

with col3:
    st.markdown("### ✍️ Agent 3 — Script Writer")
    out3 = st.empty()
    if st.session_state.s3:
        out3.markdown(st.session_state.s3)
    else:
        out3.markdown("<p style='color:#4b5563;font-style:italic;'>Waiting for Agent 2...</p>", unsafe_allow_html=True)

with col4:
    st.markdown("### 🎣 Agent 4 — Hook Generator")
    out4 = st.empty()
    if st.session_state.s4:
        out4.markdown(st.session_state.s4)
    else:
        out4.markdown("<p style='color:#4b5563;font-style:italic;'>Waiting for Agent 3...</p>", unsafe_allow_html=True)

# ─── Final Package ─────────────────────────────────────────────────────────────
if st.session_state.ran:
    st.divider()
    st.markdown("## 🚀 Final Content Package")
    with st.expander("📋 View Complete Package — Click to Copy", expanded=True):
        full_report = f"""# Content Package — {datetime.now().strftime('%Y-%m-%d')}
**Topic:** {topic}
**Niche:** {niche}
**Voice:** {voice}

---

## AGENT 1 — SCRAPER
{st.session_state.s1}

---

## AGENT 2 — VALIDATOR
{st.session_state.s2}

---

## AGENT 3 — SCRIPT
{st.session_state.s3}

---

## AGENT 4 — HOOKS
{st.session_state.s4}
"""
        st.code(full_report, language="markdown")

    col_dl1, col_dl2 = st.columns(2)
    with col_dl1:
        st.download_button(
            "⬇️ Download Full Report (.md)",
            data=full_report,
            file_name=f"content_package_{datetime.now().strftime('%Y%m%d_%H%M')}.md",
            mime="text/markdown",
            use_container_width=True
        )
    with col_dl2:
        st.download_button(
            "⬇️ Download Script Only (.md)",
            data=st.session_state.s3,
            file_name=f"reel_script_{datetime.now().strftime('%Y%m%d_%H%M')}.md",
            mime="text/markdown",
            use_container_width=True
        )

# ─── Run Pipeline ──────────────────────────────────────────────────────────────
if run_btn:
    if not topic.strip():
        st.sidebar.error("Please enter a topic first.")
        st.stop()

    try:
        client = Groq(api_key=GROQ_API_KEY)
    except Exception:
        st.error("❌ Could not initialise Groq client. Check your API key.")
        st.stop()

    # Agent 1
    with pipe_placeholder:
        pipeline_bar(["active", "pending", "pending", "pending"])
    out1.markdown("<p style='color:#c4b5fd;'>🔄 Agent 1 researching your topic...</p>", unsafe_allow_html=True)
    a1_placeholder = out1.empty()
    result1 = stream_agent(
        client,
        scraper_prompt(niche),
        f"Research this topic and produce the full intelligence report:\n\nTopic: {topic}\nNiche: {niche}",
        a1_placeholder
    )
    st.session_state.s1 = result1

    # Agent 2
    with pipe_placeholder:
        pipeline_bar(["done", "active", "pending", "pending"])
    out2.markdown("<p style='color:#c4b5fd;'>🔄 Agent 2 ranking topics and picking the winner...</p>", unsafe_allow_html=True)
    a2_placeholder = out2.empty()
    result2 = stream_agent(
        client,
        validator_prompt(),
        f"Scraper output:\n\n{result1}\n\nOriginal topic: {topic}",
        a2_placeholder
    )
    st.session_state.s2 = result2

    # Agent 3
    with pipe_placeholder:
        pipeline_bar(["done", "done", "active", "pending"])
    out3.markdown("<p style='color:#c4b5fd;'>🔄 Agent 3 writing your reel script...</p>", unsafe_allow_html=True)
    a3_placeholder = out3.empty()
    result3 = stream_agent(
        client,
        script_prompt(voice),
        f"Winning topic and angle from Validator:\n\n{result2}\n\nOriginal topic: {topic}\nVoice: {voice}",
        a3_placeholder
    )
    st.session_state.s3 = result3

    # Agent 4
    with pipe_placeholder:
        pipeline_bar(["done", "done", "done", "active"])
    out4.markdown("<p style='color:#c4b5fd;'>🔄 Agent 4 generating hooks...</p>", unsafe_allow_html=True)
    a4_placeholder = out4.empty()
    result4 = stream_agent(
        client,
        hook_prompt(),
        f"Topic: {topic}\n\nWinning angle:\n{result2}\n\nScript:\n{result3}",
        a4_placeholder
    )
    st.session_state.s4 = result4

    # Done
    with pipe_placeholder:
        pipeline_bar(["done", "done", "done", "done"])

    st.session_state.ran = True
    st.balloons()
    st.rerun()