"""
Trend Intelligence Service - Advanced analytics for TrendRadar module.

Features:
- Trending creators detection (fastest growing)
- Niche-specific trend radar
- Trend saturation warning
- Trend timeline (birth -> peak -> decline)
- Content format trending analysis
- Best time prediction per content type
- Best platform prediction
- Cross-platform pattern detection
- Trend alerts system
- Sentiment-enhanced trend scoring
"""

import logging
from datetime import datetime, timedelta
from collections import Counter, defaultdict

from sqlalchemy import func, desc, and_, or_, String
from sqlalchemy.orm import Session

from backend.models.video import Video
from backend.models.creator import Creator

logger = logging.getLogger(__name__)


# ── Trending Creators ──────────────────────────────────────────

def get_trending_creators(db: Session, days: int = 7, limit: int = 20,
                          platform: str = "", min_videos: int = 2) -> list[dict]:
    """
    Find creators with fastest growth: most viral videos recently.
    Ranked by sum of viral scores of their recent videos.
    """
    since = datetime.utcnow() - timedelta(days=days)

    query = db.query(
        Creator.id,
        Creator.username,
        Creator.platform,
        Creator.followers,
        Creator.avg_views,
        Creator.size_tier,
        Creator.avatar_url,
        func.count(Video.id).label("video_count"),
        func.sum(Video.viral_score).label("total_score"),
        func.avg(Video.viral_score).label("avg_score"),
        func.max(Video.viral_score).label("best_score"),
        func.sum(Video.views).label("total_views"),
    ).join(Video, Video.creator_id == Creator.id).filter(
        Video.collected_at >= since,
    )

    if platform:
        query = query.filter(Creator.platform == platform)

    results = query.group_by(Creator.id).having(
        func.count(Video.id) >= min_videos
    ).order_by(desc("total_score")).limit(limit).all()

    creators = []
    for r in results:
        creators.append({
            "id": r.id,
            "username": r.username,
            "platform": r.platform,
            "followers": r.followers or 0,
            "size_tier": r.size_tier or "unknown",
            "avatar_url": r.avatar_url or "",
            "video_count": r.video_count,
            "total_score": round(r.total_score or 0, 1),
            "avg_score": round(r.avg_score or 0, 1),
            "best_score": round(r.best_score or 0, 1),
            "total_views": r.total_views or 0,
        })

    return creators


# ── Niche-Specific Trend Radar ─────────────────────────────────

NICHES = {
    "construcao_ia": ["ai house", "ai construction", "ai mansion", "casa ia", "construcao ia", "sora house"],
    "construcao": ["construcao", "construction", "obra", "building", "house build"],
    "beleza": ["beleza", "beauty", "skincare", "maquiagem", "makeup"],
    "fitness": ["fitness", "treino", "workout", "gym", "academia"],
    "moda": ["moda", "fashion", "outfit", "look", "style"],
    "tech": ["tech", "tecnologia", "gadget", "smartphone", "setup"],
    "receitas": ["receita", "recipe", "cooking", "food", "comida"],
    "humor": ["humor", "funny", "comedy", "meme", "challenge"],
    "educacao": ["educacao", "tutorial", "como fazer", "how to", "dica"],
    "decoracao": ["decoracao", "decor", "home decor", "interior"],
    "lifestyle": ["lifestyle", "rotina", "routine", "vlog", "daily"],
    "financas": ["financas", "investimento", "money", "renda", "crypto"],
}


def get_niche_trends(db: Session, niche: str = "", days: int = 7,
                     platform: str = "") -> dict:
    """
    Get trend data for a specific niche or all niches.
    Returns video count, avg score, growth, top hashtags per niche.
    """
    since = datetime.utcnow() - timedelta(days=days)
    prev_since = since - timedelta(days=days)

    niches_to_check = {niche: NICHES[niche]} if niche and niche in NICHES else NICHES

    results = {}
    for niche_name, keywords in niches_to_check.items():
        # Build filter conditions
        conditions = []
        for kw in keywords:
            conditions.append(Video.title.ilike(f"%{kw}%"))
            conditions.append(Video.description.ilike(f"%{kw}%"))
            conditions.append(Video.hashtags.cast(String).ilike(f"%{kw}%"))

        # Current period
        q = db.query(
            func.count(Video.id),
            func.avg(Video.viral_score),
            func.sum(Video.views),
            func.avg(Video.views),
        ).filter(
            Video.collected_at >= since,
            or_(*conditions),
        )
        if platform:
            q = q.filter(Video.platform == platform)
        current = q.first()

        # Previous period (for growth)
        q_prev = db.query(func.count(Video.id)).filter(
            Video.collected_at >= prev_since,
            Video.collected_at < since,
            or_(*conditions),
        )
        if platform:
            q_prev = q_prev.filter(Video.platform == platform)
        prev_count = q_prev.scalar() or 0

        count = current[0] or 0
        growth = 0
        if prev_count > 0:
            growth = round(((count - prev_count) / prev_count) * 100, 1)
        elif count > 0:
            growth = 100.0

        # Top hashtags for this niche
        niche_videos = db.query(Video.hashtags).filter(
            Video.collected_at >= since,
            or_(*conditions),
        ).limit(100).all()

        hashtag_counter = Counter()
        for (tags,) in niche_videos:
            if tags:
                for t in (tags if isinstance(tags, list) else []):
                    t = str(t).strip().strip("#").lower()
                    if t and len(t) > 1:
                        hashtag_counter[t] += 1

        results[niche_name] = {
            "video_count": count,
            "avg_score": round(current[1] or 0, 1),
            "total_views": current[2] or 0,
            "avg_views": round(current[3] or 0),
            "growth_percent": growth,
            "top_hashtags": hashtag_counter.most_common(10),
            "status": "hot" if growth > 50 else "growing" if growth > 10 else "stable" if growth >= 0 else "declining",
        }

    return results


# ── Trend Saturation Warning ──────────────────────────────────

def check_saturation(db: Session, keyword: str, days: int = 14) -> dict:
    """
    Check if a trend/keyword is saturated.
    High saturation = too many videos, declining engagement.
    """
    since = datetime.utcnow() - timedelta(days=days)
    mid_point = since + timedelta(days=days // 2)

    conditions = [
        Video.title.ilike(f"%{keyword}%"),
        Video.description.ilike(f"%{keyword}%"),
        Video.hashtags.cast(String).ilike(f"%{keyword}%"),
    ]

    # First half metrics
    first_half = db.query(
        func.count(Video.id),
        func.avg(Video.viral_score),
        func.avg(Video.engagement_rate),
    ).filter(
        Video.collected_at >= since,
        Video.collected_at < mid_point,
        or_(*conditions),
    ).first()

    # Second half metrics
    second_half = db.query(
        func.count(Video.id),
        func.avg(Video.viral_score),
        func.avg(Video.engagement_rate),
    ).filter(
        Video.collected_at >= mid_point,
        or_(*conditions),
    ).first()

    first_count = first_half[0] or 0
    second_count = second_half[0] or 0
    first_score = first_half[1] or 0
    second_score = second_half[1] or 0
    first_eng = first_half[2] or 0
    second_eng = second_half[2] or 0

    # Saturation indicators
    volume_growing = second_count > first_count * 1.2
    score_declining = second_score < first_score * 0.8
    engagement_declining = second_eng < first_eng * 0.8

    if volume_growing and (score_declining or engagement_declining):
        saturation = 90
        warning = "SATURADO - Muitos videos, engagement caindo. Mude o angulo ou espere."
    elif volume_growing and second_score < first_score:
        saturation = 70
        warning = "Quase saturado - Volume alto, scores diminuindo. Inove no formato."
    elif score_declining:
        saturation = 60
        warning = "Scores caindo - O publico pode estar cansando deste tema."
    elif volume_growing:
        saturation = 40
        warning = "Crescendo rapido - Ainda ha espaco mas entre logo."
    else:
        saturation = 20
        warning = "Baixa saturacao - Boa oportunidade para entrar agora."

    return {
        "keyword": keyword,
        "saturation_score": saturation,
        "warning": warning,
        "metrics": {
            "first_half": {"count": first_count, "avg_score": round(first_score, 1), "avg_engagement": round(first_eng, 2)},
            "second_half": {"count": second_count, "avg_score": round(second_score, 1), "avg_engagement": round(second_eng, 2)},
        },
        "label": "Saturado" if saturation >= 70 else "Alerta" if saturation >= 50 else "Oportunidade",
    }


# ── Trend Timeline ─────────────────────────────────────────────

def get_trend_timeline(db: Session, keyword: str, days: int = 30) -> dict:
    """
    Build a timeline showing trend birth → growth → peak → decline.
    Returns daily video counts and avg scores.
    """
    since = datetime.utcnow() - timedelta(days=days)

    conditions = [
        Video.title.ilike(f"%{keyword}%"),
        Video.description.ilike(f"%{keyword}%"),
        Video.hashtags.cast(String).ilike(f"%{keyword}%"),
    ]

    videos = db.query(
        Video.collected_at,
        Video.viral_score,
        Video.views,
    ).filter(
        Video.collected_at >= since,
        or_(*conditions),
    ).order_by(Video.collected_at).all()

    if not videos:
        return {"keyword": keyword, "timeline": [], "phase": "unknown", "days_analyzed": days}

    # Group by day
    daily = defaultdict(lambda: {"count": 0, "total_score": 0, "total_views": 0})
    for v in videos:
        day = v.collected_at.strftime("%Y-%m-%d") if v.collected_at else "unknown"
        daily[day]["count"] += 1
        daily[day]["total_score"] += v.viral_score or 0
        daily[day]["total_views"] += v.views or 0

    timeline = []
    for day in sorted(daily.keys()):
        d = daily[day]
        timeline.append({
            "date": day,
            "video_count": d["count"],
            "avg_score": round(d["total_score"] / d["count"], 1) if d["count"] > 0 else 0,
            "total_views": d["total_views"],
        })

    # Determine current phase
    if len(timeline) >= 3:
        recent = timeline[-3:]
        earlier = timeline[:3] if len(timeline) >= 6 else timeline[:1]
        recent_avg = sum(t["video_count"] for t in recent) / len(recent)
        earlier_avg = sum(t["video_count"] for t in earlier) / len(earlier)

        if recent_avg > earlier_avg * 1.5:
            phase = "growing"
        elif recent_avg < earlier_avg * 0.5:
            phase = "declining"
        elif recent_avg >= earlier_avg * 0.8:
            phase = "peak"
        else:
            phase = "emerging"
    else:
        phase = "emerging"

    return {
        "keyword": keyword,
        "timeline": timeline,
        "phase": phase,
        "total_videos": sum(d["video_count"] for d in timeline),
        "days_analyzed": days,
    }


# ── Content Format Trending Analysis ───────────────────────────

FORMAT_KEYWORDS = {
    "tutorial": ["tutorial", "como fazer", "how to", "passo a passo", "step by step"],
    "pov": ["pov", "point of view"],
    "challenge": ["challenge", "desafio"],
    "timelapse": ["timelapse", "time lapse", "speed build"],
    "before_after": ["antes depois", "before after", "transformacao", "transformation"],
    "review": ["review", "resenha", "testei", "vale a pena"],
    "unboxing": ["unboxing", "abrindo", "haul"],
    "storytime": ["storytime", "historia", "story"],
    "reaction": ["reacao", "react", "reaction"],
    "asmr_satisfying": ["asmr", "satisfying", "satisfatorio", "oddly satisfying"],
    "ranking": ["top", "ranking", "melhor", "best", "worst"],
    "grwm": ["grwm", "get ready with me", "arrume-se comigo"],
}


def analyze_format_trends(db: Session, days: int = 7, platform: str = "") -> dict:
    """
    Analyze which video formats are trending.
    Returns format ranking with growth and performance metrics.
    """
    since = datetime.utcnow() - timedelta(days=days)
    prev_since = since - timedelta(days=days)

    q = db.query(Video).filter(Video.collected_at >= since)
    if platform:
        q = q.filter(Video.platform == platform)
    videos = q.all()

    q_prev = db.query(Video).filter(Video.collected_at >= prev_since, Video.collected_at < since)
    if platform:
        q_prev = q_prev.filter(Video.platform == platform)
    prev_videos = q_prev.all()

    # Classify videos by format
    def classify(vid_list):
        counts = Counter()
        scores = defaultdict(list)
        views = defaultdict(list)
        for v in vid_list:
            text = ((v.title or "") + " " + (v.description or "")).lower()
            matched = False
            for fmt, keywords in FORMAT_KEYWORDS.items():
                if any(kw in text for kw in keywords):
                    counts[fmt] += 1
                    scores[fmt].append(v.viral_score or 0)
                    views[fmt].append(v.views or 0)
                    matched = True
                    break
            if not matched:
                counts["other"] += 1
                scores["other"].append(v.viral_score or 0)
                views["other"].append(v.views or 0)
        return counts, scores, views

    current_counts, current_scores, current_views = classify(videos)
    prev_counts, _, _ = classify(prev_videos)

    formats = []
    for fmt in set(list(current_counts.keys()) + list(prev_counts.keys())):
        curr = current_counts.get(fmt, 0)
        prev = prev_counts.get(fmt, 0)
        growth = round(((curr - prev) / max(prev, 1)) * 100, 1)
        avg_score = round(sum(current_scores.get(fmt, [0])) / max(len(current_scores.get(fmt, [1])), 1), 1)
        avg_views = round(sum(current_views.get(fmt, [0])) / max(len(current_views.get(fmt, [1])), 1))

        formats.append({
            "format": fmt,
            "video_count": curr,
            "prev_count": prev,
            "growth_percent": growth,
            "avg_score": avg_score,
            "avg_views": avg_views,
            "status": "hot" if growth > 50 else "growing" if growth > 10 else "stable" if growth >= 0 else "declining",
        })

    formats.sort(key=lambda x: x["growth_percent"], reverse=True)
    return {"formats": formats, "total_videos": len(videos), "period_days": days}


# ── Best Time Prediction ───────────────────────────────────────

def predict_best_time(db: Session, days: int = 14, platform: str = "",
                      niche: str = "") -> dict:
    """
    Predict best posting time based on when high-scoring videos were published.
    Returns hour-by-hour and day-of-week performance.
    """
    since = datetime.utcnow() - timedelta(days=days)

    q = db.query(Video).filter(
        Video.collected_at >= since,
        Video.published_at.isnot(None),
        Video.viral_score > 0,
    )
    if platform:
        q = q.filter(Video.platform == platform)

    if niche and niche in NICHES:
        conditions = []
        for kw in NICHES[niche]:
            conditions.append(Video.title.ilike(f"%{kw}%"))
            conditions.append(Video.hashtags.cast(String).ilike(f"%{kw}%"))
        q = q.filter(or_(*conditions))

    videos = q.all()

    if not videos:
        return {"best_hour": 19, "best_day": "quinta", "hours": {}, "days": {}}

    hour_data = defaultdict(lambda: {"count": 0, "total_score": 0, "total_views": 0})
    day_data = defaultdict(lambda: {"count": 0, "total_score": 0, "total_views": 0})

    for v in videos:
        if v.published_at:
            h = v.published_at.hour
            d = v.published_at.strftime("%A")
            hour_data[h]["count"] += 1
            hour_data[h]["total_score"] += v.viral_score or 0
            hour_data[h]["total_views"] += v.views or 0
            day_data[d]["count"] += 1
            day_data[d]["total_score"] += v.viral_score or 0
            day_data[d]["total_views"] += v.views or 0

    # Build hour rankings
    hours = {}
    for h in range(24):
        d = hour_data.get(h, {"count": 0, "total_score": 0, "total_views": 0})
        hours[h] = {
            "count": d["count"],
            "avg_score": round(d["total_score"] / d["count"], 1) if d["count"] > 0 else 0,
            "avg_views": round(d["total_views"] / d["count"]) if d["count"] > 0 else 0,
        }

    # Best hour by avg score
    best_hour = max(hours.items(), key=lambda x: x[1]["avg_score"])[0] if hours else 19

    # Build day rankings
    day_names_pt = {
        "Monday": "segunda", "Tuesday": "terca", "Wednesday": "quarta",
        "Thursday": "quinta", "Friday": "sexta", "Saturday": "sabado", "Sunday": "domingo",
    }
    days = {}
    for eng_name, pt_name in day_names_pt.items():
        d = day_data.get(eng_name, {"count": 0, "total_score": 0, "total_views": 0})
        days[pt_name] = {
            "count": d["count"],
            "avg_score": round(d["total_score"] / d["count"], 1) if d["count"] > 0 else 0,
        }

    best_day = max(days.items(), key=lambda x: x[1]["avg_score"])[0] if days else "quinta"

    return {
        "best_hour": best_hour,
        "best_day": best_day,
        "hours": hours,
        "days": days,
        "total_analyzed": len(videos),
        "recommendation": f"Poste as {best_hour}:00 na {best_day}-feira para melhor performance",
    }


# ── Best Platform Prediction ──────────────────────────────────

def predict_best_platform(db: Session, keyword: str = "", days: int = 14) -> dict:
    """
    Predict which platform a topic/keyword performs best on.
    """
    since = datetime.utcnow() - timedelta(days=days)

    platforms_data = {}
    for plat in ["tiktok", "youtube", "instagram"]:
        q = db.query(
            func.count(Video.id),
            func.avg(Video.viral_score),
            func.avg(Video.views),
            func.avg(Video.engagement_rate),
        ).filter(
            Video.collected_at >= since,
            Video.platform == plat,
        )

        if keyword:
            conditions = [
                Video.title.ilike(f"%{keyword}%"),
                Video.description.ilike(f"%{keyword}%"),
                Video.hashtags.cast(String).ilike(f"%{keyword}%"),
            ]
            q = q.filter(or_(*conditions))

        result = q.first()
        platforms_data[plat] = {
            "video_count": result[0] or 0,
            "avg_score": round(result[1] or 0, 1),
            "avg_views": round(result[2] or 0),
            "avg_engagement": round(result[3] or 0, 2),
        }

    # Rank platforms
    best = max(platforms_data.items(), key=lambda x: x[1]["avg_score"])

    return {
        "keyword": keyword or "all",
        "platforms": platforms_data,
        "best_platform": best[0],
        "recommendation": f"Melhor plataforma: {best[0].title()} (score medio: {best[1]['avg_score']})",
    }


# ── Cross-Platform Pattern Detection ──────────────────────────

def detect_cross_platform(db: Session, days: int = 7, min_platforms: int = 2) -> list[dict]:
    """
    Find hashtags/keywords that are trending on multiple platforms simultaneously.
    These are the strongest trends.
    """
    since = datetime.utcnow() - timedelta(days=days)

    videos = db.query(Video.platform, Video.hashtags, Video.viral_score).filter(
        Video.collected_at >= since,
        Video.viral_score >= 30,
    ).all()

    # Count hashtags per platform
    platform_tags = defaultdict(lambda: defaultdict(lambda: {"count": 0, "total_score": 0}))

    for plat, tags, score in videos:
        if not tags:
            continue
        for t in (tags if isinstance(tags, list) else []):
            t = str(t).strip().strip("#").lower()
            if t and len(t) > 2:
                platform_tags[t][plat]["count"] += 1
                platform_tags[t][plat]["total_score"] += score or 0

    # Find cross-platform trends
    cross_trends = []
    for tag, platforms in platform_tags.items():
        if len(platforms) >= min_platforms:
            total_count = sum(p["count"] for p in platforms.values())
            total_score = sum(p["total_score"] for p in platforms.values())
            avg_score = total_score / total_count if total_count > 0 else 0

            cross_trends.append({
                "hashtag": tag,
                "platforms": {k: v["count"] for k, v in platforms.items()},
                "platform_count": len(platforms),
                "total_videos": total_count,
                "avg_score": round(avg_score, 1),
            })

    cross_trends.sort(key=lambda x: (x["platform_count"], x["total_videos"]), reverse=True)
    return cross_trends[:30]


# ── Trend Alerts ───────────────────────────────────────────────

def get_trend_alerts(db: Session, hours: int = 24) -> list[dict]:
    """
    Generate alerts for significant trend movements:
    - New emerging trends (first seen < 24h)
    - Exploding trends (growth > 200%)
    - Saturating trends (high volume + declining engagement)
    - Cross-platform trends
    """
    since = datetime.utcnow() - timedelta(hours=hours)
    alerts = []

    # 1. New high-scoring videos from small creators (opportunities)
    new_virals = db.query(Video).filter(
        Video.collected_at >= since,
        Video.viral_score >= 60,
        Video.is_small_creator == True,
    ).order_by(desc(Video.viral_score)).limit(5).all()

    for v in new_virals:
        alerts.append({
            "type": "opportunity",
            "priority": "high",
            "icon": "target",
            "title": f"Oportunidade: video viral de criador pequeno",
            "detail": f"{v.title[:60]}... Score: {v.viral_score}",
            "video_id": v.id,
            "timestamp": v.collected_at.isoformat() if v.collected_at else None,
        })

    # 2. Explosion detection (very high outlier)
    explosions = db.query(Video).filter(
        Video.collected_at >= since,
        Video.outlier_ratio >= 20,
    ).order_by(desc(Video.outlier_ratio)).limit(3).all()

    for v in explosions:
        alerts.append({
            "type": "explosion",
            "priority": "urgent",
            "icon": "zap",
            "title": f"Explosao detectada: {v.outlier_ratio:.0f}x acima da media",
            "detail": f"{v.title[:60]}... ({v.views:,} views)",
            "video_id": v.id,
            "timestamp": v.collected_at.isoformat() if v.collected_at else None,
        })

    # 3. Cross-platform trends
    cross = detect_cross_platform(db, days=3, min_platforms=2)
    for ct in cross[:3]:
        plats = ", ".join(ct["platforms"].keys())
        alerts.append({
            "type": "cross_platform",
            "priority": "medium",
            "icon": "globe",
            "title": f"Trend cross-platform: #{ct['hashtag']}",
            "detail": f"Aparecendo em {plats} ({ct['total_videos']} videos, score {ct['avg_score']})",
            "hashtag": ct["hashtag"],
            "timestamp": datetime.utcnow().isoformat(),
        })

    # Sort by priority
    priority_order = {"urgent": 0, "high": 1, "medium": 2, "low": 3}
    alerts.sort(key=lambda a: priority_order.get(a["priority"], 99))

    return alerts


# ── Micro-Trend Early Detection ──────────────────────────────

def detect_micro_trends(db: Session, hours: int = 48, min_videos: int = 3) -> list[dict]:
    """
    Detect micro-trends: hashtags/topics appearing for the first time recently
    that already show strong engagement. These are the earliest opportunities.
    """
    since = datetime.utcnow() - timedelta(hours=hours)
    before = since - timedelta(days=30)  # 30-day lookback

    # Get recent hashtags
    recent_videos = db.query(Video.hashtags, Video.viral_score, Video.views, Video.platform).filter(
        Video.collected_at >= since,
    ).all()

    # Get historical hashtags (what existed before)
    historical_tags = set()
    historical_vids = db.query(Video.hashtags).filter(
        Video.collected_at >= before,
        Video.collected_at < since,
    ).limit(5000).all()
    for (tags,) in historical_vids:
        if tags:
            for t in (tags if isinstance(tags, list) else []):
                historical_tags.add(str(t).strip().strip("#").lower())

    # Count new hashtags
    new_tags = defaultdict(lambda: {"count": 0, "total_score": 0, "total_views": 0, "platforms": set()})
    for tags, score, views, platform in recent_videos:
        if not tags:
            continue
        for t in (tags if isinstance(tags, list) else []):
            t = str(t).strip().strip("#").lower()
            if t and len(t) > 2 and t not in historical_tags:
                nt = new_tags[t]
                nt["count"] += 1
                nt["total_score"] += score or 0
                nt["total_views"] += views or 0
                nt["platforms"].add(platform)

    # Filter: must have minimum videos and decent scores
    micro_trends = []
    for tag, data in new_tags.items():
        if data["count"] >= min_videos:
            avg_score = data["total_score"] / data["count"]
            micro_trends.append({
                "hashtag": tag,
                "video_count": data["count"],
                "avg_score": round(avg_score, 1),
                "total_views": data["total_views"],
                "platforms": list(data["platforms"]),
                "platform_count": len(data["platforms"]),
                "is_cross_platform": len(data["platforms"]) >= 2,
                "potential": "alto" if avg_score >= 50 and data["count"] >= 5 else "medio" if avg_score >= 30 else "baixo",
            })

    micro_trends.sort(key=lambda x: x["avg_score"] * x["video_count"], reverse=True)
    return micro_trends[:30]


# ── Platform Algorithm Change Detection ──────────────────────

def detect_algorithm_changes(db: Session, days: int = 14) -> dict:
    """
    Detect potential algorithm changes by analyzing shifts in engagement patterns.
    Sudden changes in avg engagement, viral score distribution, or video performance
    can indicate an algorithm update.
    """
    now = datetime.utcnow()
    periods = []

    # Compare 4 periods of equal length
    period_days = days // 4 or 1
    for i in range(4):
        start = now - timedelta(days=period_days * (i + 1))
        end = now - timedelta(days=period_days * i)

        for platform in ["tiktok", "youtube", "instagram"]:
            stats = db.query(
                func.count(Video.id),
                func.avg(Video.viral_score),
                func.avg(Video.engagement_rate),
                func.avg(Video.views),
                func.avg(Video.likes),
            ).filter(
                Video.collected_at >= start,
                Video.collected_at < end,
                Video.platform == platform,
            ).first()

            periods.append({
                "platform": platform,
                "period": i,
                "period_label": f"Periodo {i+1} ({period_days*(i+1)}-{period_days*i}d atras)",
                "video_count": stats[0] or 0,
                "avg_score": round(float(stats[1] or 0), 1),
                "avg_engagement": round(float(stats[2] or 0), 3),
                "avg_views": round(float(stats[3] or 0)),
                "avg_likes": round(float(stats[4] or 0)),
            })

    # Detect anomalies per platform
    anomalies = []
    for platform in ["tiktok", "youtube", "instagram"]:
        plat_periods = [p for p in periods if p["platform"] == platform and p["video_count"] > 5]
        if len(plat_periods) < 2:
            continue

        # Compare most recent vs previous
        latest = plat_periods[0]
        prev = plat_periods[1]

        if prev["avg_score"] > 0:
            score_change = ((latest["avg_score"] - prev["avg_score"]) / prev["avg_score"]) * 100
            if abs(score_change) > 20:
                anomalies.append({
                    "platform": platform,
                    "type": "score_shift",
                    "change_percent": round(score_change, 1),
                    "direction": "up" if score_change > 0 else "down",
                    "description": f"Viral score medio {'subiu' if score_change > 0 else 'caiu'} {abs(score_change):.0f}% no {platform.title()}",
                    "possible_cause": "Possivel mudanca no algoritmo de distribuicao" if abs(score_change) > 30 else "Flutuacao significativa",
                })

        if prev["avg_engagement"] > 0:
            eng_change = ((latest["avg_engagement"] - prev["avg_engagement"]) / prev["avg_engagement"]) * 100
            if abs(eng_change) > 25:
                anomalies.append({
                    "platform": platform,
                    "type": "engagement_shift",
                    "change_percent": round(eng_change, 1),
                    "direction": "up" if eng_change > 0 else "down",
                    "description": f"Engagement medio {'subiu' if eng_change > 0 else 'caiu'} {abs(eng_change):.0f}% no {platform.title()}",
                    "possible_cause": "Algoritmo pode estar priorizando diferente tipo de conteudo",
                })

    return {
        "periods": periods,
        "anomalies": anomalies,
        "has_changes": len(anomalies) > 0,
        "days_analyzed": days,
        "recommendation": "Mudancas detectadas! Ajuste sua estrategia." if anomalies else "Nenhuma mudanca significativa detectada.",
    }


# ── Music/Sound Pattern Analysis ─────────────────────────────

def analyze_music_patterns(db: Session, days: int = 7, platform: str = "") -> dict:
    """
    Analyze music/sound patterns in viral videos.
    Since we don't have direct audio analysis, we use title/hashtag signals.
    """
    since = datetime.utcnow() - timedelta(days=days)

    query = db.query(Video).filter(
        Video.collected_at >= since,
        Video.viral_score >= 30,
    )
    if platform:
        query = query.filter(Video.platform == platform)

    videos = query.limit(500).all()

    # Music-related patterns from titles and hashtags
    music_keywords = {
        "trending_sound": ["trending sound", "som viral", "audio viral", "sound viral"],
        "original_sound": ["som original", "original sound", "original audio"],
        "remix": ["remix", "mashup", "edit"],
        "asmr": ["asmr", "satisfying"],
        "music_genre_funk": ["funk", "funknejo"],
        "music_genre_sertanejo": ["sertanejo", "modao"],
        "music_genre_pop": ["pop", "kpop", "k-pop"],
        "music_genre_trap": ["trap", "rap", "hip hop"],
        "music_genre_electronic": ["edm", "electronic", "house", "techno"],
        "music_genre_reggaeton": ["reggaeton", "perreo", "latino"],
    }

    sound_stats = defaultdict(lambda: {"count": 0, "total_score": 0, "total_views": 0, "examples": []})
    commerce_music_count = 0

    for v in videos:
        text = ((v.title or "") + " " + str(v.hashtags or "")).lower()

        if v.is_commerce_music:
            commerce_music_count += 1

        for pattern, keywords in music_keywords.items():
            if any(kw in text for kw in keywords):
                s = sound_stats[pattern]
                s["count"] += 1
                s["total_score"] += v.viral_score or 0
                s["total_views"] += v.views or 0
                if len(s["examples"]) < 3:
                    s["examples"].append({
                        "title": v.title[:50] if v.title else "",
                        "views": v.views,
                        "score": v.viral_score,
                    })

    patterns = []
    for pattern, data in sound_stats.items():
        if data["count"] > 0:
            patterns.append({
                "pattern": pattern,
                "label": pattern.replace("_", " ").title(),
                "video_count": data["count"],
                "avg_score": round(data["total_score"] / data["count"], 1),
                "total_views": data["total_views"],
                "examples": data["examples"],
            })

    patterns.sort(key=lambda x: x["video_count"], reverse=True)

    return {
        "patterns": patterns,
        "total_analyzed": len(videos),
        "commerce_music_count": commerce_music_count,
        "commerce_music_pct": round((commerce_music_count / max(len(videos), 1)) * 100, 1),
        "top_pattern": patterns[0]["pattern"] if patterns else "unknown",
        "recommendation": _music_recommendation(patterns),
    }


def _music_recommendation(patterns: list) -> str:
    if not patterns:
        return "Sem dados suficientes sobre padroes musicais."
    top = patterns[0]
    if "trending_sound" in top["pattern"]:
        return "Sons trending estao dominando! Use audios virais para maior alcance."
    if "original" in top["pattern"]:
        return "Sons originais estao em alta. Crie seu proprio audio unico."
    if "genre" in top["pattern"]:
        genre = top["label"]
        return f"{genre} e o genero mais popular. Use esse estilo nos seus videos."
    return f"Padrao mais comum: {top['label']}. Incorpore nos seus videos."


# ── Global Trend Map by Country ──────────────────────────────

def get_global_trend_map(db: Session, days: int = 7) -> dict:
    """
    Build a global map of trends by country/region.
    Uses video region and language data.
    """
    since = datetime.utcnow() - timedelta(days=days)

    # Aggregate by region
    region_data = db.query(
        Video.region,
        func.count(Video.id),
        func.avg(Video.viral_score),
        func.sum(Video.views),
        func.avg(Video.engagement_rate),
    ).filter(
        Video.collected_at >= since,
        Video.region != "",
        Video.region.isnot(None),
    ).group_by(Video.region).all()

    regions = []
    for region, count, avg_score, total_views, avg_eng in region_data:
        if not region or count < 2:
            continue

        # Get top hashtags for this region
        tag_vids = db.query(Video.hashtags).filter(
            Video.collected_at >= since,
            Video.region == region,
        ).limit(50).all()

        tag_counter = Counter()
        for (tags,) in tag_vids:
            if tags:
                for t in (tags if isinstance(tags, list) else []):
                    t = str(t).strip().strip("#").lower()
                    if t and len(t) > 2:
                        tag_counter[t] += 1

        region_name = {
            "BR": "Brasil", "US": "Estados Unidos", "GB": "Reino Unido",
            "MX": "Mexico", "AR": "Argentina", "CO": "Colombia",
            "ES": "Espanha", "PT": "Portugal", "FR": "Franca",
            "DE": "Alemanha", "IT": "Italia", "IN": "India",
            "JP": "Japao", "KR": "Coreia do Sul", "ID": "Indonesia",
            "PH": "Filipinas", "TH": "Tailandia", "VN": "Vietna",
        }.get(region, region)

        regions.append({
            "code": region,
            "name": region_name,
            "video_count": count,
            "avg_score": round(float(avg_score or 0), 1),
            "total_views": int(total_views or 0),
            "avg_engagement": round(float(avg_eng or 0), 2),
            "top_hashtags": tag_counter.most_common(5),
        })

    regions.sort(key=lambda x: x["video_count"], reverse=True)

    # Language distribution
    lang_data = db.query(
        Video.language,
        func.count(Video.id),
        func.avg(Video.viral_score),
    ).filter(
        Video.collected_at >= since,
        Video.language != "",
        Video.language.isnot(None),
    ).group_by(Video.language).all()

    languages = []
    for lang, count, avg_score in lang_data:
        if not lang or count < 2:
            continue
        languages.append({
            "code": lang,
            "video_count": count,
            "avg_score": round(float(avg_score or 0), 1),
        })
    languages.sort(key=lambda x: x["video_count"], reverse=True)

    return {
        "regions": regions,
        "languages": languages,
        "total_regions": len(regions),
        "total_languages": len(languages),
    }


# ── STEPPS Virality Score ─────────────────────────────────────

def calculate_stepps_score(db: Session, keyword: str = "", hashtag: str = "",
                            days: int = 7) -> dict:
    """
    Calculate STEPPS virality score (Jonah Berger framework):
    Social Currency (15%), Triggers (15%), Emotion (20%), Public (15%),
    Practical Value (20%), Stories (15%).
    Uses VADER sentiment + pattern matching + cross-platform detection.
    """
    from backend.services.local_ai import analyze_sentiment_batch

    since = datetime.utcnow() - timedelta(days=days)
    search_term = keyword or hashtag or ""
    if not search_term:
        return {"error": "keyword ou hashtag obrigatorio", "score": 0}

    # Get matching videos
    conditions = [
        Video.title.ilike(f"%{search_term}%"),
        Video.description.ilike(f"%{search_term}%"),
        Video.hashtags.cast(String).ilike(f"%{search_term}%"),
    ]
    videos = (
        db.query(Video)
        .filter(Video.collected_at >= since, or_(*conditions))
        .limit(200)
        .all()
    )

    if not videos:
        return {"keyword": search_term, "score": 0, "breakdown": {}, "video_count": 0}

    titles = [v.title or "" for v in videos]

    # 1. Social Currency (15%) - exclusivity, status, insider knowledge
    social_keywords = ["secreto", "segredo", "ninguem sabe", "exclusivo", "first", "hack", "truque", "secret", "insider", "vip"]
    social_matches = sum(1 for t in titles if any(k in t.lower() for k in social_keywords))
    social_score = min((social_matches / max(len(videos), 1)) * 500, 100)

    # 2. Triggers (15%) - frequency, daily reminders, associations
    trigger_keywords = ["todo dia", "sempre", "toda vez", "rotina", "daily", "every day", "morning", "manha", "noite"]
    trigger_matches = sum(1 for t in titles if any(k in t.lower() for k in trigger_keywords))
    trigger_score = min((trigger_matches / max(len(videos), 1)) * 500, 100)

    # 3. Emotion (20%) - arousal, awe, anxiety, anger, humor
    sentiment = analyze_sentiment_batch(titles[:50])
    avg_compound = sentiment.get("average_compound", 0)
    emotion_intensity = abs(avg_compound) * 100
    emotion_score = min(emotion_intensity * 1.5, 100)

    # 4. Public (15%) - observable behavior, social proof
    avg_shares = sum(v.shares or 0 for v in videos) / max(len(videos), 1)
    avg_views = sum(v.views or 0 for v in videos) / max(len(videos), 1)
    public_ratio = avg_shares / max(avg_views, 1) * 10000
    public_score = min(public_ratio * 10, 100)

    # 5. Practical Value (20%) - usefulness, savings, tips
    practical_keywords = ["como", "how to", "dica", "tip", "tutorial", "aprenda", "facil", "rapido", "gratis", "free", "economize", "save"]
    practical_matches = sum(1 for t in titles if any(k in t.lower() for k in practical_keywords))
    practical_score = min((practical_matches / max(len(videos), 1)) * 400, 100)

    # 6. Stories (15%) - narrative, journey, transformation
    story_keywords = ["historia", "story", "jornada", "journey", "antes depois", "transformation", "transformacao", "comecei", "mudou", "changed"]
    story_matches = sum(1 for t in titles if any(k in t.lower() for k in story_keywords))
    story_score = min((story_matches / max(len(videos), 1)) * 500, 100)

    # Weighted total
    total = (
        social_score * 0.15 +
        trigger_score * 0.15 +
        emotion_score * 0.20 +
        public_score * 0.15 +
        practical_score * 0.20 +
        story_score * 0.15
    )

    # Cross-platform bonus
    platforms = set(v.platform for v in videos if v.platform)
    if len(platforms) >= 2:
        total = min(total * 1.1, 100)

    breakdown = {
        "social_currency": round(social_score, 1),
        "triggers": round(trigger_score, 1),
        "emotion": round(emotion_score, 1),
        "public": round(public_score, 1),
        "practical_value": round(practical_score, 1),
        "stories": round(story_score, 1),
    }

    label = "Altamente Viral" if total >= 70 else "Viral" if total >= 50 else "Potencial" if total >= 30 else "Baixo"

    return {
        "keyword": search_term,
        "score": round(total, 1),
        "label": label,
        "breakdown": breakdown,
        "video_count": len(videos),
        "platforms": list(platforms),
        "cross_platform_bonus": len(platforms) >= 2,
        "sentiment": sentiment,
        "days": days,
    }


# ── Revenue Prediction per Trend ─────────────────────────────

def predict_trend_revenue(db: Session, keyword: str = "", platform: str = "tiktok",
                           days: int = 14) -> dict:
    """
    Predict potential revenue from a trend using CPM/RPM by niche,
    affiliate estimation, and 30-day projection.
    """
    since = datetime.utcnow() - timedelta(days=days)

    conditions = [
        Video.title.ilike(f"%{keyword}%"),
        Video.description.ilike(f"%{keyword}%"),
        Video.hashtags.cast(String).ilike(f"%{keyword}%"),
    ]
    query = db.query(Video).filter(Video.collected_at >= since, or_(*conditions))
    if platform:
        query = query.filter(Video.platform == platform)
    videos = query.limit(200).all()

    if not videos:
        return {"keyword": keyword, "total_estimated": 0, "error": "Sem videos encontrados"}

    total_views = sum(v.views or 0 for v in videos)
    avg_views = total_views / max(len(videos), 1)
    total_engagement = sum((v.likes or 0) + (v.comments or 0) + (v.shares or 0) for v in videos)

    # CPM/RPM rates by niche (Brazilian market, BRL)
    niche_rates = {
        "tech": {"cpm": 8.0, "rpm": 12.0, "affiliate_rate": 0.05},
        "beleza": {"cpm": 6.0, "rpm": 10.0, "affiliate_rate": 0.08},
        "fitness": {"cpm": 5.0, "rpm": 8.0, "affiliate_rate": 0.06},
        "financas": {"cpm": 15.0, "rpm": 25.0, "affiliate_rate": 0.03},
        "educacao": {"cpm": 7.0, "rpm": 12.0, "affiliate_rate": 0.04},
        "default": {"cpm": 4.0, "rpm": 6.0, "affiliate_rate": 0.03},
    }

    # Detect niche from keyword
    detected_niche = "default"
    for niche in niche_rates:
        if niche != "default" and niche in keyword.lower():
            detected_niche = niche
            break

    rates = niche_rates[detected_niche]

    # Ad revenue estimation
    ad_revenue = (total_views / 1000) * rates["cpm"]

    # Creator fund estimation (platform-specific)
    platform_rpms = {"tiktok": 0.5, "youtube": 4.0, "instagram": 1.0}
    fund_rpm = platform_rpms.get(platform, 1.0)
    fund_revenue = (total_views / 1000) * fund_rpm

    # Affiliate estimation
    affiliate_revenue = total_engagement * rates["affiliate_rate"] * 50  # avg product R$50

    # 30-day projection (linear + momentum factor)
    daily_views = total_views / max(days, 1)
    momentum = 1.0
    # Check if trend is growing
    half = datetime.utcnow() - timedelta(days=days // 2)
    first_half = [v for v in videos if v.collected_at and v.collected_at < half]
    second_half = [v for v in videos if v.collected_at and v.collected_at >= half]
    if first_half and second_half:
        first_avg = sum(v.views or 0 for v in first_half) / max(len(first_half), 1)
        second_avg = sum(v.views or 0 for v in second_half) / max(len(second_half), 1)
        if first_avg > 0:
            momentum = min(second_avg / first_avg, 3.0)

    projected_30d_views = daily_views * 30 * momentum
    projected_ad = (projected_30d_views / 1000) * rates["cpm"]
    projected_total = projected_ad + (affiliate_revenue * (30 / max(days, 1)))

    return {
        "keyword": keyword,
        "platform": platform,
        "niche_detected": detected_niche,
        "days_analyzed": days,
        "video_count": len(videos),
        "total_views": total_views,
        "avg_views": round(avg_views),
        "revenue": {
            "ad_revenue": round(ad_revenue, 2),
            "fund_revenue": round(fund_revenue, 2),
            "affiliate_estimated": round(affiliate_revenue, 2),
            "total_current": round(ad_revenue + fund_revenue + affiliate_revenue, 2),
        },
        "projection_30d": {
            "momentum_factor": round(momentum, 2),
            "projected_views": round(projected_30d_views),
            "projected_revenue": round(projected_total, 2),
            "trend_direction": "growing" if momentum > 1.1 else "stable" if momentum > 0.9 else "declining",
        },
        "rates_used": rates,
    }


# ── Sentiment Virality Scoring ───────────────────────────────

def analyze_sentiment_virality(db: Session, keyword: str = "", days: int = 7) -> dict:
    """
    Analyze correlation between sentiment and viral performance.
    Uses VADER batch sentiment + correlation with viral_score.
    Returns emotional virality index.
    """
    from backend.services.local_ai import analyze_sentiment_batch, analyze_sentiment

    since = datetime.utcnow() - timedelta(days=days)
    conditions = [
        Video.title.ilike(f"%{keyword}%"),
        Video.description.ilike(f"%{keyword}%"),
        Video.hashtags.cast(String).ilike(f"%{keyword}%"),
    ]
    videos = (
        db.query(Video)
        .filter(Video.collected_at >= since, or_(*conditions))
        .order_by(desc(Video.viral_score))
        .limit(200)
        .all()
    )

    if not videos:
        return {"keyword": keyword, "emotional_virality_index": 0, "video_count": 0}

    # Analyze sentiment of each video title
    results = []
    for v in videos:
        sent = analyze_sentiment(v.title or "")
        results.append({
            "title": (v.title or "")[:60],
            "viral_score": v.viral_score or 0,
            "views": v.views or 0,
            "sentiment_compound": sent.get("compound", 0),
            "sentiment_label": sent.get("label", "neutral"),
        })

    # Group by sentiment
    positive = [r for r in results if r["sentiment_label"] == "positive"]
    negative = [r for r in results if r["sentiment_label"] == "negative"]
    neutral = [r for r in results if r["sentiment_label"] == "neutral"]

    avg_score_pos = sum(r["viral_score"] for r in positive) / max(len(positive), 1)
    avg_score_neg = sum(r["viral_score"] for r in negative) / max(len(negative), 1)
    avg_score_neu = sum(r["viral_score"] for r in neutral) / max(len(neutral), 1)

    # Emotional Virality Index: high-emotion content vs neutral
    emotional_avg = (avg_score_pos + avg_score_neg) / 2 if (positive or negative) else 0
    evi = ((emotional_avg - avg_score_neu) / max(avg_score_neu, 1)) * 100 if avg_score_neu > 0 else 0

    # Batch stats
    batch_sentiment = analyze_sentiment_batch([v.title or "" for v in videos[:50]])

    return {
        "keyword": keyword,
        "days": days,
        "video_count": len(videos),
        "emotional_virality_index": round(evi, 1),
        "evi_label": "Emocao amplifica" if evi > 20 else "Neutro" if evi > -10 else "Emocao reduz",
        "sentiment_distribution": {
            "positive": {"count": len(positive), "avg_viral_score": round(avg_score_pos, 1)},
            "negative": {"count": len(negative), "avg_viral_score": round(avg_score_neg, 1)},
            "neutral": {"count": len(neutral), "avg_viral_score": round(avg_score_neu, 1)},
        },
        "batch_sentiment": batch_sentiment,
        "top_viral_sentiments": sorted(results, key=lambda x: x["viral_score"], reverse=True)[:10],
    }


# ── Automated Weekly Report ──────────────────────────────────

async def generate_weekly_report(db: Session) -> dict:
    """
    Generate a comprehensive weekly trend report.
    Combines all intelligence into one summary.
    """
    # Gather all data
    niches = get_niche_trends(db, days=7)
    formats = analyze_format_trends(db, days=7)
    creators = get_trending_creators(db, days=7, limit=5)
    cross_platform = detect_cross_platform(db, days=7)
    alerts = get_trend_alerts(db, hours=168)  # Last 7 days
    micro = detect_micro_trends(db, hours=168)
    algo = detect_algorithm_changes(db, days=14)

    # Summarize niches
    hot_niches = [
        {"name": name, "growth": data["growth_percent"], "score": data["avg_score"]}
        for name, data in niches.items()
        if data["status"] in ("hot", "growing") and data["video_count"] > 0
    ]
    hot_niches.sort(key=lambda x: x["growth"], reverse=True)

    # Summarize formats
    hot_formats = [f for f in formats.get("formats", []) if f["status"] in ("hot", "growing")]

    # Summary text
    summary_parts = []
    if hot_niches:
        top = hot_niches[0]
        summary_parts.append(f"Nicho mais quente: {top['name']} (+{top['growth']}%)")
    if hot_formats:
        top_fmt = hot_formats[0]
        summary_parts.append(f"Formato trending: {top_fmt['format']} (+{top_fmt['growth_percent']}%)")
    if creators:
        summary_parts.append(f"Creator em destaque: @{creators[0]['username']} ({creators[0]['total_views']:,} views)")
    if cross_platform:
        summary_parts.append(f"Trend cross-platform: #{cross_platform[0]['hashtag']} ({cross_platform[0]['platform_count']} plataformas)")
    if micro:
        summary_parts.append(f"Micro-trend emergente: #{micro[0]['hashtag']} ({micro[0]['video_count']} videos)")

    # AI Narrative
    ai_narrative = ""
    try:
        from backend.services.local_ai import llm_chat
        summary_text = " | ".join(summary_parts) if summary_parts else "Sem dados."
        system = "Voce e um analista de tendencias digitais. Escreva em portugues brasileiro, maximo 300 palavras."
        prompt = f"""Gere uma narrativa executiva do relatorio semanal de tendencias:

Resumo: {summary_text}
Nichos quentes: {', '.join(n['name'] for n in hot_niches[:3])}
Formatos trending: {', '.join(f['format'] for f in hot_formats[:3])}
Alertas: {len(alerts)} alertas ({sum(1 for a in alerts if a.get('priority') == 'urgent')} urgentes)
Micro-trends: {len(micro)} emergentes

Escreva 3-4 paragrafos com: visao geral, oportunidades, riscos e recomendacoes praticas."""

        ai_narrative = await llm_chat(prompt, system=system, temperature=0.4, max_tokens=1000)
    except Exception as e:
        logger.error(f"Weekly report AI narrative error: {e}")
        ai_narrative = ""

    return {
        "period": "ultimos 7 dias",
        "generated_at": datetime.utcnow().isoformat(),
        "summary": " | ".join(summary_parts) if summary_parts else "Sem dados suficientes para o relatorio.",
        "ai_narrative": ai_narrative or "Narrativa IA indisponivel.",
        "hot_niches": hot_niches[:5],
        "hot_formats": hot_formats[:5],
        "top_creators": creators[:5],
        "cross_platform_trends": cross_platform[:5],
        "micro_trends": micro[:5],
        "alerts": alerts[:10],
        "algorithm_changes": algo["anomalies"],
        "total_alerts": len(alerts),
    }


# ── Telegram/Email Alert System ──────────────────────────────

async def send_telegram_alert(message: str, bot_token: str = "",
                               chat_id: str = "") -> dict:
    """
    Send trend alert via Telegram Bot API.
    Requires bot_token and chat_id to be configured.
    """
    import httpx

    if not bot_token or not chat_id:
        return {"success": False, "error": "Bot token e chat_id necessarios. Configure em Configuracoes."}

    url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
    payload = {
        "chat_id": chat_id,
        "text": message,
        "parse_mode": "HTML",
    }

    try:
        async with httpx.AsyncClient(timeout=10) as client:
            r = await client.post(url, json=payload)
            r.raise_for_status()
            return {"success": True, "message_id": r.json().get("result", {}).get("message_id")}
    except Exception as e:
        logger.error(f"Telegram send error: {e}")
        return {"success": False, "error": str(e)}


def format_alert_for_telegram(alerts: list) -> str:
    """Format trend alerts as a Telegram-friendly message."""
    if not alerts:
        return "Nenhum alerta no momento."

    icons = {
        "urgent": "🚨", "high": "🔥", "medium": "📊", "low": "ℹ️",
        "opportunity": "🎯", "explosion": "⚡", "cross_platform": "🌐",
    }

    lines = ["<b>📡 Viral Social - Alertas de Tendencias</b>\n"]
    for a in alerts[:10]:
        icon = icons.get(a.get("type", ""), icons.get(a.get("priority", ""), ""))
        lines.append(f"{icon} <b>{a['title']}</b>")
        lines.append(f"   {a['detail']}\n")

    lines.append(f"\n🔗 viral.chatys.com.br")
    return "\n".join(lines)
