#!/usr/bin/env python3
"""
Formatter — Convert ranked signals into a Telegram-friendly brief.
Max 10 bullets, under 300 words, with design prompt.
"""

from typing import List, Dict
from datetime import datetime


def create_telegram_brief(signals: List[Dict]) -> str:
    """
    Format top signals into a Telegram brief.
    Args:
        signals: List of ranked signal dicts
    Returns:
        Formatted brief string (< 300 words)
    """
    brief_lines = [
        "🔍 **Daily Research Brief**",
        f"*{datetime.now().strftime('%A, %B %d')}*\n"
    ]
    
    # Build bullet points (max 10)
    niche_coverage = set()
    for idx, signal in enumerate(signals[:10], 1):
        niche = signal.get("niche", "Unknown")
        title = signal.get("title", "")
        
        # Shorten title if needed
        if len(title) > 60:
            title = title[:57] + "..."
        
        # Determine why it matters based on source
        source = signal.get("source", "")
        engagement = signal.get("engagement", 0)
        
        if source == "reddit" and engagement > 50:
            why_matters = "Strong community interest"
        elif source == "brave":
            why_matters = "Trending in search"
        elif source == "youtube":
            why_matters = "Creator focus area"
        else:
            why_matters = "Emerging trend"
        
        brief_lines.append(
            f"🔥 {niche} — {title} — {why_matters}"
        )
        niche_coverage.add(niche)
    
    # Add separator and design prompt
    brief_lines.append("")
    
    # Generate top design prompt from highest-ranked signal
    if signals:
        top_signal = signals[0]
        top_niche = top_signal.get("niche", "")
        top_title = top_signal.get("title", "")
        
        # Create a Gemini-ready design prompt based on top signal
        design_prompt = generate_design_prompt(top_niche, top_title)
        brief_lines.append(f"📊 **Top Design Prompt:**")
        brief_lines.append(f"*{design_prompt}*")
    
    # Join and ensure under 300 words
    brief_text = "\n".join(brief_lines)
    
    # Count words (rough approximation)
    word_count = len(brief_text.split())
    
    if word_count > 300:
        # Truncate if needed
        words = brief_text.split()
        brief_text = " ".join(words[:300]) + "..."
    
    return brief_text


def generate_design_prompt(niche: str, topic: str) -> str:
    """
    Generate a Gemini-ready image design prompt based on trending topic.
    """
    # Clean topic string
    topic = topic.replace("trending", "").replace("2026", "").strip()
    
    niche_templates = {
        "USMC / Military": f"Military-inspired t-shirt design featuring {topic}. Minimalist aesthetic, military color palette (OD green, tan, black). Suitable for veteran apparel.",
        "Military Family": f"Military family pride design: {topic}. Heartfelt, supportive tone. Family-friendly apparel design.",
        "Reformed Christian": f"Reformed theology t-shirt: {topic}. Elegant, theologically-grounded. Coram Deo aesthetic.",
        "Patriotic": f"Patriotic apparel design: {topic}. American values theme. Professional merchandise quality.",
        "Print on Demand": f"Trending POD design concept: {topic}. Modern, scalable design. TikTok/Etsy viral potential.",
        "AI Services / Small Business": f"Small business automation concept: {topic}. Clean, professional design for business audience."
    }
    
    return niche_templates.get(
        niche,
        f"T-shirt design: {topic}. Modern, trending aesthetic. Merchandise-ready."
    )


if __name__ == "__main__":
    # Test with mock signals
    test_signals = [
        {
            "source": "reddit",
            "niche": "USMC / Military",
            "title": "Marine Corps meme designs trending",
            "engagement": 150,
            "score": 150
        },
        {
            "source": "brave",
            "niche": "Reformed Christian",
            "title": "Presbyterian church social media growth",
            "engagement": 0,
            "score": 0
        }
    ]
    
    brief = create_telegram_brief(test_signals)
    print(brief)
    print(f"\nWord count: {len(brief.split())}")
