"""
Prompt C: Unclustered Raw Post Analysis

This prompt BYPASSES the clustering step entirely.
It receives a sample of raw Reddit posts and looks for viral hooks directly.

Hypothesis: Clustering may be abstracting away the specific details that make hooks work.
By looking at raw posts, we might find hooks that clustering would obscure into generic themes.
"""

PROMPT_C = """You are a viral content scout. Below are {post_count} raw Reddit posts from communities related to {topic_area}.

Your job: Find the SINGLE POST with the most viral potential and extract its hook.

I don't want themes. I don't want "people are interested in X." I want you to find the ONE specific post that contains something so surprising, counterintuitive, or emotionally charged that millions of people would click on it.

## THE RAW POSTS

{posts_text}

## WHAT YOU'RE LOOKING FOR

The best viral hooks come from:
1. **Personal confessions with numbers**: "I spent $50k on a financial advisor. Here's what I got."
2. **Counterintuitive outcomes**: "I followed all the advice and it made things worse"
3. **Revealed mechanisms**: "Why the thing you think helps is actually hurting you"
4. **Emotional recognition**: "That feeling when X happens" (if X is universal but unspoken)
5. **Surprising connections**: "Why your [A] is actually causing your [B]"

The best hooks are SPECIFIC (numbers, names, concrete details) not GENERAL (broad topics).

## YOUR TASK

1. Read every post
2. Identify which ONE post has the most viral potential
3. Extract the specific hook from that post
4. Turn it into a video concept

## RESPOND IN JSON:

{{
  "winning_post": {{
    "post_index": "Which post number (1-{post_count})",
    "why_this_one": "In 1-2 sentences, what makes this specific post viral-worthy?",
    "the_hook": "The specific surprising detail (quote the post if possible)"
  }},

  "video_concept": {{
    "title": "A specific, clickable title built from this hook",
    "the_question_it_answers": "What are viewers desperate to understand?",
    "the_revelation": "The surprising truth they'll learn",
    "why_share": "Why would someone send this to a friend?",
    "emotional_payoff": "How viewers feel after watching (validated/empowered/smarter/relieved/amused)"
  }},

  "hook_quality": {{
    "specificity": "1-5: Does it have concrete details (numbers, names, specific situations)?",
    "surprise_factor": "1-5: How much does it violate expectations?",
    "emotional_pull": "1-5: Does it make you feel something?",
    "universality": "1-5: Can many people relate to this?",
    "overall_score": "Average, 1 decimal"
  }},

  "runner_up_posts": [
    {{
      "post_index": "2nd best post number",
      "hook": "The hook from that post",
      "why_not_winner": "What's it missing vs the winner?"
    }},
    {{
      "post_index": "3rd best post number",
      "hook": "The hook from that post",
      "why_not_winner": "What's it missing?"
    }}
  ],

  "verdict": "MAKE_NOW / WORTH_MAKING / NEEDS_RESEARCH / SKIP",
  "verdict_reasoning": "One sentence"
}}

IMPORTANT:
- If NONE of the posts have genuine viral potential, say so. Verdict = SKIP.
- Don't force a hook where there isn't one.
- A good post in the data is worth more than a theoretically good topic.

Respond in JSON only. No markdown code blocks."""


def format_prompt_c(raw_posts: list, topic_area: str = "psychology and behavior") -> str:
    """Format Prompt C with raw posts (no clustering)."""
    # Build detailed post text
    posts_lines = []
    for i, post in enumerate(raw_posts[:25], 1):  # Limit to 25 posts
        title = post.get('title', '')
        selftext = post.get('selftext', '')
        subreddit = post.get('subreddit', '')
        num_comments = post.get('num_comments', 0)
        score = post.get('score', 0)

        posts_lines.append(f"\n---\n## POST {i} | r/{subreddit} | {num_comments} comments | score: {score}")
        posts_lines.append(f"**Title:** {title}")
        if selftext:
            # Include substantial selftext - this is the raw data
            posts_lines.append(f"\n{selftext[:1000]}")
            if len(selftext) > 1000:
                posts_lines.append("[truncated]")
        else:
            posts_lines.append("*[no body text]*")
        posts_lines.append("")

    posts_text = "\n".join(posts_lines)
    post_count = min(len(raw_posts), 25)

    return PROMPT_C.format(
        post_count=post_count,
        topic_area=topic_area,
        posts_text=posts_text
    )


def get_unclustered_posts_sample(cluster_data: dict, sample_size: int = 25) -> list:
    """Extract raw posts from cluster for unclustered analysis."""
    # Get posts with content, sorted by engagement
    posts = cluster_data.get('raw_posts', [])

    # Sort by num_comments (proxy for engagement)
    posts_with_content = [p for p in posts if len(p.get('selftext', '')) > 50]
    posts_with_content.sort(key=lambda x: x.get('num_comments', 0), reverse=True)

    # Mix: top engaged + random sample for diversity
    top_posts = posts_with_content[:sample_size // 2]
    remaining = [p for p in posts_with_content if p not in top_posts]

    import random
    random_sample = random.sample(remaining, min(len(remaining), sample_size - len(top_posts)))

    return top_posts + random_sample


if __name__ == "__main__":
    # Test with sample data
    import json
    with open('test_clusters.json') as f:
        data = json.load(f)

    cluster = data['clusters'][0]
    posts = get_unclustered_posts_sample(cluster)
    prompt = format_prompt_c(posts, topic_area="cognitive psychology")
    print(prompt[:3000])
    print("...")
    print(f"\nTotal prompt length: {len(prompt)} chars")
