"""
Trend Lifecycle Tracker - Classify trends as emerging, growing, peak, declining.
"""

from datetime import datetime
from sqlalchemy.orm import Session

from backend.models.competitor import TrendLifecycle


PHASE_LABELS = {
    "emerging": {"label": "Emergente", "emoji": "🟢", "action": "HORA DE ENTRAR!"},
    "growing": {"label": "Crescendo", "emoji": "📈", "action": "Ainda da tempo"},
    "peak": {"label": "Pico", "emoji": "🔴", "action": "Saturado - evitar"},
    "declining": {"label": "Declinando", "emoji": "⬇️", "action": "Tarde demais"},
}


def analyze_trend(db: Session, sc, keyword: str, platform: str = "tiktok") -> dict:
    """Analyze a trend/keyword and classify its lifecycle phase."""
    existing = db.query(TrendLifecycle).filter(
        TrendLifecycle.keyword == keyword.lower(),
        TrendLifecycle.platform == platform,
    ).first()

    # Fetch current data
    videos = []
    try:
        if platform == "tiktok":
            videos = sc.tiktok_search_top(keyword, 20)
        elif platform == "instagram":
            videos = sc.instagram_reels_search(keyword, 20)
        elif platform == "youtube":
            result = sc.youtube_search(keyword, 20)
            videos = result.get("videos", []) + result.get("shorts", [])
    except Exception:
        pass

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

    # Calculate metrics
    video_count = len(videos)
    views = [v.get("views", 0) or 0 for v in videos]
    likes = [v.get("likes", 0) or 0 for v in videos]
    avg_views = sum(views) / max(1, len(views))
    avg_likes = sum(likes) / max(1, len(likes))
    avg_engagement = (avg_likes / max(1, avg_views)) * 100

    # Top creators
    creators = {}
    for v in videos:
        c = v.get("creator_username", "")
        if c:
            creators[c] = creators.get(c, 0) + 1
    top_creators = sorted(creators.items(), key=lambda x: x[1], reverse=True)[:5]

    # Classify phase
    if existing:
        prev_count = existing.video_count
        growth = video_count - prev_count
        phase = _classify(video_count, avg_views, growth, existing.first_seen, avg_engagement)

        # Update history
        history = existing.history or []
        history.append({
            "date": datetime.utcnow().strftime("%d/%m %H:%M"),
            "video_count": video_count,
            "avg_views": round(avg_views),
            "phase": phase,
        })
        if len(history) > 50:
            history = history[-50:]

        existing.video_count = video_count
        existing.avg_views = round(avg_views)
        existing.avg_engagement = round(avg_engagement, 2)
        existing.top_creators = [{"username": c[0], "videos": c[1]} for c in top_creators]
        existing.phase = phase
        existing.history = history
        existing.last_checked = datetime.utcnow()
        db.commit()
        result = existing.to_dict()
    else:
        phase = "emerging" if video_count < 20 else "growing"
        trend = TrendLifecycle(
            keyword=keyword.lower(),
            platform=platform,
            phase=phase,
            video_count=video_count,
            avg_views=round(avg_views),
            avg_engagement=round(avg_engagement, 2),
            top_creators=[{"username": c[0], "videos": c[1]} for c in top_creators],
            history=[{
                "date": datetime.utcnow().strftime("%d/%m %H:%M"),
                "video_count": video_count,
                "avg_views": round(avg_views),
                "phase": phase,
            }],
        )
        db.add(trend)
        db.commit()
        db.refresh(trend)
        result = trend.to_dict()

    phase_info = PHASE_LABELS.get(phase, PHASE_LABELS["emerging"])
    result["phase_label"] = phase_info["label"]
    result["phase_emoji"] = phase_info["emoji"]
    result["phase_action"] = phase_info["action"]
    result["sample_videos"] = videos[:5]

    return result


def get_all_tracked_trends(db: Session) -> list[dict]:
    trends = db.query(TrendLifecycle).order_by(TrendLifecycle.last_checked.desc()).all()
    result = []
    for t in trends:
        d = t.to_dict()
        info = PHASE_LABELS.get(t.phase, PHASE_LABELS["emerging"])
        d["phase_label"] = info["label"]
        d["phase_emoji"] = info["emoji"]
        d["phase_action"] = info["action"]
        result.append(d)
    return result


def get_emerging_trends(db: Session) -> list[dict]:
    trends = (
        db.query(TrendLifecycle)
        .filter(TrendLifecycle.phase.in_(["emerging", "growing"]))
        .order_by(TrendLifecycle.avg_views.desc())
        .all()
    )
    return [t.to_dict() for t in trends]


def _classify(video_count: int, avg_views: float, growth: int, first_seen: datetime, engagement: float) -> str:
    hours = max(1, (datetime.utcnow() - first_seen).total_seconds() / 3600)

    if video_count < 10 and hours < 48:
        return "emerging"
    elif growth > 0 and video_count < 50 and hours < 168:
        return "growing" if avg_views > 10000 else "emerging"
    elif growth <= 0 and video_count > 20:
        return "declining"
    elif video_count >= 50 or (hours > 168 and growth < 5):
        return "peak"
    elif growth > 0:
        return "growing"
    return "peak"
