"""
ViralAcademy - AI Coach, gamification, learning hub.
Uses Ollama + Qwen 2.5 3B local (R$0/mes).
"""

import logging
from datetime import datetime, timedelta

from sqlalchemy.orm import Session

from backend.models.academy import UserProgress, Achievement, UserAchievement, Challenge, GrowthPlan

logger = logging.getLogger(__name__)


# ─── Helpers ──────────────────────────────────────────────────


def _get_or_create_progress(db: Session, user_id: str = "default") -> UserProgress:
    """Get or create user progress record."""
    progress = db.query(UserProgress).filter(UserProgress.user_id == user_id).first()
    if not progress:
        progress = UserProgress(user_id=user_id)
        db.add(progress)
        db.commit()
        db.refresh(progress)
    return progress


def add_xp(db: Session, amount: int, user_id: str = "default") -> dict:
    """Add XP to user and check for level up."""
    p = _get_or_create_progress(db, user_id)
    p.xp += amount
    # Check level up
    xp_needed = p.level * 500
    leveled_up = False
    while p.xp >= xp_needed:
        p.level += 1
        xp_needed = p.level * 500
        leveled_up = True

    # Update streak
    now = datetime.utcnow()
    if p.last_active:
        days_since = (now - p.last_active).days
        if days_since == 1:
            p.streak_days += 1
        elif days_since > 1:
            p.streak_days = 1
    else:
        p.streak_days = 1
    p.last_active = now

    db.commit()
    return {"xp_added": amount, "total_xp": p.xp, "level": p.level, "leveled_up": leveled_up, "streak": p.streak_days}


# ─── AI Coach (5 functions) ───────────────────────────────────


async def channel_audit(db: Session, platform: str = "tiktok", username: str = "") -> dict:
    """AI-powered channel audit with actionable recommendations."""
    from backend.services.local_ai import llm_chat
    from backend.models.video import Video

    # Gather data
    total_videos = db.query(Video).filter(Video.platform == platform).count()
    avg_views = 0
    avg_eng = 0
    if total_videos > 0:
        from sqlalchemy import func
        stats = db.query(
            func.avg(Video.views), func.avg(Video.engagement_rate)
        ).filter(Video.platform == platform).first()
        avg_views = int(stats[0] or 0)
        avg_eng = round(float(stats[1] or 0), 2)

    prompt = f"""Faca uma auditoria completa deste canal de {platform} em portugues:

DADOS DO CANAL:
- Username: @{username or 'meucanal'}
- Plataforma: {platform}
- Total de videos coletados: {total_videos}
- Media de views: {avg_views:,}
- Taxa de engajamento media: {avg_eng}%

Analise e forneça:
1. NOTA GERAL (0-100) - Avaliacao do canal
2. PONTOS FORTES (3 itens) - O que esta bom
3. AREAS DE MELHORIA (3 itens) - O que precisa melhorar
4. DIAGNOSTICO DE CONTEUDO - Tipos de conteudo que funcionam melhor
5. RECOMENDACOES IMEDIATAS (3 acoes) - O que fazer AGORA
6. META PARA 30 DIAS - Objetivo realista

Seja direto e acionavel."""

    audit_text = await llm_chat(prompt, system="Voce e um consultor de growth para criadores de conteudo digital brasileiros.", max_tokens=1500)

    # Award XP for doing audit
    xp_result = add_xp(db, 50)

    return {
        "audit": audit_text or "Erro ao gerar auditoria. Verifique se o Ollama esta rodando.",
        "stats": {"total_videos": total_videos, "avg_views": avg_views, "avg_engagement": avg_eng},
        "platform": platform,
        "xp_earned": 50,
        "generated_at": datetime.utcnow().isoformat(),
    }


async def personalized_recommendations(db: Session, user_id: str = "default") -> dict:
    """Generate personalized content recommendations based on user data."""
    from backend.services.local_ai import llm_chat
    from backend.models.video import Video

    progress = _get_or_create_progress(db, user_id)
    skills = progress.skill_scores or {}

    # Get top performing content patterns
    from sqlalchemy import func
    top_formats = db.query(
        Video.platform, func.avg(Video.views), func.count(Video.id)
    ).group_by(Video.platform).all()

    formats_str = ", ".join([f"{p}: {int(v or 0)} views medio ({c} videos)" for p, v, c in top_formats])

    prompt = f"""Gere recomendacoes personalizadas para este criador de conteudo:

NIVEL: {progress.level} | XP: {progress.xp} | Streak: {progress.streak_days} dias
SKILLS: {skills}
DADOS DA PLATAFORMA: {formats_str}
MODULOS COMPLETOS: {len(progress.completed_modules or [])} de 24

Com base nesses dados, recomende:
1. PROXIMO PASSO - O que deve focar agora
2. TIPO DE CONTEUDO - Que formato vai gerar mais resultado
3. SKILL PARA DESENVOLVER - Qual habilidade priorizar
4. DICA DO DIA - Uma dica pratica e imediata
5. MOTIVACAO - Mensagem inspiradora baseada no progresso

Responda em portugues, de forma direta e motivadora."""

    recs = await llm_chat(prompt, system="Voce e um coach de conteudo digital. Fale de forma motivadora e acionavel.", max_tokens=1000)

    return {
        "recommendations": recs or "Erro ao gerar recomendacoes.",
        "level": progress.level,
        "xp": progress.xp,
        "streak": progress.streak_days,
        "generated_at": datetime.utcnow().isoformat(),
    }


async def generate_growth_plan(db: Session, goal: str = "10k seguidores", platform: str = "tiktok",
                                days: int = 90, user_id: str = "default") -> dict:
    """Generate a personalized growth plan."""
    from backend.services.local_ai import llm_chat

    prompt = f"""Crie um plano de crescimento detalhado em portugues:

META: {goal}
PLATAFORMA: {platform}
PRAZO: {days} dias

Estruture o plano em fases:

FASE 1 (Dias 1-30): FUNDACAO
- 5 acoes concretas com frequencia

FASE 2 (Dias 31-60): CRESCIMENTO
- 5 acoes para escalar

FASE 3 (Dias 61-{days}): ACELERACAO
- 5 acoes para maximizar resultado

Para cada acao inclua: o que fazer, quando, e meta mensuravel.
Seja realista e acionavel."""

    plan_text = await llm_chat(prompt, system="Voce e um estrategista de growth hacking para redes sociais brasileiras.", max_tokens=2000)

    # Save plan
    plan = GrowthPlan(
        user_id=user_id,
        title=f"Plano: {goal} em {days} dias ({platform})",
        plan_data={"goal": goal, "platform": platform, "days": days, "plan": plan_text},
        duration_days=days,
    )
    db.add(plan)
    db.commit()
    db.refresh(plan)

    add_xp(db, 100, user_id)

    return {
        "plan": plan.to_dict(),
        "plan_text": plan_text or "Erro ao gerar plano.",
        "xp_earned": 100,
        "generated_at": datetime.utcnow().isoformat(),
    }


async def weekly_performance_report(db: Session, user_id: str = "default") -> dict:
    """Generate weekly performance report."""
    from backend.services.local_ai import llm_chat
    from backend.models.video import Video
    from sqlalchemy import func

    week_ago = datetime.utcnow() - timedelta(days=7)

    # Stats from last week
    weekly_videos = db.query(func.count(Video.id)).filter(Video.collected_at >= week_ago).scalar() or 0
    weekly_avg_views = db.query(func.avg(Video.views)).filter(Video.collected_at >= week_ago).scalar() or 0
    progress = _get_or_create_progress(db, user_id)

    prompt = f"""Gere um relatorio semanal de performance em portugues:

DADOS DA SEMANA:
- Videos analisados: {weekly_videos}
- Views medio dos videos: {int(weekly_avg_views):,}
- Nivel atual: {progress.level}
- XP ganho: {progress.xp}
- Streak: {progress.streak_days} dias
- Desafios completados: {progress.total_challenges_done}

Gere um relatorio com:
1. RESUMO DA SEMANA - Como foi o desempenho
2. DESTAQUES - O que deu certo
3. AREAS DE ATENCAO - O que precisa melhorar
4. METAS PARA PROXIMA SEMANA - 3 metas concretas
5. DICA DA SEMANA - Uma insight valiosa

Seja motivador mas honesto."""

    report = await llm_chat(prompt, system="Voce e um coach de performance digital.", max_tokens=1200)

    add_xp(db, 30, user_id)

    return {
        "report": report or "Erro ao gerar relatorio.",
        "stats": {
            "weekly_videos": weekly_videos,
            "weekly_avg_views": int(weekly_avg_views),
            "level": progress.level,
            "streak": progress.streak_days,
        },
        "xp_earned": 30,
        "generated_at": datetime.utcnow().isoformat(),
    }


def update_growth_plan_progress(db: Session, plan_id: int, progress_percent: float, user_id: str = "default") -> dict:
    """Update growth plan progress."""
    plan = db.query(GrowthPlan).filter(GrowthPlan.id == plan_id, GrowthPlan.user_id == user_id).first()
    if not plan:
        return {"error": "Plano nao encontrado"}
    plan.progress_percent = min(100, max(0, progress_percent))
    if plan.progress_percent >= 100:
        plan.status = "completed"
        add_xp(db, 500, user_id)
    plan.updated_at = datetime.utcnow()
    db.commit()
    return plan.to_dict()


# ─── Gamification (6 functions) ───────────────────────────────


def seed_achievements(db: Session) -> dict:
    """Seed 30+ achievements."""
    existing = db.query(Achievement).count()
    if existing >= 10:
        return {"status": "already_seeded", "count": existing}

    achievements = [
        # Aprendizado
        ("first_lesson", "Primeiro Passo", "Complete seu primeiro modulo", "book-open", 50, "aprendizado", "comum"),
        ("five_modules", "Estudante Dedicado", "Complete 5 modulos do curso", "graduation-cap", 200, "aprendizado", "raro"),
        ("ten_modules", "Metade do Caminho", "Complete 10 modulos", "milestone", 400, "aprendizado", "raro"),
        ("all_modules", "Mestre Viral", "Complete todos os 24 modulos", "crown", 2000, "aprendizado", "lendario"),
        ("skill_master", "Especialista", "Atinja nota maxima em uma skill", "star", 300, "aprendizado", "epico"),
        # Consistencia
        ("streak_3", "Consistente", "Mantenha 3 dias de streak", "flame", 50, "consistencia", "comum"),
        ("streak_7", "Semana Perfeita", "Mantenha 7 dias de streak", "calendar-check", 150, "consistencia", "raro"),
        ("streak_30", "Maquina de Conteudo", "Mantenha 30 dias de streak", "trophy", 500, "consistencia", "epico"),
        ("streak_100", "Lenda Viral", "Mantenha 100 dias de streak", "zap", 2000, "consistencia", "lendario"),
        # Desafios
        ("first_challenge", "Desafiante", "Complete seu primeiro desafio", "target", 50, "desafios", "comum"),
        ("ten_challenges", "Guerreiro", "Complete 10 desafios", "swords", 200, "desafios", "raro"),
        ("fifty_challenges", "Imbativel", "Complete 50 desafios", "shield", 1000, "desafios", "epico"),
        # Analise
        ("first_audit", "Autoconhecimento", "Faca sua primeira auditoria de canal", "search", 100, "analise", "comum"),
        ("first_plan", "Estrategista", "Crie seu primeiro plano de crescimento", "map", 100, "analise", "comum"),
        ("first_report", "Analista", "Gere seu primeiro relatorio semanal", "bar-chart", 80, "analise", "comum"),
        # Conteudo
        ("first_script", "Roteirista", "Gere seu primeiro script", "pen-tool", 50, "conteudo", "comum"),
        ("ten_scripts", "Escritor Prolifico", "Gere 10 scripts", "file-text", 200, "conteudo", "raro"),
        ("first_hook", "Pescador", "Use um hook do banco de hooks", "anchor", 30, "conteudo", "comum"),
        ("viral_reverse", "Detetive Viral", "Faca engenharia reversa de um video viral", "flask-conical", 100, "conteudo", "raro"),
        # Niveis
        ("level_5", "Aprendiz", "Atinja nivel 5", "chevrons-up", 100, "nivel", "comum"),
        ("level_10", "Intermediario", "Atinja nivel 10", "arrow-up-circle", 300, "nivel", "raro"),
        ("level_25", "Avancado", "Atinja nivel 25", "rocket", 800, "nivel", "epico"),
        ("level_50", "Elite", "Atinja nivel 50", "diamond", 2000, "nivel", "lendario"),
        # Exploracao
        ("spy_5", "Espiao Iniciante", "Analise 5 concorrentes", "eye", 100, "exploracao", "comum"),
        ("compare_3", "Comparador", "Compare 3 concorrentes lado a lado", "git-compare", 80, "exploracao", "comum"),
        ("trend_hunter", "Caca-Tendencias", "Descubra 10 tendencias", "trending-up", 150, "exploracao", "raro"),
        ("first_tts", "Narrador", "Gere seu primeiro audio TTS", "volume-2", 50, "conteudo", "comum"),
        # Social
        ("xp_1000", "Milhar", "Acumule 1.000 XP", "award", 100, "nivel", "comum"),
        ("xp_5000", "5K XP Club", "Acumule 5.000 XP", "medal", 200, "nivel", "raro"),
        ("xp_10000", "10K Master", "Acumule 10.000 XP", "gem", 500, "nivel", "epico"),
    ]

    count = 0
    for code, name, desc, icon, xp, cat, rarity in achievements:
        existing_a = db.query(Achievement).filter(Achievement.code == code).first()
        if not existing_a:
            db.add(Achievement(code=code, name=name, description=desc, icon=icon,
                               xp_reward=xp, category=cat, rarity=rarity))
            count += 1

    db.commit()
    return {"status": "seeded", "new": count, "total": db.query(Achievement).count()}


def check_and_award_achievements(db: Session, user_id: str = "default") -> list[dict]:
    """Check and award any earned achievements."""
    progress = _get_or_create_progress(db, user_id)
    earned = db.query(UserAchievement).filter(UserAchievement.user_id == user_id).all()
    earned_codes = {e.achievement_code for e in earned}

    new_achievements = []
    all_achievements = db.query(Achievement).all()

    conditions = {
        "streak_3": progress.streak_days >= 3,
        "streak_7": progress.streak_days >= 7,
        "streak_30": progress.streak_days >= 30,
        "streak_100": progress.streak_days >= 100,
        "level_5": progress.level >= 5,
        "level_10": progress.level >= 10,
        "level_25": progress.level >= 25,
        "level_50": progress.level >= 50,
        "xp_1000": progress.xp >= 1000,
        "xp_5000": progress.xp >= 5000,
        "xp_10000": progress.xp >= 10000,
        "first_challenge": progress.total_challenges_done >= 1,
        "ten_challenges": progress.total_challenges_done >= 10,
        "fifty_challenges": progress.total_challenges_done >= 50,
        "five_modules": len(progress.completed_modules or []) >= 5,
        "ten_modules": len(progress.completed_modules or []) >= 10,
        "all_modules": len(progress.completed_modules or []) >= 24,
        "first_lesson": len(progress.completed_modules or []) >= 1,
    }

    for ach in all_achievements:
        if ach.code in earned_codes:
            continue
        if conditions.get(ach.code, False):
            ua = UserAchievement(user_id=user_id, achievement_code=ach.code)
            db.add(ua)
            progress.xp += ach.xp_reward
            new_achievements.append({**ach.to_dict(), "just_earned": True})

    if new_achievements:
        # Re-check level
        xp_needed = progress.level * 500
        while progress.xp >= xp_needed:
            progress.level += 1
            xp_needed = progress.level * 500
        db.commit()

    return new_achievements


def get_user_stats(db: Session, user_id: str = "default") -> dict:
    """Get complete user stats for the academy."""
    progress = _get_or_create_progress(db, user_id)
    earned = db.query(UserAchievement).filter(UserAchievement.user_id == user_id).all()
    earned_codes = {e.achievement_code for e in earned}
    all_achievements = db.query(Achievement).all()
    total_achievements = len(all_achievements)
    earned_achievements = len(earned_codes)

    # Active challenges
    now = datetime.utcnow()
    active_challenges = db.query(Challenge).filter(
        Challenge.user_id == user_id,
        Challenge.is_completed == False,
        (Challenge.expires_at == None) | (Challenge.expires_at > now),
    ).count()

    # Active plans
    active_plans = db.query(GrowthPlan).filter(
        GrowthPlan.user_id == user_id, GrowthPlan.status == "active"
    ).count()

    return {
        **progress.to_dict(),
        "achievements_earned": earned_achievements,
        "achievements_total": total_achievements,
        "achievements_percent": round(earned_achievements / max(1, total_achievements) * 100),
        "earned_codes": list(earned_codes),
        "active_challenges": active_challenges,
        "active_plans": active_plans,
    }


def generate_daily_challenges(db: Session, user_id: str = "default") -> list[dict]:
    """Generate daily challenges."""
    # Check if already have active daily challenges
    now = datetime.utcnow()
    today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
    existing = db.query(Challenge).filter(
        Challenge.user_id == user_id,
        Challenge.challenge_type == "daily",
        Challenge.created_at >= today_start,
    ).all()

    if existing:
        return [c.to_dict() for c in existing]

    daily_challenges = [
        ("Analise 3 videos virais no Scanner", "Use o Viral Scanner para analisar 3 videos com score acima de 70", "analise", 30),
        ("Gere um roteiro completo", "Use o ScriptGenius para gerar um roteiro para seu proximo video", "conteudo", 40),
        ("Descubra 5 hashtags novas", "Pesquise e encontre 5 hashtags relevantes para seu nicho", "estrategia", 25),
        ("Estude 1 modulo do curso", "Complete um modulo do curso de viralizacao", "aprendizado", 50),
        ("Analise 1 concorrente", "Abra o Espiao e analise a estrategia de um concorrente", "analise", 35),
        ("Crie 3 hooks para seu proximo video", "Use o banco de hooks ou gere novos com IA", "conteudo", 30),
        ("Revise e melhore um script", "Pegue um script salvo e use a IA para melhorar", "conteudo", 35),
        ("Faca uma auditoria do seu canal", "Use o Coach IA para auditar seu canal", "analise", 45),
        ("Planeje seu conteudo da semana", "Use o calendario para planejar 3+ videos", "estrategia", 40),
        ("Pesquise trends no TrendRadar", "Encontre 3 tendencias emergentes para surfar", "estrategia", 30),
    ]

    import random
    selected = random.sample(daily_challenges, min(3, len(daily_challenges)))
    challenges = []
    for title, desc, cat, xp in selected:
        c = Challenge(
            title=title, description=desc, challenge_type="daily",
            xp_reward=xp, category=cat, user_id=user_id,
            expires_at=now.replace(hour=23, minute=59, second=59),
        )
        db.add(c)
        challenges.append(c)

    db.commit()
    return [c.to_dict() for c in challenges]


def generate_weekly_challenge(db: Session, user_id: str = "default") -> dict:
    """Generate a weekly challenge."""
    now = datetime.utcnow()
    week_start = now - timedelta(days=now.weekday())
    week_start = week_start.replace(hour=0, minute=0, second=0, microsecond=0)

    existing = db.query(Challenge).filter(
        Challenge.user_id == user_id,
        Challenge.challenge_type == "weekly",
        Challenge.created_at >= week_start,
    ).first()

    if existing:
        return existing.to_dict()

    weekly_challenges = [
        ("Publique 3 videos esta semana", "Crie e publique pelo menos 3 videos em qualquer plataforma", "conteudo", 200),
        ("Complete 5 modulos do curso", "Estude e complete 5 modulos do curso de viralizacao", "aprendizado", 250),
        ("Analise 5 concorrentes", "Faca analise detalhada de 5 concorrentes no Espiao", "analise", 180),
        ("Gere 5 scripts diferentes", "Use o ScriptGenius para criar 5 roteiros variados", "conteudo", 200),
        ("Mantenha streak a semana toda", "Acesse a plataforma todos os dias da semana", "consistencia", 150),
    ]

    import random
    title, desc, cat, xp = random.choice(weekly_challenges)
    c = Challenge(
        title=title, description=desc, challenge_type="weekly",
        xp_reward=xp, category=cat, user_id=user_id,
        expires_at=week_start + timedelta(days=7),
    )
    db.add(c)
    db.commit()
    return c.to_dict()


def get_active_challenges(db: Session, user_id: str = "default") -> dict:
    """Get all active challenges."""
    now = datetime.utcnow()
    challenges = db.query(Challenge).filter(
        Challenge.user_id == user_id,
        Challenge.is_completed == False,
        (Challenge.expires_at == None) | (Challenge.expires_at > now),
    ).order_by(Challenge.challenge_type, Challenge.created_at).all()

    daily = [c.to_dict() for c in challenges if c.challenge_type == "daily"]
    weekly = [c.to_dict() for c in challenges if c.challenge_type == "weekly"]

    return {"daily": daily, "weekly": weekly, "total": len(challenges)}


def complete_challenge(db: Session, challenge_id: int, user_id: str = "default") -> dict:
    """Mark a challenge as completed and award XP."""
    c = db.query(Challenge).filter(Challenge.id == challenge_id, Challenge.user_id == user_id).first()
    if not c:
        return {"error": "Desafio nao encontrado"}
    if c.is_completed:
        return {"error": "Desafio ja completado"}

    c.is_completed = True
    xp_result = add_xp(db, c.xp_reward, user_id)

    # Update total challenges
    progress = _get_or_create_progress(db, user_id)
    progress.total_challenges_done += 1
    db.commit()

    # Check achievements
    new_achievements = check_and_award_achievements(db, user_id)

    return {
        "challenge": c.to_dict(),
        "xp_earned": c.xp_reward,
        **xp_result,
        "new_achievements": new_achievements,
    }


# ─── Learning Hub (4 functions) ──────────────────────────────


COURSE_MODULES = [
    {"id": 1, "title": "Fundamentos da Viralizacao", "category": "fundamentos", "duration": 15,
     "description": "Entenda como o algoritmo funciona e o que torna um video viral."},
    {"id": 2, "title": "Psicologia do Scroll", "category": "fundamentos", "duration": 12,
     "description": "Por que as pessoas param de rolar? Triggers psicologicos."},
    {"id": 3, "title": "Hook Irresistivel", "category": "hooks", "duration": 20,
     "description": "Domine os primeiros 3 segundos do seu video."},
    {"id": 4, "title": "Estrutura de Roteiro Viral", "category": "roteiro", "duration": 18,
     "description": "Framework passo-a-passo para roteiros que prendem."},
    {"id": 5, "title": "Pattern Interrupts", "category": "retencao", "duration": 15,
     "description": "Tecnicas para manter atencao a cada 5-7 segundos."},
    {"id": 6, "title": "CTAs que Convertem", "category": "engajamento", "duration": 12,
     "description": "Chamadas para acao que geram likes, comentarios e shares."},
    {"id": 7, "title": "Hashtag Strategy 2026", "category": "descoberta", "duration": 15,
     "description": "Estrategia de hashtags para maximizar alcance."},
    {"id": 8, "title": "Thumbnails e Capas", "category": "visual", "duration": 10,
     "description": "Design de thumbnails que aumentam CTR."},
    {"id": 9, "title": "Edicao para Retencao", "category": "edicao", "duration": 20,
     "description": "Tecnicas de edicao que maximizam watch time."},
    {"id": 10, "title": "Storytelling Viral", "category": "roteiro", "duration": 25,
     "description": "Como contar historias que viralizam."},
    {"id": 11, "title": "Tendencias e Timing", "category": "estrategia", "duration": 15,
     "description": "Como surfar tendencias no momento certo."},
    {"id": 12, "title": "Nicho e Posicionamento", "category": "estrategia", "duration": 18,
     "description": "Encontre e domine seu nicho unico."},
    {"id": 13, "title": "Algoritmo do TikTok", "category": "plataformas", "duration": 20,
     "description": "Como o algoritmo do TikTok funciona em 2026."},
    {"id": 14, "title": "Algoritmo do Instagram", "category": "plataformas", "duration": 20,
     "description": "Reels, Stories e Feed: o que o Instagram prioriza."},
    {"id": 15, "title": "YouTube Shorts & Long-form", "category": "plataformas", "duration": 22,
     "description": "Estrategia dual: Shorts para crescer, long-form para monetizar."},
    {"id": 16, "title": "Cross-posting Inteligente", "category": "estrategia", "duration": 12,
     "description": "Como adaptar conteudo para multiplas plataformas."},
    {"id": 17, "title": "Engajamento Organico", "category": "engajamento", "duration": 15,
     "description": "Construa comunidade sem gastar com ads."},
    {"id": 18, "title": "Monetizacao de Conteudo", "category": "monetizacao", "duration": 25,
     "description": "7 formas de monetizar seu conteudo."},
    {"id": 19, "title": "Parcerias e Collabs", "category": "crescimento", "duration": 15,
     "description": "Estrategias de colaboracao para crescer mais rapido."},
    {"id": 20, "title": "Analytics e Metricas", "category": "analise", "duration": 20,
     "description": "Quais numeros importam e como interpreta-los."},
    {"id": 21, "title": "Calendario de Conteudo", "category": "planejamento", "duration": 15,
     "description": "Planeje 30 dias de conteudo em 1 hora."},
    {"id": 22, "title": "Repurposing de Conteudo", "category": "estrategia", "duration": 12,
     "description": "Transforme 1 video em 10 pecas de conteudo."},
    {"id": 23, "title": "Mindset de Criador", "category": "mindset", "duration": 18,
     "description": "Burnout, consistencia e mentalidade de longo prazo."},
    {"id": 24, "title": "Plano de Escala", "category": "avancado", "duration": 30,
     "description": "De criador solo a equipe: como escalar seu conteudo."},
]


def get_course_progress(db: Session, user_id: str = "default") -> dict:
    """Get course progress with module statuses."""
    progress = _get_or_create_progress(db, user_id)
    completed = set(progress.completed_modules or [])

    modules = []
    for m in COURSE_MODULES:
        modules.append({
            **m,
            "completed": m["id"] in completed,
            "status": "completed" if m["id"] in completed else "available",
        })

    total = len(COURSE_MODULES)
    done = len(completed)

    return {
        "modules": modules,
        "total": total,
        "completed": done,
        "percent": round(done / total * 100),
        "next_module": next((m for m in modules if not m["completed"]), None),
    }


def mark_module_complete(db: Session, module_id: int, user_id: str = "default") -> dict:
    """Mark a course module as complete."""
    if module_id < 1 or module_id > len(COURSE_MODULES):
        return {"error": "Modulo invalido"}

    progress = _get_or_create_progress(db, user_id)
    completed = list(progress.completed_modules or [])

    if module_id in completed:
        return {"error": "Modulo ja completado", "progress": progress.to_dict()}

    completed.append(module_id)
    progress.completed_modules = completed

    xp_result = add_xp(db, 75, user_id)
    db.commit()

    # Check achievements
    new_achievements = check_and_award_achievements(db, user_id)

    return {
        "module_id": module_id,
        "xp_earned": 75,
        "total_completed": len(completed),
        "new_achievements": new_achievements,
        **xp_result,
    }


async def skill_assessment(db: Session, skill: str = "hooks", user_id: str = "default") -> dict:
    """AI-powered skill assessment."""
    from backend.services.local_ai import llm_chat

    skills_map = {
        "hooks": "Capacidade de criar ganchos que capturam atencao nos primeiros 3 segundos",
        "storytelling": "Habilidade de contar historias envolventes em formato curto",
        "engajamento": "Capacidade de gerar interacao (likes, comentarios, shares)",
        "estrategia": "Planejamento de conteudo e visao de longo prazo",
        "edicao": "Habilidades tecnicas de edicao de video",
        "analytics": "Capacidade de interpretar metricas e tomar decisoes baseadas em dados",
        "tendencias": "Capacidade de identificar e surfar tendencias no momento certo",
    }

    skill_desc = skills_map.get(skill, skill)

    prompt = f"""Crie uma avaliacao rapida (3 perguntas) para medir a habilidade: "{skill}" ({skill_desc})

Para cada pergunta:
- Faca a pergunta de forma pratica
- De 3 opcoes de resposta (A, B, C)
- Indique qual resposta vale mais pontos

Formate como quiz rapido em portugues."""

    quiz = await llm_chat(prompt, system="Voce e um professor de marketing digital criando quizzes de avaliacao.", max_tokens=800)

    return {
        "skill": skill,
        "description": skill_desc,
        "quiz": quiz or "Erro ao gerar quiz.",
        "generated_at": datetime.utcnow().isoformat(),
    }


def get_learning_paths() -> list[dict]:
    """Get predefined learning paths."""
    return [
        {
            "id": "iniciante",
            "name": "Iniciante Total",
            "description": "Para quem esta comecando do zero nas redes sociais",
            "icon": "seedling",
            "modules": [1, 2, 3, 4, 6, 12],
            "duration": "2 semanas",
            "difficulty": "facil",
        },
        {
            "id": "viral_master",
            "name": "Mestre da Viralizacao",
            "description": "Domine as tecnicas avancadas de viralidade",
            "icon": "flame",
            "modules": [3, 5, 9, 10, 11, 13, 14],
            "duration": "3 semanas",
            "difficulty": "intermediario",
        },
        {
            "id": "monetization",
            "name": "Monetizacao",
            "description": "Transforme views em dinheiro",
            "icon": "dollar-sign",
            "modules": [18, 19, 17, 12, 15, 20],
            "duration": "2 semanas",
            "difficulty": "avancado",
        },
        {
            "id": "growth_hacker",
            "name": "Growth Hacker",
            "description": "Cresça rapido com estrategias agressivas",
            "icon": "rocket",
            "modules": [7, 11, 13, 14, 16, 19, 21, 22],
            "duration": "4 semanas",
            "difficulty": "avancado",
        },
        {
            "id": "full_course",
            "name": "Curso Completo",
            "description": "Todos os 24 modulos na ordem ideal",
            "icon": "graduation-cap",
            "modules": list(range(1, 25)),
            "duration": "8 semanas",
            "difficulty": "completo",
        },
    ]


def get_user_achievements(db: Session, user_id: str = "default") -> dict:
    """Get all achievements with earned status."""
    all_achs = db.query(Achievement).all()
    earned = db.query(UserAchievement).filter(UserAchievement.user_id == user_id).all()
    earned_map = {e.achievement_code: e.earned_at for e in earned}

    achievements = []
    for a in all_achs:
        achievements.append({
            **a.to_dict(),
            "earned": a.code in earned_map,
            "earned_at": earned_map[a.code].isoformat() if a.code in earned_map else None,
        })

    return {
        "achievements": achievements,
        "earned": len(earned_map),
        "total": len(all_achs),
    }


def get_growth_plans(db: Session, user_id: str = "default") -> list[dict]:
    """Get user's growth plans."""
    plans = db.query(GrowthPlan).filter(GrowthPlan.user_id == user_id).order_by(GrowthPlan.created_at.desc()).all()
    return [p.to_dict() for p in plans]
