"""
AutoFlow - Workflow Automation Engine with AI Agents.
Visual workflows, triggers, AI agent orchestration, content factory pipeline.
Uses Ollama local AI (R$0/mes). No external API costs.
"""

import json
import logging
import uuid
import time
import asyncio
from datetime import datetime, timedelta
from collections import defaultdict

from sqlalchemy.orm import Session
from sqlalchemy import func, desc

from backend.models.video import Video

logger = logging.getLogger(__name__)

# In-memory workflow storage
_workflows = {}
_workflow_runs = {}


# ─── 1. create_workflow ──────────────────────────────────────────

def create_workflow(
    name: str,
    description: str = "",
    trigger_type: str = "manual",
    trigger_config: dict = None,
    steps: list = None,
) -> dict:
    """
    Create a workflow with steps.
    trigger_type: manual, schedule, event, condition
    steps: list of {type, config, name}
    """
    workflow_id = str(uuid.uuid4())[:12]
    now = datetime.utcnow().isoformat()

    if trigger_config is None:
        trigger_config = {}
    if steps is None:
        steps = []

    validated_steps = []
    available = {s["type"] for s in get_available_step_types()}
    for i, step in enumerate(steps):
        step_type = step.get("type", "")
        step_name = step.get("name", f"Passo {i + 1}")
        step_config = step.get("config", {})
        validated_steps.append({
            "id": f"step_{i}",
            "order": i,
            "type": step_type,
            "name": step_name,
            "config": step_config,
            "status": "pending",
        })

    workflow = {
        "workflow_id": workflow_id,
        "name": name,
        "description": description,
        "trigger": {
            "type": trigger_type,
            "config": trigger_config,
        },
        "steps": validated_steps,
        "status": "active",
        "created_at": now,
        "updated_at": now,
        "run_count": 0,
        "last_run": None,
    }

    _workflows[workflow_id] = workflow
    logger.info(f"Workflow criado: {name} ({workflow_id}) com {len(validated_steps)} passos")
    return workflow


# ─── 2. list_workflows ──────────────────────────────────────────

def list_workflows() -> list:
    """Return all workflows with status."""
    results = []
    for wf in _workflows.values():
        results.append({
            "workflow_id": wf["workflow_id"],
            "name": wf["name"],
            "description": wf["description"],
            "trigger_type": wf["trigger"]["type"],
            "steps_count": len(wf["steps"]),
            "status": wf["status"],
            "run_count": wf["run_count"],
            "last_run": wf["last_run"],
            "created_at": wf["created_at"],
        })
    results.sort(key=lambda x: x["created_at"], reverse=True)
    return results


# ─── 3. get_workflow ─────────────────────────────────────────────

def get_workflow(workflow_id: str) -> dict:
    """Get full workflow details."""
    wf = _workflows.get(workflow_id)
    if not wf:
        return {"error": f"Workflow {workflow_id} nao encontrado"}
    return wf


# ─── 4. delete_workflow ──────────────────────────────────────────

def delete_workflow(workflow_id: str) -> bool:
    """Delete a workflow by ID."""
    if workflow_id in _workflows:
        del _workflows[workflow_id]
        logger.info(f"Workflow deletado: {workflow_id}")
        return True
    return False


# ─── 5. execute_workflow ─────────────────────────────────────────

async def execute_workflow(
    workflow_id: str,
    db: Session = None,
    input_data: dict = None,
) -> dict:
    """
    Execute a workflow step by step.
    For each step, call the appropriate handler.
    Track run in _workflow_runs.
    """
    wf = _workflows.get(workflow_id)
    if not wf:
        return {"error": f"Workflow {workflow_id} nao encontrado"}

    run_id = str(uuid.uuid4())[:12]
    start_time = time.time()
    now_iso = datetime.utcnow().isoformat()

    run_record = {
        "run_id": run_id,
        "workflow_id": workflow_id,
        "workflow_name": wf["name"],
        "status": "running",
        "started_at": now_iso,
        "finished_at": None,
        "steps_completed": 0,
        "steps_total": len(wf["steps"]),
        "results": [],
        "duration": 0,
        "input_data": input_data or {},
        "error": None,
    }
    _workflow_runs[run_id] = run_record

    context = {
        "workflow_id": workflow_id,
        "run_id": run_id,
        "input_data": input_data or {},
        "step_results": {},
        "accumulated_data": {},
    }

    steps_completed = 0
    step_results = []

    for step in wf["steps"]:
        step_start = time.time()
        try:
            result = await _execute_step(step, context, db)
            step_duration = round(time.time() - step_start, 2)

            step_record = {
                "step_id": step["id"],
                "step_name": step["name"],
                "step_type": step["type"],
                "success": result.get("success", False),
                "result": result.get("result", {}),
                "duration": step_duration,
                "error": result.get("error"),
            }
            step_results.append(step_record)

            if result.get("success"):
                steps_completed += 1
                context["step_results"][step["id"]] = result.get("result", {})
                if isinstance(result.get("result"), dict):
                    context["accumulated_data"].update(result["result"])
            else:
                logger.warning(
                    f"Step {step['name']} falhou no workflow {wf['name']}: "
                    f"{result.get('error', 'Unknown error')}"
                )
                break

        except Exception as e:
            step_duration = round(time.time() - step_start, 2)
            step_results.append({
                "step_id": step["id"],
                "step_name": step["name"],
                "step_type": step["type"],
                "success": False,
                "result": {},
                "duration": step_duration,
                "error": str(e),
            })
            logger.error(f"Erro executando step {step['name']}: {e}")
            break

    total_duration = round(time.time() - start_time, 2)
    final_status = "success" if steps_completed == len(wf["steps"]) else "failed"
    if steps_completed > 0 and steps_completed < len(wf["steps"]):
        final_status = "partial"

    run_record.update({
        "status": final_status,
        "finished_at": datetime.utcnow().isoformat(),
        "steps_completed": steps_completed,
        "results": step_results,
        "duration": total_duration,
    })

    wf["run_count"] += 1
    wf["last_run"] = datetime.utcnow().isoformat()

    logger.info(
        f"Workflow {wf['name']} executado: {final_status} "
        f"({steps_completed}/{len(wf['steps'])} passos em {total_duration}s)"
    )

    return {
        "run_id": run_id,
        "status": final_status,
        "steps_completed": steps_completed,
        "steps_total": len(wf["steps"]),
        "results": step_results,
        "duration": total_duration,
    }


# ─── 6. get_workflow_run ─────────────────────────────────────────

def get_workflow_run(run_id: str) -> dict:
    """Get run status and results."""
    run = _workflow_runs.get(run_id)
    if not run:
        return {"error": f"Run {run_id} nao encontrada"}
    return run


# ─── 7. list_workflow_runs ───────────────────────────────────────

def list_workflow_runs(workflow_id: str = "", limit: int = 20) -> list:
    """List workflow runs, optionally filtered by workflow_id."""
    runs = list(_workflow_runs.values())
    if workflow_id:
        runs = [r for r in runs if r.get("workflow_id") == workflow_id]
    runs.sort(key=lambda x: x.get("started_at", ""), reverse=True)
    return runs[:limit]


# ─── 8. get_workflow_templates ───────────────────────────────────

def get_workflow_templates() -> list:
    """Return 8 predefined workflow templates."""
    return [
        {
            "template_id": "trend_to_content",
            "name": "Trend to Content",
            "description": "Detecta tendencia viral -> Gera roteiro otimizado -> Cria audio TTS -> Pronto para publicar",
            "icon": "trending-up",
            "color": "brand",
            "category": "producao",
            "steps": [
                {"type": "detect_trends", "name": "Detectar Tendencias", "config": {"days": 3, "min_score": 60}},
                {"type": "generate_script", "name": "Gerar Roteiro", "config": {"style": "trending", "duration": 30}},
                {"type": "generate_tts", "name": "Gerar Audio TTS", "config": {"language": "pt-BR"}},
                {"type": "seo_optimize", "name": "Otimizar SEO", "config": {"platform": "tiktok"}},
            ],
        },
        {
            "template_id": "daily_scan",
            "name": "Scan Diario",
            "description": "Escaneia plataformas -> Detecta videos virais -> Envia alerta no Telegram",
            "icon": "radar",
            "color": "cyan",
            "category": "monitoramento",
            "steps": [
                {"type": "scan_trending", "name": "Scan Plataformas", "config": {"platforms": ["tiktok", "youtube"], "region": "BR"}},
                {"type": "detect_trends", "name": "Detectar Virais", "config": {"min_score": 70}},
                {"type": "send_alert", "name": "Alerta Telegram", "config": {"channel": "telegram", "template": "viral_alert"}},
            ],
        },
        {
            "template_id": "competitor_watch",
            "name": "Espiao de Concorrentes",
            "description": "Monitora concorrentes -> Detecta novos virais -> Analise de gaps -> Gera ideias de conteudo",
            "icon": "eye",
            "color": "pink",
            "category": "estrategia",
            "steps": [
                {"type": "scan_trending", "name": "Checar Concorrentes", "config": {"source": "competitors"}},
                {"type": "detect_trends", "name": "Detectar Virais Novos", "config": {"min_score": 50, "days": 2}},
                {"type": "gap_analysis", "name": "Analise de Gaps", "config": {}},
                {"type": "generate_script", "name": "Gerar Ideias", "config": {"style": "lista", "count": 5}},
            ],
        },
        {
            "template_id": "shop_monitor",
            "name": "Monitor de Loja",
            "description": "Monitora produtos TikTok Shop -> Detecta mudancas de preco -> Envia alertas",
            "icon": "shopping-bag",
            "color": "orange",
            "category": "ecommerce",
            "steps": [
                {"type": "scan_trending", "name": "Checar Produtos", "config": {"source": "shop", "platform": "tiktok"}},
                {"type": "analyze_video", "name": "Detectar Mudancas", "config": {"focus": "price_changes"}},
                {"type": "send_alert", "name": "Alerta de Preco", "config": {"channel": "telegram", "template": "price_change"}},
            ],
        },
        {
            "template_id": "content_repurpose",
            "name": "Reaproveitamento de Conteudo",
            "description": "Pega video viral -> Transcreve -> Reescreve para 3 plataformas diferentes",
            "icon": "repeat",
            "color": "green",
            "category": "producao",
            "steps": [
                {"type": "transcribe", "name": "Transcrever Video", "config": {"language": "pt"}},
                {"type": "generate_script", "name": "Adaptar p/ TikTok", "config": {"platform": "tiktok", "style": "trending"}},
                {"type": "generate_script", "name": "Adaptar p/ YouTube", "config": {"platform": "youtube", "style": "tutorial"}},
                {"type": "generate_script", "name": "Adaptar p/ Instagram", "config": {"platform": "instagram", "style": "storytelling"}},
            ],
        },
        {
            "template_id": "audience_engage",
            "name": "Engajamento de Audiencia",
            "description": "Coleta comentarios -> Classifica por sentimento -> Responde automaticamente os importantes",
            "icon": "message-circle",
            "color": "cyan",
            "category": "engajamento",
            "steps": [
                {"type": "classify_comments", "name": "Classificar Comentarios", "config": {"limit": 50}},
                {"type": "auto_reply", "name": "Respostas Automaticas", "config": {"reply_to": "positive", "max_replies": 10}},
                {"type": "send_alert", "name": "Resumo Engagement", "config": {"channel": "telegram", "template": "engagement_summary"}},
            ],
        },
        {
            "template_id": "weekly_report",
            "name": "Relatorio Semanal",
            "description": "Coleta todos os dados da semana -> Gera relatorio completo com IA -> Envia no Telegram",
            "icon": "bar-chart-3",
            "color": "brand",
            "category": "relatorios",
            "steps": [
                {"type": "detect_trends", "name": "Coletar Dados Semana", "config": {"days": 7}},
                {"type": "analyze_video", "name": "Gerar Relatorio", "config": {"focus": "weekly_summary"}},
                {"type": "send_alert", "name": "Enviar Telegram", "config": {"channel": "telegram", "template": "weekly_report"}},
            ],
        },
        {
            "template_id": "batch_scripts",
            "name": "Fabrica de Roteiros",
            "description": "Pega 5 topicos trending -> Gera 5 roteiros completos -> Salva prontos para producao",
            "icon": "pen-tool",
            "color": "pink",
            "category": "producao",
            "steps": [
                {"type": "detect_trends", "name": "Buscar 5 Trending", "config": {"limit": 5, "min_score": 50}},
                {"type": "batch_process", "name": "Gerar 5 Roteiros", "config": {"action": "generate_scripts", "count": 5}},
                {"type": "seo_optimize", "name": "Otimizar Todos", "config": {"batch": True}},
            ],
        },
    ]


# ─── 9. create_from_template ────────────────────────────────────

async def create_from_template(template_id: str, db: Session = None) -> dict:
    """Create workflow from a predefined template."""
    templates = get_workflow_templates()
    template = None
    for t in templates:
        if t["template_id"] == template_id:
            template = t
            break

    if not template:
        return {"error": f"Template '{template_id}' nao encontrado"}

    workflow = create_workflow(
        name=template["name"],
        description=template["description"],
        trigger_type="manual",
        trigger_config={"from_template": template_id},
        steps=template["steps"],
    )

    logger.info(f"Workflow criado a partir do template: {template['name']}")
    return workflow


# ─── 10. get_available_step_types ────────────────────────────────

def get_available_step_types() -> list:
    """Return all available step types with descriptions."""
    return [
        {
            "type": "scan_trending",
            "name": "Scan Trending",
            "description": "Escaneia plataformas em busca de videos e conteudos em alta",
            "icon": "radar",
            "category": "coleta",
            "estimated_duration": "30-60s",
            "cost": "R$0 (local)",
        },
        {
            "type": "generate_script",
            "name": "Gerar Roteiro",
            "description": "Gera roteiro completo com hook, corpo e CTA usando IA local",
            "icon": "pen-tool",
            "category": "producao",
            "estimated_duration": "10-30s",
            "cost": "R$0 (Ollama local)",
        },
        {
            "type": "generate_tts",
            "name": "Gerar Audio TTS",
            "description": "Converte texto do roteiro em audio narrado",
            "icon": "volume-2",
            "category": "producao",
            "estimated_duration": "15-45s",
            "cost": "R$0 (local)",
        },
        {
            "type": "analyze_video",
            "name": "Analisar Video",
            "description": "Analise profunda de metricas, engajamento e potencial viral",
            "icon": "bar-chart-3",
            "category": "analise",
            "estimated_duration": "5-15s",
            "cost": "R$0 (local)",
        },
        {
            "type": "detect_trends",
            "name": "Detectar Tendencias",
            "description": "Identifica tendencias emergentes a partir dos dados coletados",
            "icon": "trending-up",
            "category": "analise",
            "estimated_duration": "5-20s",
            "cost": "R$0 (local)",
        },
        {
            "type": "send_alert",
            "name": "Enviar Alerta",
            "description": "Envia notificacao via Telegram, email ou webhook",
            "icon": "bell",
            "category": "notificacao",
            "estimated_duration": "2-5s",
            "cost": "R$0",
        },
        {
            "type": "classify_comments",
            "name": "Classificar Comentarios",
            "description": "Classifica comentarios por sentimento (positivo, negativo, neutro)",
            "icon": "message-circle",
            "category": "analise",
            "estimated_duration": "5-15s",
            "cost": "R$0 (VADER local)",
        },
        {
            "type": "auto_reply",
            "name": "Resposta Automatica",
            "description": "Gera respostas automaticas inteligentes para comentarios",
            "icon": "reply",
            "category": "engajamento",
            "estimated_duration": "10-30s",
            "cost": "R$0 (Ollama local)",
        },
        {
            "type": "gap_analysis",
            "name": "Analise de Gaps",
            "description": "Identifica lacunas de conteudo comparando com concorrentes",
            "icon": "git-compare",
            "category": "estrategia",
            "estimated_duration": "10-20s",
            "cost": "R$0 (Ollama local)",
        },
        {
            "type": "seo_optimize",
            "name": "Otimizar SEO",
            "description": "Otimiza titulo, descricao e hashtags para maximo alcance",
            "icon": "search",
            "category": "otimizacao",
            "estimated_duration": "5-15s",
            "cost": "R$0 (Ollama local)",
        },
        {
            "type": "transcribe",
            "name": "Transcrever",
            "description": "Transcreve audio/video para texto usando Whisper local",
            "icon": "file-text",
            "category": "producao",
            "estimated_duration": "30-120s",
            "cost": "R$0 (Whisper local)",
        },
        {
            "type": "translate",
            "name": "Traduzir",
            "description": "Traduz conteudo entre idiomas usando IA local",
            "icon": "languages",
            "category": "producao",
            "estimated_duration": "10-30s",
            "cost": "R$0 (Ollama local)",
        },
        {
            "type": "batch_process",
            "name": "Processar em Lote",
            "description": "Executa uma acao em multiplos itens de uma vez",
            "icon": "layers",
            "category": "automacao",
            "estimated_duration": "30-120s",
            "cost": "R$0 (local)",
        },
    ]


# ─── 11. _execute_step (internal) ───────────────────────────────

async def _execute_step(step: dict, context: dict, db: Session = None) -> dict:
    """
    Internal step executor.
    Based on step type, call the appropriate service.
    Returns {success, result, duration, error}.
    """
    step_type = step.get("type", "")
    config = step.get("config", {})
    start = time.time()

    try:
        if step_type == "scan_trending":
            result = await _step_scan_trending(config, context, db)

        elif step_type == "generate_script":
            result = await _step_generate_script(config, context, db)

        elif step_type == "generate_tts":
            result = await _step_generate_tts(config, context)

        elif step_type == "analyze_video":
            result = await _step_analyze_video(config, context, db)

        elif step_type == "detect_trends":
            result = await _step_detect_trends(config, context, db)

        elif step_type == "send_alert":
            result = await _step_send_alert(config, context)

        elif step_type == "classify_comments":
            result = await _step_classify_comments(config, context, db)

        elif step_type == "auto_reply":
            result = await _step_auto_reply(config, context)

        elif step_type == "gap_analysis":
            result = await _step_gap_analysis(config, context, db)

        elif step_type == "seo_optimize":
            result = await _step_seo_optimize(config, context)

        elif step_type == "transcribe":
            result = await _step_transcribe(config, context)

        elif step_type == "translate":
            result = await _step_translate(config, context)

        elif step_type == "batch_process":
            result = await _step_batch_process(config, context, db)

        else:
            result = {"success": False, "error": f"Tipo de step desconhecido: {step_type}"}

        duration = round(time.time() - start, 2)
        result["duration"] = duration
        return result

    except Exception as e:
        duration = round(time.time() - start, 2)
        logger.error(f"Erro no step {step_type}: {e}")
        return {"success": False, "result": {}, "duration": duration, "error": str(e)}


# ─── Step handlers ───────────────────────────────────────────────

async def _step_scan_trending(config: dict, context: dict, db: Session = None) -> dict:
    """Scan platforms for trending content."""
    platforms = config.get("platforms", ["tiktok"])
    region = config.get("region", "BR")

    trending_videos = []
    if db:
        since = datetime.utcnow() - timedelta(days=config.get("days", 3))
        videos = (
            db.query(Video)
            .filter(Video.collected_at >= since, Video.viral_score >= 40)
            .order_by(desc(Video.viral_score))
            .limit(config.get("limit", 20))
            .all()
        )
        for v in videos:
            trending_videos.append({
                "id": v.id,
                "title": v.title[:100],
                "platform": v.platform,
                "views": v.views,
                "likes": v.likes,
                "viral_score": v.viral_score,
                "hashtags": v.hashtags or [],
            })
    else:
        trending_videos = [
            {"title": "Video trending simulado", "platform": "tiktok", "views": 500000, "viral_score": 85}
        ]

    context["accumulated_data"]["trending_videos"] = trending_videos

    return {
        "success": True,
        "result": {
            "videos_found": len(trending_videos),
            "platforms_scanned": platforms,
            "region": region,
            "trending_videos": trending_videos[:10],
        },
    }


async def _step_generate_script(config: dict, context: dict, db: Session = None) -> dict:
    """Generate a video script using local AI."""
    from backend.services.local_ai import llm_chat

    platform = config.get("platform", "tiktok")
    style = config.get("style", "trending")
    duration = config.get("duration", 30)

    topic = config.get("topic", "")
    if not topic:
        trending = context.get("accumulated_data", {}).get("trending_videos", [])
        if trending:
            top = trending[0]
            topic = top.get("title", "conteudo viral")
            tags = top.get("hashtags", [])
            if tags and isinstance(tags, list):
                topic += " " + " ".join(f"#{t}" for t in tags[:3])
        else:
            topic = context.get("input_data", {}).get("topic", "dicas para viralizar nas redes sociais")

    prompt = f"""Crie um roteiro completo para video de {platform} sobre: "{topic}"

ESTILO: {style}
DURACAO: ~{duration} segundos

Estruture assim:
HOOK (3 segundos): [frase poderosa que capture atencao]
CORPO: [conteudo principal em blocos curtos]
CTA: [chamada para acao]
HASHTAGS: [5-8 hashtags]

Use linguagem natural, frases curtas, ritmo rapido."""

    script_text = await llm_chat(
        prompt,
        system="Voce e um roteirista profissional de videos virais para redes sociais brasileiras.",
        max_tokens=1200,
    )

    if not script_text:
        script_text = (
            f"HOOK: Voce precisa saber disso sobre {topic}!\n\n"
            f"CORPO: Aqui esta o que descobri sobre {topic}. "
            "Primeiro, preste atencao nesse detalhe importante. "
            "Segundo, a maioria das pessoas ignora isso. "
            "Terceiro, essa e a chave para o sucesso.\n\n"
            "CTA: Salva esse video e compartilha com alguem que precisa ver isso!\n\n"
            f"HASHTAGS: #viral #trending #{platform} #dicas #fyp"
        )

    context["accumulated_data"]["script"] = script_text
    context["accumulated_data"]["topic"] = topic

    return {
        "success": True,
        "result": {
            "script": script_text,
            "topic": topic,
            "platform": platform,
            "style": style,
            "duration": duration,
            "word_count": len(script_text.split()),
        },
    }


async def _step_generate_tts(config: dict, context: dict) -> dict:
    """Generate TTS audio from script text."""
    script = context.get("accumulated_data", {}).get("script", "")
    if not script:
        return {"success": False, "result": {}, "error": "Nenhum roteiro disponivel para TTS"}

    language = config.get("language", "pt-BR")

    lines = [line.strip() for line in script.split("\n") if line.strip()]
    hook = ""
    body_parts = []
    for line in lines:
        upper = line.upper()
        if upper.startswith("HOOK"):
            hook = line.split(":", 1)[-1].strip() if ":" in line else line
        elif not upper.startswith("HASHTAG") and not upper.startswith("CTA"):
            body_parts.append(line)

    tts_text = hook + " " + " ".join(body_parts[:5]) if hook else " ".join(body_parts[:6])
    estimated_duration = len(tts_text.split()) * 0.4

    return {
        "success": True,
        "result": {
            "tts_text": tts_text[:500],
            "language": language,
            "estimated_duration_sec": round(estimated_duration, 1),
            "status": "tts_ready",
            "note": "Texto preparado para processamento TTS",
        },
    }


async def _step_analyze_video(config: dict, context: dict, db: Session = None) -> dict:
    """Analyze video metrics and patterns."""
    from backend.services.local_ai import llm_chat

    focus = config.get("focus", "general")
    trending = context.get("accumulated_data", {}).get("trending_videos", [])

    if focus == "weekly_summary" and db:
        since = datetime.utcnow() - timedelta(days=7)
        total_videos = db.query(func.count(Video.id)).filter(Video.collected_at >= since).scalar() or 0
        avg_score = db.query(func.avg(Video.viral_score)).filter(Video.collected_at >= since).scalar() or 0
        top_platform = (
            db.query(Video.platform, func.count(Video.id).label("cnt"))
            .filter(Video.collected_at >= since)
            .group_by(Video.platform)
            .order_by(desc("cnt"))
            .first()
        )
        total_views = db.query(func.sum(Video.views)).filter(Video.collected_at >= since).scalar() or 0

        summary_prompt = f"""Gere um resumo semanal de performance em redes sociais:
- Videos coletados: {total_videos}
- Score viral medio: {avg_score:.1f}
- Plataforma principal: {top_platform[0] if top_platform else 'N/A'}
- Views totais: {total_views:,}

Faca um resumo executivo de 3-4 frases em portugues com insights acionaveis."""

        summary = await llm_chat(summary_prompt, system="Voce e um analista de marketing digital.", max_tokens=500)
        if not summary:
            summary = (
                f"Semana com {total_videos} videos coletados e score viral medio de {avg_score:.1f}. "
                f"A plataforma mais ativa foi {top_platform[0] if top_platform else 'N/A'} "
                f"com total de {total_views:,} views acumuladas."
            )

        return {
            "success": True,
            "result": {
                "focus": focus,
                "total_videos": total_videos,
                "avg_viral_score": round(avg_score, 1),
                "top_platform": top_platform[0] if top_platform else "N/A",
                "total_views": total_views,
                "summary": summary,
            },
        }

    elif focus == "price_changes":
        changes_found = []
        if db:
            since = datetime.utcnow() - timedelta(days=1)
            shop_vids = (
                db.query(Video)
                .filter(Video.collected_at >= since, Video.with_shop_entry == True)
                .order_by(desc(Video.views))
                .limit(10)
                .all()
            )
            for v in shop_vids:
                changes_found.append({
                    "title": v.title[:80],
                    "views": v.views,
                    "platform": v.platform,
                    "shop_url": v.shop_product_url,
                })

        return {
            "success": True,
            "result": {
                "focus": focus,
                "changes_detected": len(changes_found),
                "products": changes_found,
            },
        }

    else:
        analysis = {
            "total_analyzed": len(trending),
            "avg_views": 0,
            "avg_viral_score": 0,
            "top_hashtags": [],
        }
        if trending:
            views_list = [v.get("views", 0) for v in trending]
            scores_list = [v.get("viral_score", 0) for v in trending]
            analysis["avg_views"] = int(sum(views_list) / len(views_list)) if views_list else 0
            analysis["avg_viral_score"] = round(sum(scores_list) / len(scores_list), 1) if scores_list else 0

            all_tags = []
            for v in trending:
                tags = v.get("hashtags", [])
                if isinstance(tags, list):
                    all_tags.extend(tags)
            from collections import Counter
            tag_counter = Counter(all_tags)
            analysis["top_hashtags"] = [t for t, _ in tag_counter.most_common(10)]

        return {
            "success": True,
            "result": {
                "focus": focus,
                "analysis": analysis,
            },
        }


async def _step_detect_trends(config: dict, context: dict, db: Session = None) -> dict:
    """Detect emerging trends from collected data."""
    days = config.get("days", 7)
    min_score = config.get("min_score", 50)
    limit = config.get("limit", 10)

    trends = []
    if db:
        since = datetime.utcnow() - timedelta(days=days)
        videos = (
            db.query(Video)
            .filter(Video.collected_at >= since, Video.viral_score >= min_score)
            .order_by(desc(Video.viral_score))
            .limit(limit * 3)
            .all()
        )

        hashtag_count = defaultdict(lambda: {"count": 0, "total_views": 0, "total_score": 0})
        for v in videos:
            tags = v.hashtags or []
            if isinstance(tags, str):
                tags = [t.strip() for t in tags.split(",") if t.strip()]
            for tag in tags:
                tag = tag.lower().strip("#")
                if tag and len(tag) >= 2:
                    hashtag_count[tag]["count"] += 1
                    hashtag_count[tag]["total_views"] += v.views
                    hashtag_count[tag]["total_score"] += v.viral_score

        sorted_tags = sorted(
            hashtag_count.items(),
            key=lambda x: x[1]["count"] * x[1]["total_score"],
            reverse=True,
        )

        for tag, stats in sorted_tags[:limit]:
            avg_score = stats["total_score"] / stats["count"] if stats["count"] else 0
            trends.append({
                "hashtag": tag,
                "mentions": stats["count"],
                "total_views": stats["total_views"],
                "avg_viral_score": round(avg_score, 1),
                "trending_level": "alto" if avg_score >= 70 else "medio" if avg_score >= 50 else "baixo",
            })

        trending_vids = []
        for v in videos[:limit]:
            trending_vids.append({
                "id": v.id,
                "title": v.title[:100],
                "platform": v.platform,
                "views": v.views,
                "likes": v.likes,
                "viral_score": v.viral_score,
                "hashtags": v.hashtags or [],
            })
        context["accumulated_data"]["trending_videos"] = trending_vids
    else:
        trends = [
            {"hashtag": "viral", "mentions": 15, "total_views": 2500000, "avg_viral_score": 78.5, "trending_level": "alto"},
            {"hashtag": "fyp", "mentions": 12, "total_views": 1800000, "avg_viral_score": 65.2, "trending_level": "medio"},
        ]

    context["accumulated_data"]["trends"] = trends

    return {
        "success": True,
        "result": {
            "trends_found": len(trends),
            "trends": trends,
            "period_days": days,
            "min_score_filter": min_score,
        },
    }


async def _step_send_alert(config: dict, context: dict) -> dict:
    """Send alert notification."""
    channel = config.get("channel", "telegram")
    template_name = config.get("template", "generic")

    accumulated = context.get("accumulated_data", {})
    trends = accumulated.get("trends", [])
    trending_videos = accumulated.get("trending_videos", [])
    script = accumulated.get("script", "")

    if template_name == "viral_alert":
        message_parts = ["📊 *Alerta Viral - AutoFlow*\n"]
        if trends:
            message_parts.append(f"🔥 {len(trends)} tendencias detectadas:\n")
            for t in trends[:5]:
                message_parts.append(f"  - #{t['hashtag']} ({t['mentions']}x, score {t['avg_viral_score']})")
        if trending_videos:
            message_parts.append(f"\n📹 Top videos:")
            for v in trending_videos[:3]:
                message_parts.append(f"  - {v['title'][:50]} ({v['views']:,} views)")
        message = "\n".join(message_parts)

    elif template_name == "weekly_report":
        summary = accumulated.get("summary", "Sem dados para o relatorio.")
        total_views = accumulated.get("total_views", 0)
        message = (
            f"📈 *Relatorio Semanal - AutoFlow*\n\n"
            f"Views totais: {total_views:,}\n\n"
            f"{summary}"
        )

    elif template_name == "price_change":
        products = accumulated.get("products", [])
        message = f"🛍️ *Alerta Shop - AutoFlow*\n\n{len(products)} produtos monitorados"
        for p in products[:5]:
            message += f"\n  - {p.get('title', 'Produto')[:40]}"

    elif template_name == "engagement_summary":
        message = "💬 *Resumo de Engajamento - AutoFlow*\n\nComentarios classificados e respondidos com sucesso."

    else:
        message = f"🔔 *AutoFlow Alert*\n\nWorkflow executado com sucesso."

    return {
        "success": True,
        "result": {
            "channel": channel,
            "message_preview": message[:300],
            "message_length": len(message),
            "status": "prepared",
            "note": "Mensagem preparada. Configure bot_token e chat_id para envio real.",
        },
    }


async def _step_classify_comments(config: dict, context: dict, db: Session = None) -> dict:
    """Classify comments by sentiment."""
    from backend.services.local_ai import analyze_sentiment

    limit = config.get("limit", 50)

    sample_comments = context.get("input_data", {}).get("comments", [])
    if not sample_comments:
        sample_comments = [
            "Muito bom esse conteudo!",
            "Nao gostei, podia ser melhor",
            "Faz mais videos assim por favor",
            "Perdi meu tempo assistindo",
            "Incrivel, compartilhei com todo mundo!",
            "Conteudo medio, ja vi melhor",
            "Amei! Quero mais dicas",
            "Que video maneiro, salvei aqui",
        ]

    classified = {"positivo": [], "negativo": [], "neutro": []}
    results = []
    for comment in sample_comments[:limit]:
        sentiment = analyze_sentiment(comment)
        label = sentiment.get("label", "neutro")
        classified[label].append(comment)
        results.append({"comment": comment, "sentiment": label, "score": sentiment.get("score", 0)})

    context["accumulated_data"]["classified_comments"] = classified
    context["accumulated_data"]["comment_results"] = results

    return {
        "success": True,
        "result": {
            "total_classified": len(results),
            "positivos": len(classified["positivo"]),
            "negativos": len(classified["negativo"]),
            "neutros": len(classified["neutro"]),
            "sample": results[:5],
        },
    }


async def _step_auto_reply(config: dict, context: dict) -> dict:
    """Generate automatic replies for comments."""
    from backend.services.local_ai import llm_chat

    reply_to = config.get("reply_to", "positive")
    max_replies = config.get("max_replies", 10)
    classified = context.get("accumulated_data", {}).get("classified_comments", {})

    if reply_to == "positive":
        target_comments = classified.get("positivo", [])
    elif reply_to == "negative":
        target_comments = classified.get("negativo", [])
    else:
        target_comments = classified.get("positivo", []) + classified.get("neutro", [])

    replies = []
    for comment in target_comments[:max_replies]:
        prompt = f"""Gere uma resposta curta e amigavel (max 2 frases) para este comentario em um video:
Comentario: "{comment}"

Resposta deve ser natural, como um criador de conteudo responderia. Sem emojis excessivos."""

        reply = await llm_chat(prompt, system="Voce e um criador de conteudo simpatico.", max_tokens=100)
        if not reply:
            reply = "Obrigado pelo comentario! Muito bom ter voce por aqui!"
        replies.append({"comment": comment, "reply": reply.strip()})

    return {
        "success": True,
        "result": {
            "replies_generated": len(replies),
            "target_sentiment": reply_to,
            "replies": replies,
        },
    }


async def _step_gap_analysis(config: dict, context: dict, db: Session = None) -> dict:
    """Identify content gaps by analyzing trends and competitors."""
    from backend.services.local_ai import llm_chat

    trending = context.get("accumulated_data", {}).get("trending_videos", [])
    trends = context.get("accumulated_data", {}).get("trends", [])

    trending_titles = [v.get("title", "") for v in trending[:10]]
    trending_tags = [t.get("hashtag", "") for t in trends[:10]]

    prompt = f"""Analise estas tendencias e identifique GAPS (lacunas de conteudo) que podem ser explorados:

Videos em alta:
{chr(10).join(f"- {t}" for t in trending_titles[:8]) if trending_titles else "- Sem dados de videos"}

Hashtags em alta:
{chr(10).join(f"- #{t}" for t in trending_tags[:8]) if trending_tags else "- Sem dados de hashtags"}

Identifique:
1. 3 nichos sub-explorados
2. 3 angulos originais para temas populares
3. 3 formatos que estao funcionando bem

Responda em formato de lista em portugues."""

    analysis = await llm_chat(
        prompt,
        system="Voce e um estrategista de conteudo digital especializado em videos curtos.",
        max_tokens=800,
    )
    if not analysis:
        analysis = (
            "Nichos sub-explorados:\n"
            "1. Conteudo educativo com humor\n"
            "2. Behind the scenes de processos criativos\n"
            "3. Micro-tutoriais de 15 segundos\n\n"
            "Angulos originais:\n"
            "1. Perspectiva contraria sobre temas populares\n"
            "2. Formato antes/depois com dados reais\n"
            "3. Colaboracoes inesperadas entre nichos\n\n"
            "Formatos eficazes:\n"
            "1. Listas rapidas (Top 3/5)\n"
            "2. POV storytelling\n"
            "3. Tutorial speed-run"
        )

    return {
        "success": True,
        "result": {
            "analysis": analysis,
            "videos_analyzed": len(trending_titles),
            "trends_analyzed": len(trending_tags),
        },
    }


async def _step_seo_optimize(config: dict, context: dict) -> dict:
    """Optimize title, description and hashtags for maximum reach."""
    from backend.services.local_ai import llm_chat

    platform = config.get("platform", "tiktok")
    batch = config.get("batch", False)
    script = context.get("accumulated_data", {}).get("script", "")
    topic = context.get("accumulated_data", {}).get("topic", "")

    content_to_optimize = topic if topic else script[:200]

    prompt = f"""Otimize o SEO para este conteudo de {platform}:

Conteudo: "{content_to_optimize}"

Gere:
1. TITULO (max 70 chars, com palavras-chave fortes)
2. DESCRICAO (max 150 chars, com CTA)
3. HASHTAGS (10 hashtags otimizadas, mix de populares e nicho)
4. HORARIO ideal para postar (baseado na plataforma {platform})

Formato:
TITULO: [titulo]
DESCRICAO: [descricao]
HASHTAGS: [hashtags separadas por espaco]
HORARIO: [horario recomendado]"""

    seo_result = await llm_chat(
        prompt,
        system=f"Voce e um especialista em SEO para {platform}.",
        max_tokens=500,
    )

    if not seo_result:
        seo_result = (
            f"TITULO: {content_to_optimize[:70]}\n"
            f"DESCRICAO: Descubra tudo sobre {content_to_optimize[:50]}! Salve e compartilhe!\n"
            f"HASHTAGS: #viral #fyp #{platform} #trending #dicas #conteudo #paratipage #brasil\n"
            "HORARIO: 18h-20h (horario de pico)"
        )

    parsed = {"raw": seo_result}
    for line in seo_result.split("\n"):
        line = line.strip()
        if line.upper().startswith("TITULO:"):
            parsed["title"] = line.split(":", 1)[-1].strip()
        elif line.upper().startswith("DESCRICAO:"):
            parsed["description"] = line.split(":", 1)[-1].strip()
        elif line.upper().startswith("HASHTAGS:"):
            parsed["hashtags"] = line.split(":", 1)[-1].strip()
        elif line.upper().startswith("HORARIO:"):
            parsed["best_time"] = line.split(":", 1)[-1].strip()

    return {
        "success": True,
        "result": {
            "platform": platform,
            "seo": parsed,
            "optimized": True,
        },
    }


async def _step_transcribe(config: dict, context: dict) -> dict:
    """Transcribe audio/video to text."""
    language = config.get("language", "pt")
    video_path = context.get("input_data", {}).get("video_path", "")

    if video_path:
        try:
            from backend.services.whisper_transcriber import transcribe_audio
            transcription = transcribe_audio(video_path, language=language)
            if transcription:
                context["accumulated_data"]["transcription"] = transcription
                return {
                    "success": True,
                    "result": {
                        "transcription": transcription,
                        "language": language,
                        "source": video_path,
                        "word_count": len(transcription.split()),
                    },
                }
        except Exception as e:
            logger.warning(f"Whisper transcription failed: {e}")

    sample_transcription = context.get("input_data", {}).get("text", "")
    if not sample_transcription:
        sample_transcription = (
            "Voce sabia que existem tecnicas simples para viralizar nas redes sociais? "
            "Hoje eu vou te mostrar as 3 principais estrategias que os maiores criadores usam. "
            "Primeiro, o hook nos primeiros 3 segundos e tudo. "
            "Segundo, entregue valor real em cada segundo do video. "
            "Terceiro, termine com um CTA forte que faca a pessoa comentar."
        )

    context["accumulated_data"]["transcription"] = sample_transcription

    return {
        "success": True,
        "result": {
            "transcription": sample_transcription,
            "language": language,
            "source": video_path or "input_text",
            "word_count": len(sample_transcription.split()),
        },
    }


async def _step_translate(config: dict, context: dict) -> dict:
    """Translate content between languages."""
    from backend.services.local_ai import llm_chat

    target_lang = config.get("target_language", "en")
    source_text = context.get("accumulated_data", {}).get("transcription", "")
    if not source_text:
        source_text = context.get("accumulated_data", {}).get("script", "")
    if not source_text:
        source_text = context.get("input_data", {}).get("text", "Texto de exemplo para traducao.")

    lang_names = {"en": "ingles", "es": "espanhol", "pt": "portugues", "fr": "frances", "de": "alemao"}
    lang_name = lang_names.get(target_lang, target_lang)

    prompt = f"""Traduza o seguinte texto para {lang_name}. Mantenha o tom e estilo:

{source_text[:1500]}"""

    translation = await llm_chat(prompt, system=f"Voce e um tradutor profissional para {lang_name}.", max_tokens=1500)
    if not translation:
        translation = f"[Traducao para {lang_name} nao disponivel - Ollama offline]"

    return {
        "success": True,
        "result": {
            "original_text": source_text[:200] + "..." if len(source_text) > 200 else source_text,
            "translated_text": translation,
            "target_language": target_lang,
            "word_count": len(translation.split()),
        },
    }


async def _step_batch_process(config: dict, context: dict, db: Session = None) -> dict:
    """Process multiple items in batch."""
    from backend.services.local_ai import llm_chat

    action = config.get("action", "generate_scripts")
    count = config.get("count", 5)

    if action == "generate_scripts":
        trends = context.get("accumulated_data", {}).get("trends", [])
        trending = context.get("accumulated_data", {}).get("trending_videos", [])

        topics = []
        for t in trends[:count]:
            topics.append(t.get("hashtag", ""))
        if len(topics) < count:
            for v in trending[:count - len(topics)]:
                topics.append(v.get("title", "")[:50])
        while len(topics) < count:
            topics.append(f"topico viral {len(topics) + 1}")

        scripts = []
        for i, topic in enumerate(topics[:count]):
            prompt = f"""Crie um roteiro curto de 30 segundos para video viral sobre: "{topic}"

Formato:
HOOK: [frase de 3 segundos]
CORPO: [conteudo principal]
CTA: [chamada para acao]

Seja breve e direto."""

            script = await llm_chat(
                prompt,
                system="Voce e um roteirista de videos virais.",
                max_tokens=500,
            )
            if not script:
                script = (
                    f"HOOK: Voce nao vai acreditar no que descobri sobre {topic}!\n"
                    f"CORPO: Aqui estao 3 fatos sobre {topic} que vao mudar sua perspectiva.\n"
                    "CTA: Comenta aqui qual fato mais te surpreendeu!"
                )

            scripts.append({
                "index": i + 1,
                "topic": topic,
                "script": script,
                "word_count": len(script.split()),
            })

        return {
            "success": True,
            "result": {
                "action": action,
                "total_generated": len(scripts),
                "scripts": scripts,
            },
        }

    else:
        return {
            "success": True,
            "result": {
                "action": action,
                "note": f"Acao '{action}' processada em lote",
                "count": count,
            },
        }


# ─── 12. estimate_workflow_cost ──────────────────────────────────

def estimate_workflow_cost(workflow_id: str) -> dict:
    """
    Estimate cost of running a workflow.
    All local AI = R$0. Only external API costs.
    """
    wf = _workflows.get(workflow_id)
    if not wf:
        return {"error": f"Workflow {workflow_id} nao encontrado"}

    step_costs = []
    total_cost = 0.0
    total_time_min = 0
    total_time_max = 0

    step_type_info = {s["type"]: s for s in get_available_step_types()}

    for step in wf["steps"]:
        stype = step.get("type", "")
        info = step_type_info.get(stype, {})

        cost_str = info.get("cost", "R$0 (local)")
        est_duration = info.get("estimated_duration", "5-15s")

        try:
            parts = est_duration.replace("s", "").split("-")
            t_min = int(parts[0])
            t_max = int(parts[1]) if len(parts) > 1 else t_min
        except (ValueError, IndexError):
            t_min, t_max = 5, 15

        total_time_min += t_min
        total_time_max += t_max

        step_cost = 0.0
        total_cost += step_cost

        step_costs.append({
            "step_name": step.get("name", stype),
            "step_type": stype,
            "cost": f"R${step_cost:.2f}",
            "estimated_time": est_duration,
            "engine": "local" if "local" in cost_str.lower() else "api",
        })

    return {
        "workflow_id": workflow_id,
        "workflow_name": wf["name"],
        "steps_count": len(wf["steps"]),
        "total_cost": f"R${total_cost:.2f}",
        "total_cost_value": total_cost,
        "estimated_time": f"{total_time_min}-{total_time_max}s",
        "cost_per_run": f"R${total_cost:.2f}",
        "monthly_estimate_daily": f"R${total_cost * 30:.2f}",
        "note": "Todas as operacoes de IA usam Ollama local (custo zero). Apenas APIs externas geram custo.",
        "step_costs": step_costs,
    }


# ─── 13. get_automation_stats ────────────────────────────────────

def get_automation_stats() -> dict:
    """
    Overall automation statistics:
    total workflows, runs today, success rate, avg duration, most used templates.
    """
    total_workflows = len(_workflows)
    all_runs = list(_workflow_runs.values())

    today_str = datetime.utcnow().strftime("%Y-%m-%d")
    runs_today = [
        r for r in all_runs
        if r.get("started_at", "").startswith(today_str)
    ]

    total_runs = len(all_runs)
    successful_runs = len([r for r in all_runs if r.get("status") == "success"])
    failed_runs = len([r for r in all_runs if r.get("status") == "failed"])
    partial_runs = len([r for r in all_runs if r.get("status") == "partial"])

    success_rate = (successful_runs / total_runs * 100) if total_runs > 0 else 0

    durations = [r.get("duration", 0) for r in all_runs if r.get("duration")]
    avg_duration = sum(durations) / len(durations) if durations else 0

    template_usage = defaultdict(int)
    for wf in _workflows.values():
        trigger_cfg = wf.get("trigger", {}).get("config", {})
        tmpl = trigger_cfg.get("from_template", "custom")
        template_usage[tmpl] += 1

    most_used = sorted(template_usage.items(), key=lambda x: x[1], reverse=True)

    steps_executed = sum(r.get("steps_completed", 0) for r in all_runs)

    active_workflows = len([wf for wf in _workflows.values() if wf.get("status") == "active"])

    return {
        "total_workflows": total_workflows,
        "active_workflows": active_workflows,
        "total_runs": total_runs,
        "runs_today": len(runs_today),
        "successful_runs": successful_runs,
        "failed_runs": failed_runs,
        "partial_runs": partial_runs,
        "success_rate": round(success_rate, 1),
        "avg_duration": round(avg_duration, 2),
        "total_steps_executed": steps_executed,
        "most_used_templates": [{"template": t, "count": c} for t, c in most_used[:5]],
        "cost_total": "R$0.00",
        "cost_note": "100% IA local via Ollama - custo zero",
    }


# ─── 14. content_factory_pipeline ────────────────────────────────

async def content_factory_pipeline(
    db: Session,
    topics: list = None,
    count: int = 5,
    niche: str = "",
) -> dict:
    """
    Content factory: takes topics or auto-detects trending,
    generates scripts for each, returns batch of ready-to-produce content.
    """
    from backend.services.local_ai import llm_chat

    start_time = time.time()

    # Step 1: Get topics
    final_topics = []
    if topics and len(topics) > 0:
        final_topics = [t.strip() for t in topics if t.strip()][:count]

    # Auto-detect trending if not enough topics provided
    if len(final_topics) < count and db:
        since = datetime.utcnow() - timedelta(days=3)
        query = db.query(Video).filter(
            Video.collected_at >= since,
            Video.viral_score >= 50,
        )
        if niche:
            query = query.filter(
                Video.description.ilike(f"%{niche}%")
                | Video.title.ilike(f"%{niche}%")
            )

        trending = (
            query.order_by(desc(Video.viral_score))
            .limit((count - len(final_topics)) * 2)
            .all()
        )

        seen_topics = set(t.lower() for t in final_topics)
        for v in trending:
            topic_candidate = v.title[:80] if v.title else ""
            if topic_candidate and topic_candidate.lower() not in seen_topics:
                final_topics.append(topic_candidate)
                seen_topics.add(topic_candidate.lower())
                if len(final_topics) >= count:
                    break

    # Fill remaining with AI-generated topics
    if len(final_topics) < count:
        niche_context = f" no nicho de {niche}" if niche else ""
        prompt = f"""Sugira {count - len(final_topics)} topicos virais para videos curtos{niche_context}.

Cada topico deve ser especifico e ter potencial viral.
Liste apenas os topicos, um por linha, sem numeracao."""

        ai_topics = await llm_chat(
            prompt,
            system="Voce e um especialista em conteudo viral para redes sociais brasileiras.",
            max_tokens=300,
        )
        if ai_topics:
            for line in ai_topics.split("\n"):
                line = line.strip().lstrip("0123456789.-) ")
                if line and len(line) > 5:
                    final_topics.append(line)
                    if len(final_topics) >= count:
                        break

    while len(final_topics) < count:
        defaults = [
            "3 habitos matinais de pessoas de sucesso",
            "Como ganhar dinheiro com IA em 2026",
            "Truques de edicao de video que ninguem te conta",
            "Erros que impedem seu conteudo de viralizar",
            "Como crescer de 0 a 10K seguidores rapido",
        ]
        for d in defaults:
            if d not in final_topics:
                final_topics.append(d)
                if len(final_topics) >= count:
                    break

    final_topics = final_topics[:count]

    # Step 2: Generate scripts for each topic
    content_batch = []
    for i, topic in enumerate(final_topics):
        niche_guide = f" Foco no nicho: {niche}." if niche else ""
        prompt = f"""Crie um roteiro COMPLETO de 30s para video viral sobre: "{topic}"{niche_guide}

Formato EXATO:
HOOK: [frase impactante de 3 segundos]
CORPO: [conteudo principal em 3-4 frases curtas]
CTA: [chamada para acao forte]
HASHTAGS: [8 hashtags otimizadas]
TITULO: [titulo otimizado para SEO, max 60 chars]"""

        script = await llm_chat(
            prompt,
            system="Voce e um roteirista profissional de videos virais.",
            max_tokens=800,
        )

        if not script:
            script = (
                f"HOOK: Isso vai mudar tudo que voce sabe sobre {topic}!\n\n"
                f"CORPO: Vou te revelar o segredo por tras de {topic}. "
                "A maioria das pessoas nao sabe disso. "
                "Mas os criadores de sucesso usam essa estrategia todos os dias. "
                "E o resultado e impressionante.\n\n"
                "CTA: Salva esse video e manda pra alguem que precisa ver isso!\n\n"
                f"HASHTAGS: #viral #fyp #dicas #{topic.split()[0].lower() if topic.split() else 'trending'} #conteudo\n\n"
                f"TITULO: {topic[:60]}"
            )

        # Parse the script
        parsed = {"raw": script, "topic": topic}
        for line in script.split("\n"):
            line = line.strip()
            upper = line.upper()
            if upper.startswith("HOOK:"):
                parsed["hook"] = line.split(":", 1)[-1].strip()
            elif upper.startswith("CORPO:"):
                parsed["body"] = line.split(":", 1)[-1].strip()
            elif upper.startswith("CTA:"):
                parsed["cta"] = line.split(":", 1)[-1].strip()
            elif upper.startswith("HASHTAGS:"):
                parsed["hashtags"] = line.split(":", 1)[-1].strip()
            elif upper.startswith("TITULO:"):
                parsed["title"] = line.split(":", 1)[-1].strip()

        content_batch.append({
            "index": i + 1,
            "topic": topic,
            "script": script,
            "parsed": parsed,
            "word_count": len(script.split()),
            "estimated_duration": f"{max(15, len(script.split()) // 3)}s",
            "status": "ready",
            "niche": niche,
        })

    total_duration = round(time.time() - start_time, 2)

    return {
        "total_generated": len(content_batch),
        "topics_used": final_topics,
        "niche": niche,
        "content": content_batch,
        "duration": total_duration,
        "cost": "R$0.00 (100% IA local)",
        "note": f"{len(content_batch)} roteiros prontos para producao gerados em {total_duration}s",
    }
