from datetime import datetime, timedelta

from sqlalchemy.orm import Session
from sqlalchemy import desc

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


# In-memory alerts storage
_alerts: list[dict] = []


def get_alerts(limit: int = 50) -> list[dict]:
    return list(reversed(_alerts[-limit:]))


def clear_alerts():
    _alerts.clear()


def mark_alert_read(alert_id: int):
    for a in _alerts:
        if a["id"] == alert_id:
            a["read"] = True
            break


def get_unread_count() -> int:
    return sum(1 for a in _alerts if not a.get("read"))


def _add_alert(alert_type: str, title: str, message: str, data: dict = None):
    alert = {
        "id": len(_alerts) + 1,
        "type": alert_type,
        "title": title,
        "message": message,
        "data": data or {},
        "read": False,
        "created_at": datetime.utcnow().isoformat(),
    }
    _alerts.append(alert)
    return alert


def check_new_virals(db: Session, threshold: float = 75, hours: int = 24):
    """Check for new viral videos since last check."""
    since = datetime.utcnow() - timedelta(hours=hours)
    virals = (
        db.query(Video)
        .filter(Video.collected_at >= since, Video.viral_score >= threshold)
        .order_by(desc(Video.viral_score))
        .limit(10)
        .all()
    )
    for v in virals:
        existing = any(
            a["data"].get("video_id") == v.id and a["type"] == "viral"
            for a in _alerts
        )
        if not existing:
            creator_name = f"@{v.creator.username}" if v.creator else "Desconhecido"
            _add_alert(
                "viral",
                f"Novo viral no {v.platform.title()}!",
                f'"{v.title[:60]}" de {creator_name} - Score {v.viral_score}',
                {"video_id": v.id, "platform": v.platform, "url": v.url, "score": v.viral_score},
            )
    return len(virals)


def check_tracked_creators(db: Session, hours: int = 24):
    """Check if tracked creators have new viral content."""
    since = datetime.utcnow() - timedelta(hours=hours)
    tracked = db.query(Creator).filter(Creator.tracked == True).all()  # noqa: E712

    count = 0
    for creator in tracked:
        new_virals = (
            db.query(Video)
            .filter(
                Video.creator_id == creator.id,
                Video.collected_at >= since,
                Video.viral_score >= 60,
            )
            .all()
        )
        for v in new_virals:
            existing = any(
                a["data"].get("video_id") == v.id and a["type"] == "creator_viral"
                for a in _alerts
            )
            if not existing:
                _add_alert(
                    "creator_viral",
                    f"@{creator.username} viralizou!",
                    f'Novo vídeo com score {v.viral_score}: "{v.title[:50]}"',
                    {"creator_id": creator.id, "video_id": v.id, "platform": v.platform, "url": v.url},
                )
                count += 1
    return count


def check_trending_hashtags(db: Session, min_growth: float = 50):
    """Check for rapidly growing hashtags."""
    trends = (
        db.query(Trend)
        .filter(Trend.growth_rate >= min_growth)
        .order_by(desc(Trend.growth_rate))
        .limit(5)
        .all()
    )
    count = 0
    for t in trends:
        existing = any(
            a["data"].get("trend_name") == t.name and a["type"] == "trend"
            for a in _alerts
        )
        if not existing:
            _add_alert(
                "trend",
                f"Hashtag #{t.name} em alta!",
                f"Score médio {t.growth_rate} com {t.video_count} vídeos no {t.platform.title()}",
                {"trend_name": t.name, "platform": t.platform},
            )
            count += 1
    return count


def run_all_checks(db: Session) -> dict:
    """Run all alert checks and return summary."""
    virals = check_new_virals(db)
    creators = check_tracked_creators(db)
    trends = check_trending_hashtags(db)
    return {
        "new_virals": virals,
        "creator_alerts": creators,
        "trend_alerts": trends,
        "total_unread": get_unread_count(),
    }
