import json
import logging
from datetime import datetime, timedelta
from pathlib import Path

from fastapi import APIRouter, Depends, Query, HTTPException, BackgroundTasks, UploadFile, File

logger = logging.getLogger(__name__)
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session

from backend.database.connection import get_db
from backend.services import video_service
from backend.services.downloader import VideoDownloader
from backend.services.viral_detector import ViralDetector
from backend.services.sora_downloader import SoraDownloader
from backend.services.bulk_download import create_bulk_job, get_job_status, cancel_job
from backend.scrapers.youtube import YouTubeScraper
from backend.scrapers.tiktok import TikTokScraper
from backend.scrapers.instagram import InstagramScraper
from backend.models.video import Video
from backend.models.collection import Collection, VideoCollection
from backend.core.config import settings

router = APIRouter()
downloader = VideoDownloader()
detector = ViralDetector()
sora_downloader = SoraDownloader()


# ─── Scraper status endpoint ────────────────────────────────────

@router.get("/scraper/status")
def scraper_status():
    """Check which scrapers are properly configured."""
    return {
        "youtube": {
            "api_key": bool(settings.YOUTUBE_API_KEY),
            "fallback": "yt-dlp (funciona sem API key)",
            "status": "API configurada" if settings.YOUTUBE_API_KEY else "Usando yt-dlp (sem API key)",
        },
        "tiktok": {
            "cookies": bool(settings.TIKTOK_COOKIE_FILE or settings.COOKIES_FROM_BROWSER),
            "status": "Cookies configurados" if (settings.TIKTOK_COOKIE_FILE or settings.COOKIES_FROM_BROWSER) else "Sem cookies (pode ter limitações)",
        },
        "instagram": {
            "cookies": bool(settings.INSTAGRAM_COOKIE_FILE or settings.COOKIES_FROM_BROWSER),
            "status": "Cookies configurados" if (settings.INSTAGRAM_COOKIE_FILE or settings.COOKIES_FROM_BROWSER) else "Sem cookies (requer login para maioria das funções)",
        },
    }


# ─── Scraping endpoints ─────────────────────────────────────────

@router.post("/scrape/youtube")
def scrape_youtube(
    query: str = "",
    region: str = "BR",
    max_results: int = Query(default=25, le=50),
    trending: bool = False,
    db: Session = Depends(get_db),
):
    scraper = YouTubeScraper()
    try:
        if trending:
            videos_data = scraper.get_trending_videos(
                region=region, max_results=max_results
            )
        else:
            if not query and not scraper.has_api_key:
                query = "trending"
            videos_data = scraper.search_trending(
                query=query, region=region, max_results=max_results
            )
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erro ao buscar YouTube: {e}")

    if not videos_data:
        msg = "Nenhum vídeo encontrado no YouTube."
        if not scraper.has_api_key:
            msg += " Dica: configure YOUTUBE_API_KEY no .env para melhores resultados."
        return {
            "platform": "youtube",
            "found": 0,
            "saved": 0,
            "message": msg,
        }

    saved = video_service.save_videos(db, videos_data)
    method = "API" if scraper.has_api_key else "yt-dlp"
    return {
        "platform": "youtube",
        "found": len(videos_data),
        "saved": len(saved),
        "message": f"{len(saved)} vídeos do YouTube coletados (via {method})",
    }


@router.post("/scrape/tiktok")
def scrape_tiktok(
    query: str = "",
    hashtag: str = "",
    username: str = "",
    max_results: int = Query(default=20, le=50),
    db: Session = Depends(get_db),
):
    scraper = TikTokScraper()
    try:
        if hashtag:
            videos_data = scraper.get_hashtag_videos(hashtag, max_results)
        elif username:
            videos_data = scraper.get_user_videos(username, max_results)
        elif query:
            videos_data = scraper.search_videos(query, max_results)
        else:
            raise HTTPException(
                status_code=400, detail="Informe query, hashtag ou username"
            )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Erro ao buscar TikTok: {e}. Tente atualizar yt-dlp: pip install -U yt-dlp",
        )

    if not videos_data:
        msg = "Nenhum vídeo encontrado no TikTok."
        if not (settings.TIKTOK_COOKIE_FILE or settings.COOKIES_FROM_BROWSER):
            msg += " Dica: configure COOKIES_FROM_BROWSER=chrome no .env para melhores resultados."
        return {
            "platform": "tiktok",
            "found": 0,
            "saved": 0,
            "message": msg,
        }

    saved = video_service.save_videos(db, videos_data)
    return {
        "platform": "tiktok",
        "found": len(videos_data),
        "saved": len(saved),
        "message": f"{len(saved)} vídeos do TikTok coletados",
    }


@router.post("/scrape/instagram")
def scrape_instagram(
    hashtag: str = "",
    username: str = "",
    max_results: int = Query(default=20, le=50),
    db: Session = Depends(get_db),
):
    scraper = InstagramScraper()
    try:
        if hashtag:
            videos_data = scraper.search_hashtag(hashtag, max_results)
        elif username:
            videos_data = scraper.get_user_reels(username, max_results)
        else:
            videos_data = scraper.search_explore(max_results)
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Erro ao buscar Instagram: {e}. "
            "Instagram geralmente requer cookies de login.",
        )

    if not videos_data:
        has_cookies = bool(settings.INSTAGRAM_COOKIE_FILE or settings.COOKIES_FROM_BROWSER)
        msg = "Nenhum vídeo encontrado no Instagram."
        if not has_cookies:
            msg += " Instagram requer login. Configure COOKIES_FROM_BROWSER=chrome no .env."
        return {
            "platform": "instagram",
            "found": 0,
            "saved": 0,
            "message": msg,
        }

    saved = video_service.save_videos(db, videos_data)
    return {
        "platform": "instagram",
        "found": len(videos_data),
        "saved": len(saved),
        "message": f"{len(saved)} vídeos do Instagram coletados",
    }


# ─── Videos endpoints ────────────────────────────────────────────

@router.get("/videos")
def list_videos(
    platform: str = "",
    search: str = "",
    sort_by: str = "viral_score",
    min_score: float = 0,
    min_outlier: float = 0,
    creator_tier: str = "",
    language: str = "",
    limit: int = Query(default=50, le=200),
    offset: int = 0,
    db: Session = Depends(get_db),
):
    videos, total = video_service.get_videos(
        db,
        platform=platform,
        search=search,
        sort_by=sort_by,
        min_score=min_score,
        min_outlier=min_outlier,
        creator_tier=creator_tier,
        language=language,
        limit=limit,
        offset=offset,
    )

    return {
        "total": total,
        "limit": limit,
        "offset": offset,
        "videos": [_serialize_video(v) for v in videos],
    }


def _serialize_video(v):
    return {
        "id": v.id,
        "platform": v.platform,
        "external_id": v.external_id,
        "url": v.url,
        "title": v.title,
        "description": v.description[:200] if v.description else "",
        "hashtags": v.hashtags or [],
        "views": v.views,
        "views_formatted": v.views_formatted,
        "likes": v.likes,
        "comments": v.comments,
        "shares": v.shares,
        "duration": v.duration,
        "duration_formatted": v.duration_formatted,
        "thumbnail_url": v.thumbnail_url,
        "viral_score": v.viral_score,
        "viral_label": detector.get_viral_label(v.viral_score),
        "viral_color": detector.get_viral_color(v.viral_score),
        "engagement_rate": v.engagement_rate,
        "outlier_ratio": v.outlier_ratio,
        "outlier_label": detector.get_outlier_label(v.outlier_ratio),
        "creator_followers": v.creator_followers,
        "creator_avg_views": v.creator_avg_views,
        "views_per_follower": v.views_per_follower,
        "is_small_creator": v.is_small_creator,
        "replicability_score": v.replicability_score,
        "published_at": v.published_at.isoformat() if v.published_at else None,
        "collected_at": v.collected_at.isoformat() if v.collected_at else None,
        "is_downloaded": v.is_downloaded,
        "creator": {
            "username": v.creator.username if v.creator else "",
            "display_name": v.creator.display_name if v.creator else "",
            "platform": v.creator.platform if v.creator else "",
            "followers": v.creator.followers if v.creator else 0,
            "size_tier": v.creator.size_tier if v.creator else "unknown",
        } if v.creator else None,
    }


@router.get("/videos/{video_id}")
def get_video(video_id: int, db: Session = Depends(get_db)):
    video = video_service.get_video_by_id(db, video_id)
    if not video:
        raise HTTPException(status_code=404, detail="Vídeo não encontrado")
    return {"video": video}


# ─── Download endpoints ──────────────────────────────────────────

@router.post("/download/url")
def download_url(
    url: str,
    quality: str = "best",
):
    # Use Sora downloader for sora.chatgpt.com URLs
    if SoraDownloader.is_sora_url(url):
        return sora_downloader.download(url, quality)
    result = downloader.download(url=url, quality=quality)
    return result


# Bulk endpoints MUST come before /download/{video_id} to avoid route conflict
@router.post("/download/bulk")
def start_bulk_download(
    urls: str,
    quality: str = "best",
):
    """Start a bulk download job. URLs separated by newlines."""
    url_list = [u.strip() for u in urls.split("\n") if u.strip()]
    try:
        job = create_bulk_job(url_list, quality)
        return job
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/download/bulk/{job_id}/status")
def bulk_download_status(job_id: str):
    """Poll the status of a bulk download job."""
    status = get_job_status(job_id)
    if not status:
        raise HTTPException(status_code=404, detail="Job não encontrado")
    return status


@router.post("/download/bulk/{job_id}/cancel")
def cancel_bulk_download(job_id: str):
    """Cancel a running bulk download job."""
    if cancel_job(job_id):
        return {"message": "Download cancelado"}
    raise HTTPException(status_code=400, detail="Job não pode ser cancelado")


@router.post("/download/{video_id}")
def download_video(
    video_id: int,
    quality: str = "best",
    db: Session = Depends(get_db),
):
    video = video_service.get_video_by_id(db, video_id)
    if not video:
        raise HTTPException(status_code=404, detail="Vídeo não encontrado")

    result = downloader.download(
        url=video.url,
        platform=video.platform,
        quality=quality,
        video_id=video.external_id,
    )

    if result["success"]:
        video.is_downloaded = True
        video.download_path = result["path"]
        db.commit()

    return result


@router.get("/downloads/file")
def serve_download_file(path: str):
    """Serve a downloaded file for browser download."""
    file_path = Path(path)
    # Security: ensure the file is within our downloads directory
    try:
        resolved = file_path.resolve()
        base_resolved = settings.download_path.resolve()
        if not str(resolved).startswith(str(base_resolved)):
            raise HTTPException(status_code=403, detail="Acesso negado")
    except Exception:
        raise HTTPException(status_code=403, detail="Caminho inválido")

    if not file_path.exists():
        raise HTTPException(status_code=404, detail="Arquivo não encontrado")

    # Sanitize filename for HTTP headers (replace non-ASCII chars)
    import unicodedata
    safe_name = file_path.name
    try:
        safe_name.encode("latin-1")
    except UnicodeEncodeError:
        safe_name = unicodedata.normalize("NFKD", safe_name)
        safe_name = safe_name.encode("ascii", "ignore").decode("ascii")
        if not safe_name:
            safe_name = "download.mp4"

    from urllib.parse import quote
    # Use RFC 5987 for non-ASCII filenames
    encoded_name = quote(file_path.name)

    return FileResponse(
        path=str(file_path),
        filename=safe_name,
        media_type="video/mp4",
        headers={
            "Content-Disposition": f"attachment; filename=\"{safe_name}\"; filename*=UTF-8''{encoded_name}"
        },
    )


def _get_oembed_thumbnail(external_id: str) -> str | None:
    """Get fresh thumbnail URL via TikTok oEmbed API (works when CDN URLs expire)."""
    import urllib.request
    import json as _json
    try:
        url = f"https://www.tiktok.com/oembed?url=https://www.tiktok.com/@user/video/{external_id}"
        req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
        resp = urllib.request.urlopen(req, timeout=8)
        data = _json.loads(resp.read())
        return data.get("thumbnail_url", "")
    except Exception:
        return None


@router.get("/thumbnail/{video_id}")
def proxy_thumbnail(video_id: int, db: Session = Depends(get_db)):
    """Proxy, convert to JPEG, compress <100KB and cache thumbnails."""
    import io
    import httpx

    cache_dir = Path(settings.BASE_DIR) / "data" / "thumbs"
    cache_dir.mkdir(parents=True, exist_ok=True)
    cache_file = cache_dir / f"{video_id}.jpg"
    placeholder = cache_dir / "placeholder.jpg"

    if cache_file.exists() and cache_file.stat().st_size > 500:
        return FileResponse(str(cache_file), media_type="image/jpeg",
                          headers={"Cache-Control": "public, max-age=604800"})

    video = db.query(Video).filter(Video.id == video_id).first()
    if not video or not video.thumbnail_url:
        if placeholder.exists():
            return FileResponse(str(placeholder), media_type="image/jpeg",
                              headers={"Cache-Control": "public, max-age=86400"})
        raise HTTPException(status_code=404, detail="Thumbnail not found")

    try:
        r = httpx.get(video.thumbnail_url, timeout=10, follow_redirects=True,
                     headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"})
        # If original URL fails (403/expired), try TikTok oEmbed API
        if r.status_code != 200 or len(r.content) < 100:
            thumb_url = _get_oembed_thumbnail(video.external_id)
            if thumb_url:
                r = httpx.get(thumb_url, timeout=10, follow_redirects=True,
                             headers={"User-Agent": "Mozilla/5.0"})
                if r.status_code == 200 and len(r.content) >= 100:
                    # Update DB with working URL
                    video.thumbnail_url = thumb_url
                    db.commit()
            if r.status_code != 200 or len(r.content) < 100:
                raise HTTPException(status_code=404, detail="Could not fetch thumbnail")

        # Convert any format (HEIC, AVIF, WEBP, PNG) to compressed JPEG
        from PIL import Image
        try:
            import pillow_heif
            pillow_heif.register_heif_opener()
        except ImportError:
            pass

        img = Image.open(io.BytesIO(r.content))
        img = img.convert("RGB")

        # Resize if too large (max 640px wide for thumbnails)
        if img.width > 640:
            ratio = 640 / img.width
            img = img.resize((640, int(img.height * ratio)), Image.LANCZOS)

        # Compress to JPEG, target <100KB
        quality = 82
        for q in [82, 70, 55, 40]:
            buf = io.BytesIO()
            img.save(buf, format="JPEG", quality=q, optimize=True)
            if buf.tell() <= 100_000:
                quality = q
                break
            quality = q

        buf = io.BytesIO()
        img.save(buf, format="JPEG", quality=quality, optimize=True)
        cache_file.write_bytes(buf.getvalue())

        return FileResponse(str(cache_file), media_type="image/jpeg",
                          headers={"Cache-Control": "public, max-age=604800"})
    except HTTPException:
        raise
    except Exception:
        # Return placeholder on any failure
        if placeholder.exists():
            return FileResponse(str(placeholder), media_type="image/jpeg",
                              headers={"Cache-Control": "public, max-age=3600"})
        raise HTTPException(status_code=404, detail="Thumbnail not available")


@router.get("/echotik/image/{img_type}/{img_id}.jpg")
def echotik_image_proxy(img_type: str, img_id: str):
    """Download, cache and serve EchoTik images locally.

    img_type: products, sellers, creators, videos
    img_id: product_id, seller_id, user_id, or video_id
    """
    import io
    import httpx

    VALID_TYPES = {"products", "sellers", "creators", "videos"}
    if img_type not in VALID_TYPES:
        raise HTTPException(status_code=400, detail=f"Tipo invalido. Use: {VALID_TYPES}")

    cache_dir = Path(settings.BASE_DIR) / "data" / "echotik" / img_type
    cache_dir.mkdir(parents=True, exist_ok=True)
    cache_file = cache_dir / f"{img_id}.jpg"

    # Serve from cache if exists
    if cache_file.exists() and cache_file.stat().st_size > 500:
        return FileResponse(str(cache_file), media_type="image/jpeg",
                          headers={"Cache-Control": "public, max-age=2592000"})

    # Lookup URL from DB cache
    from backend.models.settings import AppSettings
    from backend.database.connection import SessionLocal
    db = SessionLocal()
    try:
        cache_key = f"echotik_img_{img_type}_{img_id}"
        row = db.query(AppSettings).filter(AppSettings.key == cache_key).first()
        if not row or not row.value:
            # No cached URL - generate placeholder directly
            _generate_placeholder(cache_file, img_id, img_type)
            return FileResponse(str(cache_file), media_type="image/jpeg",
                              headers={"Cache-Control": "public, max-age=3600"})
        source_url = row.value
    finally:
        db.close()

    try:
        r = httpx.get(source_url, timeout=15, follow_redirects=True,
                     headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"})
        if r.status_code == 200 and len(r.content) > 100:
            from PIL import Image as PILImage
            img = PILImage.open(io.BytesIO(r.content))
            img = img.convert("RGB")

            # Resize based on type
            max_w = 400 if img_type in ("products", "sellers") else 200 if img_type == "creators" else 480
            if img.width > max_w:
                ratio = max_w / img.width
                img = img.resize((max_w, int(img.height * ratio)), PILImage.LANCZOS)

            # Compress to JPEG
            buf = io.BytesIO()
            img.save(buf, format="JPEG", quality=80, optimize=True)
            cache_file.write_bytes(buf.getvalue())

            return FileResponse(str(cache_file), media_type="image/jpeg",
                              headers={"Cache-Control": "public, max-age=2592000"})

        # If download failed (403 etc), generate a colored placeholder
        _generate_placeholder(cache_file, img_id, img_type)
        return FileResponse(str(cache_file), media_type="image/jpeg",
                          headers={"Cache-Control": "public, max-age=86400"})
    except Exception:
        _generate_placeholder(cache_file, img_id, img_type)
        return FileResponse(str(cache_file), media_type="image/jpeg",
                          headers={"Cache-Control": "public, max-age=86400"})


def _generate_placeholder(path: Path, img_id: str, img_type: str):
    """Generate a colored placeholder image with initials."""
    import io
    from PIL import Image as PILImage, ImageDraw, ImageFont

    # Color based on hash of ID
    h = hash(img_id) % 360
    colors = [
        (124, 58, 237), (239, 68, 68), (16, 185, 129), (245, 158, 11),
        (59, 130, 246), (236, 72, 153), (6, 182, 212), (168, 85, 247),
    ]
    bg = colors[hash(img_id) % len(colors)]

    size = (400, 400) if img_type == "products" else (200, 200)
    img = PILImage.new("RGB", size, bg)
    draw = ImageDraw.Draw(img)

    # Draw initials
    text = img_id[-4:] if img_type == "products" else img_id[-2:]
    try:
        font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", size[0] // 4)
    except Exception:
        font = ImageFont.load_default()
    bbox = draw.textbbox((0, 0), text, font=font)
    tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
    draw.text(((size[0] - tw) / 2, (size[1] - th) / 2 - bbox[1]), text, fill=(255, 255, 255, 200), font=font)

    buf = io.BytesIO()
    img.save(buf, format="JPEG", quality=70)
    path.write_bytes(buf.getvalue())


@router.get("/downloads")
def list_downloads(platform: str = ""):
    return {"files": downloader.list_downloads(platform)}


# ─── Collections endpoints ───────────────────────────────────────

@router.get("/collections")
def list_collections(db: Session = Depends(get_db)):
    collections = db.query(Collection).all()
    return {
        "collections": [
            {
                "id": c.id,
                "name": c.name,
                "description": c.description,
                "color": c.color,
                "video_count": c.video_count,
                "created_at": c.created_at.isoformat(),
            }
            for c in collections
        ]
    }


@router.post("/collections")
def create_collection(
    name: str, description: str = "", color: str = "#6366f1",
    db: Session = Depends(get_db),
):
    collection = Collection(name=name, description=description, color=color)
    db.add(collection)
    db.commit()
    return {"id": collection.id, "name": collection.name}


@router.post("/collections/{collection_id}/videos/{video_id}")
def add_video_to_collection(
    collection_id: int,
    video_id: int,
    notes: str = "",
    tags: str = "",
    db: Session = Depends(get_db),
):
    vc = VideoCollection(
        video_id=video_id,
        collection_id=collection_id,
        notes=notes,
        tags=tags,
    )
    db.add(vc)
    db.commit()
    return {"message": "Vídeo adicionado à coleção"}


# ─── Stats endpoint ──────────────────────────────────────────────

@router.get("/stats")
def get_stats(db: Session = Depends(get_db)):
    return video_service.get_stats(db)


# ─── Trends & Analysis endpoints (Phase 2) ──────────────────────

from backend.services.trend_analyzer import TrendAnalyzer
from backend.services.creator_service import CreatorService

trend_analyzer = TrendAnalyzer()
creator_service = CreatorService()


@router.get("/trends/hashtags")
def get_trending_hashtags(
    platform: str = "",
    days: int = Query(default=7, le=90),
    limit: int = Query(default=30, le=100),
    db: Session = Depends(get_db),
):
    hashtags = trend_analyzer.analyze_hashtags(db, platform, days, limit)
    trend_analyzer.save_hashtag_trends(db, hashtags)
    return {"hashtags": hashtags, "period_days": days}


@router.get("/trends/patterns")
def get_content_patterns(
    platform: str = "",
    days: int = Query(default=30, le=90),
    db: Session = Depends(get_db),
):
    patterns = trend_analyzer.analyze_content_patterns(db, platform, days)
    return patterns


@router.get("/trends/now")
def get_trending_now(
    hours: int = Query(default=48, le=168),
    limit: int = Query(default=20, le=50),
    db: Session = Depends(get_db),
):
    trending = trend_analyzer.get_trending_now(db, hours, limit)
    return {"trending": trending}


# ─── Creators endpoints (Phase 2) ───────────────────────────────

@router.get("/creators")
def list_creators(
    platform: str = "",
    tracked_only: bool = False,
    search: str = "",
    sort_by: str = "followers",
    limit: int = Query(default=50, le=200),
    offset: int = 0,
    db: Session = Depends(get_db),
):
    creators, total = creator_service.get_creators(
        db, platform, tracked_only, search, sort_by, limit, offset
    )
    return {"creators": creators, "total": total}


@router.post("/creators/{creator_id}/track")
def toggle_creator_tracking(creator_id: int, db: Session = Depends(get_db)):
    return creator_service.toggle_tracking(db, creator_id)


@router.get("/creators/{creator_id}/videos")
def get_creator_videos(
    creator_id: int,
    limit: int = Query(default=50, le=200),
    db: Session = Depends(get_db),
):
    videos = creator_service.get_creator_videos(db, creator_id, limit)
    return {"videos": videos}


@router.post("/creators/{creator_id}/refresh")
def refresh_creator_stats(creator_id: int, db: Session = Depends(get_db)):
    return creator_service.update_creator_stats(db, creator_id)


@router.get("/creators/tracked/summary")
def tracked_creators_summary(db: Session = Depends(get_db)):
    return creator_service.get_tracked_summary(db)


# ─── Scheduler endpoints (Phase 3) ──────────────────────────────

from backend.services.scheduler import (
    get_schedule_config, update_schedule, get_job_log,
    scrape_youtube_job, scrape_tiktok_job, scrape_instagram_job,
    discovery_job,
)


@router.get("/scheduler/config")
def scheduler_config():
    return get_schedule_config()


@router.post("/scheduler/config")
def update_scheduler_config(
    enabled: bool = False,
    interval_hours: int = 6,
    yt_enabled: bool = True,
    yt_query: str = "",
    yt_region: str = "BR",
    tt_enabled: bool = False,
    tt_query: str = "",
    tt_hashtag: str = "",
    ig_enabled: bool = False,
    ig_hashtag: str = "",
    ig_username: str = "",
    db: Session = Depends(get_db),
):
    # Load scanner settings from DB to include in schedule config
    from backend.models.settings import AppSettings
    scanner_rows = db.query(AppSettings).filter(AppSettings.category == "scanner").all()
    scanner_settings = {r.key: r.value for r in scanner_rows}

    scanner_enabled = scanner_settings.get("scanner_enabled", "false").lower() == "true"
    cc_enabled = scanner_settings.get("scanner_creative_center_enabled", "true").lower() == "true"
    scanner_minutes = int(scanner_settings.get("scanner_interval_minutes", "30"))
    cc_minutes = int(scanner_settings.get("scanner_creative_center_interval_minutes", "60"))

    config = {
        "enabled": enabled,
        "interval_hours": interval_hours,
        "youtube": {"enabled": yt_enabled, "query": yt_query, "region": yt_region, "max_results": 25},
        "tiktok": {"enabled": tt_enabled, "query": tt_query, "hashtag": tt_hashtag, "max_results": 20},
        "instagram": {"enabled": ig_enabled, "hashtag": ig_hashtag, "username": ig_username, "max_results": 20},
        "scanner": {
            "enabled": scanner_enabled,
            "interval_minutes": scanner_minutes,
            "creative_center_enabled": cc_enabled,
            "creative_center_interval_minutes": cc_minutes,
        },
    }
    update_schedule(config)
    return {"message": "Configuração atualizada", "config": get_schedule_config()}


@router.get("/scheduler/log")
def scheduler_log():
    return {"log": get_job_log()}


@router.post("/scheduler/run-now")
def run_scrape_now(
    platform: str = "youtube",
    query: str = "",
    hashtag: str = "",
    username: str = "",
    region: str = "BR",
    background_tasks: BackgroundTasks = None,
):
    if platform == "discovery":
        discovery_job(region=region)
        return {"message": "Discovery completo executado (todas as plataformas + todas as fontes)"}
    elif platform == "youtube":
        scrape_youtube_job(query=query)
    elif platform == "tiktok":
        scrape_tiktok_job(query=query, hashtag=hashtag)
    elif platform == "instagram":
        scrape_instagram_job(hashtag=hashtag, username=username)
    return {"message": f"Coleta de {platform} executada"}


# ─── Export endpoints (Phase 3) ──────────────────────────────────

from fastapi.responses import StreamingResponse
from backend.services.exporter import Exporter

exporter = Exporter()


@router.get("/export/videos/csv")
def export_videos_csv(platform: str = "", min_score: float = 0, db: Session = Depends(get_db)):
    csv_data = exporter.export_videos_csv(db, platform, min_score)
    return StreamingResponse(
        iter([csv_data]),
        media_type="text/csv",
        headers={"Content-Disposition": "attachment; filename=viral_social_videos.csv"},
    )


@router.get("/export/videos/excel")
def export_videos_excel(platform: str = "", min_score: float = 0, db: Session = Depends(get_db)):
    excel_data = exporter.export_videos_excel(db, platform, min_score)
    return StreamingResponse(
        iter([excel_data]),
        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        headers={"Content-Disposition": "attachment; filename=viral_social_report.xlsx"},
    )


@router.get("/export/creators/csv")
def export_creators_csv(tracked_only: bool = False, db: Session = Depends(get_db)):
    csv_data = exporter.export_creators_csv(db, tracked_only)
    return StreamingResponse(
        iter([csv_data]),
        media_type="text/csv",
        headers={"Content-Disposition": "attachment; filename=viral_social_creators.csv"},
    )


# ─── Alerts endpoints (Phase 3) ─────────────────────────────────

from backend.services import alerts as alerts_service


@router.get("/alerts")
def get_alerts(limit: int = Query(default=50, le=200)):
    return {"alerts": alerts_service.get_alerts(limit), "unread": alerts_service.get_unread_count()}


@router.post("/alerts/check")
def check_alerts(db: Session = Depends(get_db)):
    result = alerts_service.run_all_checks(db)
    return result


@router.post("/alerts/{alert_id}/read")
def mark_alert_read(alert_id: int):
    alerts_service.mark_alert_read(alert_id)
    return {"message": "Alerta marcado como lido"}


@router.post("/alerts/clear")
def clear_alerts():
    alerts_service.clear_alerts()
    return {"message": "Alertas limpos"}


# ─── Hashtag Research endpoints (Phase 4) ────────────────────────

from backend.services.hashtag_research import HashtagResearch

hashtag_research = HashtagResearch()


@router.get("/hashtags/research")
def research_hashtags(
    seed: str = "",
    platform: str = "",
    days: int = Query(default=30, le=90),
    limit: int = Query(default=30, le=100),
    db: Session = Depends(get_db),
):
    return hashtag_research.research(db, seed, platform, days, limit)


@router.get("/hashtags/suggest")
def suggest_hashtag_combo(
    platform: str = "",
    count: int = Query(default=5, le=15),
    db: Session = Depends(get_db),
):
    combo = hashtag_research.suggest_combo(db, platform, count)
    return {"suggested_hashtags": combo, "formatted": " ".join(f"#{h}" for h in combo)}


# ─── Content Calendar endpoints (Phase 4) ────────────────────────

from backend.services.content_calendar import ContentCalendar

calendar_service = ContentCalendar()


# ─── Discovery Engine endpoints ──────────────────────────────

from backend.services.discovery import ViralDiscovery

discovery = ViralDiscovery()


@router.get("/discover/all")
def discover_all_platforms(
    region: str = "BR",
    max_per_platform: int = Query(default=50, le=100),
    db: Session = Depends(get_db),
):
    """
    Master discovery: find viral videos from ALL platforms using ALL sources.
    Free sources are always used. Paid sources used if configured.
    """
    results = discovery.discover_all(
        region=region, max_per_platform=max_per_platform
    )

    # Save everything to database
    all_videos = results["youtube"] + results["tiktok"] + results["instagram"]
    if all_videos:
        saved = video_service.save_videos(db, all_videos)
        results["saved_to_db"] = len(saved)
    else:
        results["saved_to_db"] = 0

    return results


@router.get("/discover/youtube")
def discover_youtube(
    region: str = "BR",
    max_results: int = Query(default=50, le=100),
    db: Session = Depends(get_db),
):
    """Discover viral YouTube content from all available sources."""
    videos, sources = discovery.discover_youtube(region, max_results)
    if videos:
        saved = video_service.save_videos(db, videos)
    else:
        saved = []
    return {
        "platform": "youtube",
        "found": len(videos),
        "saved": len(saved),
        "sources_used": sources,
        "videos": videos[:20],  # Preview first 20
    }


@router.get("/discover/tiktok")
def discover_tiktok(
    region: str = "BR",
    max_results: int = Query(default=50, le=100),
    db: Session = Depends(get_db),
):
    """Discover viral TikTok content from all available sources."""
    videos, sources = discovery.discover_tiktok(region, max_results)
    if videos:
        saved = video_service.save_videos(db, videos)
    else:
        saved = []
    return {
        "platform": "tiktok",
        "found": len(videos),
        "saved": len(saved),
        "sources_used": sources,
        "videos": videos[:20],
    }


@router.get("/discover/instagram")
def discover_instagram(
    max_results: int = Query(default=50, le=100),
    db: Session = Depends(get_db),
):
    """Discover viral Instagram content from all available sources."""
    videos, sources = discovery.discover_instagram(max_results)
    if videos:
        saved = video_service.save_videos(db, videos)
    else:
        saved = []
    return {
        "platform": "instagram",
        "found": len(videos),
        "saved": len(saved),
        "sources_used": sources,
        "videos": videos[:20],
    }


@router.get("/discover/trending-hashtags")
def discover_trending_hashtags(region: str = "BR"):
    """Get trending hashtags from all available sources."""
    return discovery.discover_trending_hashtags(region)


@router.get("/discover/sources")
def discover_sources_status():
    """Check which data sources are configured and available."""
    return discovery.get_source_status()


# ─── Ideas (Banco de Ideias) ────────────────────────────────────

@router.get("/ideas")
def list_ideas(db: Session = Depends(get_db)):
    from backend.models.idea import Idea
    ideas = db.query(Idea).order_by(Idea.created_at.desc()).all()
    return [i.to_dict() for i in ideas]


@router.post("/ideas")
def create_idea(
    db: Session = Depends(get_db),
    title: str = "",
    url: str = "",
    platform: str = "",
    thumbnail_url: str = "",
    notes: str = "",
    status: str = "idea",
    video_id: int = None,
):
    from backend.models.idea import Idea
    idea = Idea(
        title=title, url=url, platform=platform,
        thumbnail_url=thumbnail_url, notes=notes,
        status=status, video_id=video_id,
    )
    db.add(idea)
    db.commit()
    return idea.to_dict()


@router.put("/ideas/{idea_id}")
def update_idea(idea_id: int, db: Session = Depends(get_db), title: str = None, url: str = None, platform: str = None, notes: str = None):
    from backend.models.idea import Idea
    idea = db.query(Idea).filter(Idea.id == idea_id).first()
    if not idea:
        raise HTTPException(status_code=404, detail="Ideia nao encontrada")
    if title is not None: idea.title = title
    if url is not None: idea.url = url
    if platform is not None: idea.platform = platform
    if notes is not None: idea.notes = notes
    db.commit()
    return idea.to_dict()


@router.post("/ideas/{idea_id}/move")
def move_idea(idea_id: int, status: str = "idea", db: Session = Depends(get_db)):
    from backend.models.idea import Idea
    idea = db.query(Idea).filter(Idea.id == idea_id).first()
    if not idea:
        raise HTTPException(status_code=404, detail="Ideia nao encontrada")
    idea.status = status
    db.commit()
    return idea.to_dict()


@router.delete("/ideas/{idea_id}")
def delete_idea(idea_id: int, db: Session = Depends(get_db)):
    from backend.models.idea import Idea
    idea = db.query(Idea).filter(Idea.id == idea_id).first()
    if not idea:
        raise HTTPException(status_code=404, detail="Ideia nao encontrada")
    db.delete(idea)
    db.commit()
    return {"message": "Ideia removida"}


# ─── Opportunities & Explosions ──────────────────────────────────

@router.get("/opportunities")
def get_opportunities(
    platform: str = "",
    limit: int = Query(default=30, le=100),
    db: Session = Depends(get_db),
):
    """Get replicable viral content opportunities."""
    videos = video_service.get_opportunities(db, platform, limit)
    return {
        "total": len(videos),
        "videos": [_serialize_video(v) for v in videos],
    }


@router.get("/explosions")
def get_explosions(
    min_outlier: float = 10,
    limit: int = Query(default=20, le=100),
    db: Session = Depends(get_db),
):
    """Get videos with explosive outlier ratios."""
    videos = video_service.get_explosions(db, min_outlier, limit)
    return {
        "total": len(videos),
        "videos": [_serialize_video(v) for v in videos],
    }


@router.get("/videos/{video_id}/growth")
def get_video_growth(video_id: int, db: Session = Depends(get_db)):
    """Get growth tracking data for a video."""
    from backend.services.growth_tracker import GrowthTracker
    video = video_service.get_video_by_id(db, video_id)
    if not video:
        raise HTTPException(status_code=404, detail="Video nao encontrado")
    tracker = GrowthTracker()
    return tracker.get_growth_data(video)


@router.post("/baselines/update")
def update_baselines(db: Session = Depends(get_db)):
    """Recalculate creator baselines."""
    from backend.services.creator_baseline import CreatorBaselineService
    svc = CreatorBaselineService()
    updated = svc.update_all_baselines(db)
    return {"message": f"{updated} baselines atualizados"}


# ─── Intelligence (Platform Stats) ──────────────────────────────

@router.get("/intelligence/platform-stats")
def intelligence_platform_stats(db: Session = Depends(get_db)):
    from sqlalchemy import func
    results = []
    for platform in ["youtube", "tiktok", "instagram"]:
        q = db.query(Video).filter(Video.platform == platform)
        count = q.count()
        if count == 0:
            continue
        avg_score = db.query(func.avg(Video.viral_score)).filter(Video.platform == platform).scalar() or 0
        avg_views = db.query(func.avg(Video.views)).filter(Video.platform == platform).scalar() or 0
        viral_count = q.filter(Video.viral_score >= 60).count()

        total_eng = 0
        videos = q.limit(200).all()
        for v in videos:
            if v.views and v.views > 0:
                total_eng += ((v.likes or 0) + (v.comments or 0) + (v.shares or 0)) / v.views * 100
        avg_eng = total_eng / len(videos) if videos else 0

        results.append({
            "platform": platform,
            "count": count,
            "avg_score": round(float(avg_score), 1),
            "avg_views": int(avg_views),
            "avg_engagement": round(avg_eng, 2),
            "viral_count": viral_count,
            "viral_percent": round(viral_count / count * 100) if count else 0,
        })
    return results


# ─── TikTok Shop endpoints (EchoTik is now the primary source) ────


@router.get("/shop/products")
def shop_saved_products(
    search: str = "",
    sort_by: str = "sold_count",
    limit: int = Query(default=50, le=200),
    offset: int = 0,
    db: Session = Depends(get_db),
):
    """List saved TikTok Shop products from database."""
    from backend.models.product import Product
    q = db.query(Product)
    if search:
        q = q.filter(Product.title.ilike(f"%{search}%"))
    if sort_by == "sold_count":
        q = q.order_by(Product.sold_count.desc())
    elif sort_by == "rating":
        q = q.order_by(Product.rating.desc())
    elif sort_by == "review_count":
        q = q.order_by(Product.review_count.desc())
    elif sort_by == "recent":
        q = q.order_by(Product.collected_at.desc())
    else:
        q = q.order_by(Product.sold_count.desc())
    total = q.count()
    products = q.offset(offset).limit(limit).all()
    return {
        "total": total,
        "products": [p.to_dict() for p in products],
    }


# /shop/viral-products removido - usar /api/echotik/product/ranking


# ─── Shop Intelligence (Revenue, Cross-Platform, Categories BR) ──


@router.get("/shop/categories")
def shop_categories_br():
    """Get Brazil TikTok Shop categories with keywords."""
    from backend.services.shop_intelligence import BR_CATEGORIES
    return {"categories": BR_CATEGORIES}


# /shop/category/{category} removido - usar /api/echotik/product/search


@router.post("/shop/monitor/{product_id}")
def monitor_product(
    product_id: str,
    db: Session = Depends(get_db),
):
    """Start monitoring a product by taking the first snapshot."""
    from backend.services.shop_intelligence import take_snapshot
    from backend.models.product import Product
    product = db.query(Product).filter(Product.product_id == product_id).first()
    if not product:
        raise HTTPException(status_code=404, detail="Produto nao encontrado no banco de dados")
    snapshot = take_snapshot(db, product_id, {
        "sold_count": product.sold_count,
        "stock": product.stock,
        "price": product.price,
        "rating": product.rating,
        "review_count": product.review_count,
    })
    return {"status": "monitoring", "snapshot": snapshot.to_dict()}


@router.post("/shop/snapshot/{product_id}")
def take_product_snapshot(
    product_id: str,
    db: Session = Depends(get_db),
):
    """Take a snapshot of a product using current DB data."""
    from backend.services.shop_intelligence import take_snapshot
    from backend.models.product import Product
    product = db.query(Product).filter(Product.product_id == product_id).first()
    if not product:
        raise HTTPException(status_code=404, detail="Produto nao encontrado")
    snapshot = take_snapshot(db, product_id, {
        "sold_count": product.sold_count,
        "stock": product.stock,
        "price": product.price,
        "rating": product.rating,
        "review_count": product.review_count,
    })
    return {"status": "ok", "snapshot": snapshot.to_dict()}


@router.get("/shop/revenue/{product_id}")
def product_revenue(
    product_id: str,
    days: int = Query(default=30, le=90),
    db: Session = Depends(get_db),
):
    """Get revenue tracking data for a monitored product."""
    from backend.services.shop_intelligence import get_revenue_data
    return get_revenue_data(db, product_id, days)


@router.get("/shop/monitored")
def monitored_products(
    db: Session = Depends(get_db),
):
    """List all monitored products with latest deltas."""
    from backend.services.shop_intelligence import get_monitored_products
    products = get_monitored_products(db)
    return {"total": len(products), "products": products}


# /shop/snapshot-all e /shop/cross-platform removidos - usar EchoTik API


@router.get("/shop/velocity")
def product_velocity(
    limit: int = Query(default=20, le=50),
    db: Session = Depends(get_db),
):
    """Get products ranked by sales velocity (7-day delta)."""
    from backend.services.shop_intelligence import get_top_products_by_velocity
    products = get_top_products_by_velocity(db, limit)
    return {"total": len(products), "products": products}


# /shop/auto-detect removido - usar EchoTik API


@router.get("/shop/viral-videos")
def shop_viral_videos(
    min_views: int = 10000,
    min_viral_score: float = 0,
    min_duration: int = 0,
    max_duration: int = 0,
    description_contains: str = "",
    category: str = "",
    style: str = "",
    sort_by: str = "views",
    limit: int = 50,
    offset: int = 0,
    region_filter: str = "br",
    db: Session = Depends(get_db),
):
    """Get viral videos from DB that have shop products linked."""
    from backend.services.shop_intelligence import get_viral_videos_with_products
    videos, total = get_viral_videos_with_products(
        db, min_views=min_views, limit=limit, offset=offset,
        region_filter=region_filter, min_viral_score=min_viral_score,
        min_duration=min_duration, max_duration=max_duration,
        description_contains=description_contains,
        category=category, style=style, sort_by=sort_by,
    )
    return {"videos": videos, "total": total, "limit": limit, "offset": offset}


# /shop/auto-link removido - usar EchoTik API


@router.get("/shop/reports")
def shop_reports(
    days: int = Query(default=30, ge=7, le=90),
    db: Session = Depends(get_db),
):
    """Relatorios cruzados do TikTok Shop BR - KPIs, nicho, creators x produto."""
    from backend.services.shop_intelligence import get_shop_reports
    return get_shop_reports(db, days)


# ─── Popular / Trending Content (ScrapeCreators) ─────────────────

@router.get("/popular/videos")
def popular_videos(
    platform: str = "tiktok",
    country: str = "BR",
    period: str = "7",
    count: int = Query(default=30, le=50),
    db: Session = Depends(get_db),
):
    """Get popular videos from ScrapeCreators API."""
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    try:
        if platform == "tiktok":
            videos = sc.tiktok_search_top("viral trending", count)
        elif platform == "youtube":
            result = sc.youtube_search("viral trending", count)
            videos = result.get("videos", []) + result.get("shorts", [])
        elif platform == "instagram":
            videos = sc.instagram_reels_search("viral trending", count)
        else:
            raise HTTPException(status_code=400, detail="Plataforma invalida")
        if videos:
            saved = video_service.save_videos(db, videos)
            return {"found": len(videos), "saved": len(saved), "videos": videos[:20]}
        return {"found": 0, "saved": 0, "videos": []}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erro: {e}")


@router.get("/popular/creators")
def popular_creators(
    country: str = "BR",
    count: int = Query(default=30, le=50),
    db: Session = Depends(get_db),
):
    """Get popular creators from local database (by total views)."""
    from backend.models.creator import Creator
    creators = (
        db.query(Creator)
        .filter(Creator.followers > 0)
        .order_by(Creator.followers.desc())
        .limit(count)
        .all()
    )
    return {
        "total": len(creators),
        "creators": [
            {
                "id": c.id,
                "username": c.username,
                "platform": c.platform,
                "followers": c.followers or 0,
                "avg_views": c.avg_views or 0,
                "size_tier": c.size_tier or "",
                "avatar_url": c.avatar_url or "",
            }
            for c in creators
        ],
    }


@router.get("/popular/hashtags")
def popular_hashtags(
    country: str = "BR",
    period: str = "7",
    count: int = Query(default=30, le=50),
    db: Session = Depends(get_db),
):
    """Get popular hashtags from local database."""
    from collections import Counter
    days = int(period) if period.isdigit() else 7
    since = datetime.utcnow() - timedelta(days=days)
    videos = db.query(Video.hashtags).filter(Video.collected_at >= since).limit(2000).all()

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

    hashtags = [{"name": tag, "count": cnt} for tag, cnt in tag_counter.most_common(count)]
    return {"total": len(hashtags), "hashtags": hashtags}


@router.get("/popular/songs")
def popular_songs(
    country: str = "BR",
    count: int = Query(default=30, le=50),
    db: Session = Depends(get_db),
):
    """Get popular songs/sounds from local database."""
    from collections import Counter
    since = datetime.utcnow() - timedelta(days=7)
    videos = db.query(Video.title, Video.hashtags, Video.views).filter(
        Video.collected_at >= since,
        Video.views >= 10000,
    ).limit(1000).all()

    # Extract music-related hashtags as proxy for songs
    song_counter = Counter()
    music_tags = ["song", "music", "sound", "audio", "musica", "som", "funk", "remix"]
    for title, tags, views in videos:
        if tags:
            for t in (tags if isinstance(tags, list) else []):
                t_lower = str(t).strip().strip("#").lower()
                if any(m in t_lower for m in music_tags) and len(t_lower) > 3:
                    song_counter[t_lower] += 1

    songs = [{"name": name, "video_count": cnt} for name, cnt in song_counter.most_common(count)]
    return {"total": len(songs), "songs": songs}


@router.get("/song/details")
def song_details(url: str):
    """Get details for a specific TikTok song."""
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    try:
        return sc.tiktok_song_details(url)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erro: {e}")


@router.get("/song/videos")
def song_videos(
    url: str,
    count: int = Query(default=30, le=50),
    db: Session = Depends(get_db),
):
    """Get TikTok videos using a specific song."""
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    try:
        videos = sc.tiktok_song_videos(url, count)
        if videos:
            saved = video_service.save_videos(db, videos)
            return {"found": len(videos), "saved": len(saved), "videos": videos}
        return {"found": 0, "saved": 0, "videos": []}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erro: {e}")


# ─── Transcripts ──────────────────────────────────────────────────

@router.get("/transcript")
def get_transcript(url: str, platform: str = ""):
    """Get video transcript (TikTok, Instagram, or YouTube)."""
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    try:
        if not platform:
            if "tiktok.com" in url:
                platform = "tiktok"
            elif "instagram.com" in url:
                platform = "instagram"
            elif "youtube.com" in url or "youtu.be" in url:
                platform = "youtube"
            else:
                raise HTTPException(status_code=400, detail="Plataforma nao detectada. Informe o parametro platform.")

        if platform == "tiktok":
            return sc.tiktok_video_transcript(url)
        elif platform == "instagram":
            return sc.instagram_transcript(url)
        elif platform == "youtube":
            return sc.youtube_video_transcript(url)
        else:
            raise HTTPException(status_code=400, detail="Plataforma invalida")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erro: {e}")


@router.get("/transcript/whisper")
def transcribe_url_whisper(url: str, language: str = ""):
    """Download audio from URL and transcribe with local Whisper (free)."""
    from backend.services.whisper_transcriber import transcribe_url
    result = transcribe_url(url, language=language or None)
    if not result.get("success"):
        raise HTTPException(status_code=500, detail=result.get("error", "Erro na transcricao"))
    return result


@router.post("/transcript/upload")
async def transcribe_uploaded_file(
    file: UploadFile = File(...),
    language: str = "",
):
    """Transcribe an uploaded audio/video file using Whisper (100% free, local)."""
    import tempfile, os
    from backend.services.whisper_transcriber import transcribe_file

    allowed = {".mp4", ".mp3", ".wav", ".webm", ".m4a", ".ogg", ".aac", ".flac", ".mkv", ".mov"}
    ext = os.path.splitext(file.filename or "")[1].lower()
    if ext not in allowed:
        raise HTTPException(status_code=400, detail=f"Formato nao suportado: {ext}. Use: {', '.join(sorted(allowed))}")

    # Save to temp file
    tmp = tempfile.NamedTemporaryFile(delete=False, suffix=ext)
    try:
        content = await file.read()
        if len(content) > 100 * 1024 * 1024:  # 100MB limit
            raise HTTPException(status_code=400, detail="Arquivo muito grande. Maximo: 100MB")
        tmp.write(content)
        tmp.close()

        result = transcribe_file(tmp.name, language=language or None)
        if not result.get("success"):
            raise HTTPException(status_code=500, detail=result.get("error", "Erro na transcricao"))
        return result
    finally:
        os.unlink(tmp.name)


# ─── Comments (multi-platform) ───────────────────────────────────

@router.get("/social/comments")
def get_comments(
    url: str,
    count: int = Query(default=30, le=100),
    cursor: str = "",
):
    """Get comments from a video (TikTok, Instagram, or YouTube)."""
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    try:
        if "tiktok.com" in url:
            return sc.tiktok_comments(url, count, cursor)
        elif "instagram.com" in url:
            return sc.instagram_comments(url, count, cursor)
        elif "youtube.com" in url or "youtu.be" in url:
            return sc.youtube_comments(url, count, cursor)
        else:
            raise HTTPException(status_code=400, detail="URL nao reconhecida")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erro: {e}")


# ─── Instagram Reels Search ──────────────────────────────────────

@router.get("/instagram/reels/search")
def search_instagram_reels(
    query: str,
    count: int = Query(default=30, le=60),
    db: Session = Depends(get_db),
):
    """Search Instagram reels via ScrapeCreators."""
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    try:
        videos = sc.instagram_reels_search(query, count)
        if videos:
            saved = video_service.save_videos(db, videos)
            return {"found": len(videos), "saved": len(saved), "videos": videos[:20]}
        return {"found": 0, "saved": 0, "videos": []}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erro: {e}")


# ─── Instagram Highlights ────────────────────────────────────────

@router.get("/instagram/highlights")
def get_instagram_highlights(username: str):
    """Get Instagram story highlights."""
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    try:
        highlights = sc.instagram_highlights(username)
        return {"username": username, "total": len(highlights), "highlights": highlights}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erro: {e}")


# ─── YouTube Shorts & Channel Videos ─────────────────────────────

@router.get("/youtube/shorts/trending")
def youtube_shorts_trending(
    region: str = "BR",
    count: int = Query(default=30, le=50),
    db: Session = Depends(get_db),
):
    """Get trending YouTube Shorts."""
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    try:
        videos = sc.youtube_shorts_trending(region, count)
        if videos:
            saved = video_service.save_videos(db, videos)
            return {"found": len(videos), "saved": len(saved), "videos": videos[:20]}
        return {"found": 0, "saved": 0, "videos": []}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erro: {e}")


@router.get("/youtube/channel")
def youtube_channel_videos(
    url: str,
    count: int = Query(default=30, le=50),
    db: Session = Depends(get_db),
):
    """Get videos from a YouTube channel."""
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    try:
        result = sc.youtube_channel_videos(url, count)
        all_videos = result.get("videos", []) + result.get("shorts", [])
        if all_videos:
            saved = video_service.save_videos(db, all_videos)
            return {"found": len(all_videos), "saved": len(saved), "videos": all_videos[:20], "shorts": result.get("shorts", [])}
        return {"found": 0, "saved": 0, "videos": [], "shorts": []}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erro: {e}")


# ─── TikTok Search Top (carousels + videos) ──────────────────────

@router.get("/tiktok/search/top")
def tiktok_search_top(
    query: str,
    count: int = Query(default=30, le=50),
    db: Session = Depends(get_db),
):
    """Search TikTok with top results (videos + photo carousels)."""
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    try:
        videos = sc.tiktok_search_top(query, count)
        saved_count = 0
        if videos:
            saved = video_service.save_videos(db, videos)
            saved_count = len(saved)
        return {"found": len(videos), "saved": saved_count, "videos": videos[:20]}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erro: {e}")


# ─── TikTok Followers/Following ──────────────────────────────────

@router.get("/tiktok/followers")
def tiktok_followers(username: str, count: int = Query(default=30, le=50)):
    """Get followers of a TikTok user."""
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    try:
        return sc.tiktok_followers(username, count)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erro: {e}")


@router.get("/tiktok/following")
def tiktok_following(username: str, count: int = Query(default=30, le=50)):
    """Get accounts a TikTok user follows."""
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    try:
        return sc.tiktok_following(username, count)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erro: {e}")


# ─── Helper functions ─────────────────────────────────────────────

def _get_sc():
    """Get ScrapeCreators API instance."""
    if settings.SCRAPECREATORS_API_KEY:
        from backend.scrapers.scrapecreators import ScrapeCreatorsAPI
        return ScrapeCreatorsAPI(settings.SCRAPECREATORS_API_KEY)
    return None


def _save_product(db: Session, data: dict, url: str = ""):
    """Save a product to the database."""
    from backend.models.product import Product
    pid = str(data.get("product_id", ""))
    if not pid:
        return
    existing = db.query(Product).filter(Product.product_id == pid).first()
    if existing:
        existing.title = data.get("title", existing.title)
        existing.sold_count = data.get("sold_count", existing.sold_count)
        existing.rating = data.get("rating", existing.rating)
        existing.review_count = data.get("review_count", existing.review_count)
        existing.stock = data.get("stock", existing.stock)
        existing.related_videos = data.get("related_videos", existing.related_videos)
        existing.related_video_count = data.get("related_video_count", existing.related_video_count)
        db.commit()
        return
    product = Product(
        product_id=pid,
        title=data.get("title", ""),
        description=data.get("description", ""),
        image=data.get("image", ""),
        url=data.get("url", url),
        price=str(data.get("price", "")),
        original_price=str(data.get("original_price", "")),
        discount=str(data.get("discount", "")),
        sold_count=data.get("sold_count", 0),
        rating=data.get("rating", 0),
        review_count=data.get("review_count", 0),
        stock=data.get("stock", 0),
        seller_name=data.get("seller_name", ""),
        shop_name=data.get("shop", {}).get("name", "") if isinstance(data.get("shop"), dict) else "",
        related_video_count=data.get("related_video_count", 0),
        related_videos=data.get("related_videos", []),
    )
    db.add(product)
    db.commit()


# ─── Competitor Spy ─────────────────────────────────────────────


@router.get("/competitors")
def list_all_competitors(platform: str = "", db: Session = Depends(get_db)):
    from backend.services.competitor_spy import list_competitors
    return {"competitors": list_competitors(db, platform)}


@router.post("/competitors")
def add_new_competitor(platform: str, username: str, category: str = "", notes: str = "", db: Session = Depends(get_db)):
    from backend.services.competitor_spy import add_competitor
    return add_competitor(db, platform, username, category, notes)


@router.post("/competitors/add")
def add_competitor_json(body: dict, db: Session = Depends(get_db)):
    from backend.services.competitor_spy import add_competitor
    result = add_competitor(
        db,
        body.get("platform", "tiktok"),
        body.get("username", ""),
        body.get("category", ""),
        body.get("notes", ""),
    )
    return result.get("competitor", result)


@router.delete("/competitors/{competitor_id}")
def delete_competitor(competitor_id: int, db: Session = Depends(get_db)):
    from backend.services.competitor_spy import remove_competitor
    if remove_competitor(db, competitor_id):
        return {"status": "deleted"}
    raise HTTPException(status_code=404, detail="Competidor nao encontrado")


@router.post("/competitors/{competitor_id}/refresh")
def refresh_competitor_data(competitor_id: int, db: Session = Depends(get_db)):
    from backend.services.competitor_spy import refresh_competitor
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    return refresh_competitor(db, sc, competitor_id)


@router.get("/competitors/{competitor_id}/videos")
def competitor_videos(competitor_id: int, count: int = 20, db: Session = Depends(get_db)):
    from backend.services.competitor_spy import get_competitor_videos
    from backend.models.competitor import CompetitorProfile
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    comp = db.query(CompetitorProfile).filter(CompetitorProfile.id == competitor_id).first()
    if not comp:
        raise HTTPException(status_code=404, detail="Competidor nao encontrado")
    videos = get_competitor_videos(sc, comp.platform, comp.username, count)
    return {"competitor": comp.to_dict(), "videos": videos}


@router.get("/competitors/{competitor_id}/growth")
def competitor_growth(competitor_id: int, days: int = 30, db: Session = Depends(get_db)):
    from backend.services.competitor_spy import get_competitor_growth
    return get_competitor_growth(db, competitor_id, days)


@router.get("/competitors/{competitor_id}/analysis")
def competitor_content_analysis(competitor_id: int, count: int = 30, db: Session = Depends(get_db)):
    """Full content analysis: cadence, hashtags, formats, top content."""
    from backend.services.competitor_spy import (
        analyze_post_cadence, analyze_hashtags, analyze_content_formats, get_top_content, get_competitor_videos
    )
    from backend.models.competitor import CompetitorProfile
    comp = db.query(CompetitorProfile).filter(CompetitorProfile.id == competitor_id).first()
    if not comp:
        raise HTTPException(status_code=404, detail="Competidor nao encontrado")
    sc = _get_sc()
    videos = get_competitor_videos(sc, comp.platform, comp.username, count) if sc else []
    return {
        "competitor": comp.to_dict(),
        "cadence": analyze_post_cadence(videos),
        "hashtags": analyze_hashtags(videos),
        "formats": analyze_content_formats(videos),
        "top_content": get_top_content(videos),
        "videos_analyzed": len(videos),
    }


@router.get("/competitors/{competitor_id}/ai-report")
async def competitor_ai_report(competitor_id: int, db: Session = Depends(get_db)):
    """Generate AI report for competitor (async)."""
    from backend.services.competitor_spy import generate_ai_report, get_competitor_videos
    from backend.models.competitor import CompetitorProfile
    comp = db.query(CompetitorProfile).filter(CompetitorProfile.id == competitor_id).first()
    if not comp:
        raise HTTPException(status_code=404, detail="Competidor nao encontrado")
    sc = _get_sc()
    videos = get_competitor_videos(sc, comp.platform, comp.username, 30) if sc else []
    return await generate_ai_report(comp.to_dict(), videos)


@router.get("/competitors/{competitor_id}/gap-analysis")
async def competitor_gap_analysis(competitor_id: int, my_username: str = "", my_platform: str = "tiktok", db: Session = Depends(get_db)):
    """Gap analysis between you and a competitor (async)."""
    from backend.services.competitor_spy import gap_analysis, get_competitor_videos
    from backend.models.competitor import CompetitorProfile
    comp = db.query(CompetitorProfile).filter(CompetitorProfile.id == competitor_id).first()
    if not comp:
        raise HTTPException(status_code=404, detail="Competidor nao encontrado")
    sc = _get_sc()
    comp_videos = get_competitor_videos(sc, comp.platform, comp.username, 30) if sc else []
    my_videos = get_competitor_videos(sc, my_platform, my_username, 30) if sc and my_username else []
    my_data = {"username": my_username, "platform": my_platform, "followers": 0, "video_count": 0}
    return await gap_analysis(my_data, comp.to_dict(), my_videos, comp_videos)


@router.get("/competitors/{competitor_id}/viral-reverse")
async def competitor_viral_reverse(competitor_id: int, db: Session = Depends(get_db)):
    """Reverse-engineer viral patterns (async)."""
    from backend.services.competitor_spy import reverse_engineer_viral, get_competitor_videos
    from backend.models.competitor import CompetitorProfile
    comp = db.query(CompetitorProfile).filter(CompetitorProfile.id == competitor_id).first()
    if not comp:
        raise HTTPException(status_code=404, detail="Competidor nao encontrado")
    sc = _get_sc()
    videos = get_competitor_videos(sc, comp.platform, comp.username, 30) if sc else []
    return await reverse_engineer_viral(videos, comp.display_name or comp.username)


@router.get("/competitors/{competitor_id}/revenue")
def competitor_revenue(competitor_id: int, db: Session = Depends(get_db)):
    """Estimate competitor revenue."""
    from backend.services.competitor_spy import estimate_revenue, get_competitor_videos
    from backend.models.competitor import CompetitorProfile
    comp = db.query(CompetitorProfile).filter(CompetitorProfile.id == competitor_id).first()
    if not comp:
        raise HTTPException(status_code=404, detail="Competidor nao encontrado")
    sc = _get_sc()
    videos = get_competitor_videos(sc, comp.platform, comp.username, 20) if sc else []
    return estimate_revenue(comp.to_dict(), videos)


@router.post("/competitors/compare")
def compare_competitors_api(body: dict, db: Session = Depends(get_db)):
    """Compare multiple competitors side by side."""
    from backend.services.competitor_spy import compare_competitors
    ids = body.get("competitor_ids", [])
    if not ids:
        raise HTTPException(status_code=400, detail="competitor_ids obrigatorio")
    return compare_competitors(db, ids)


@router.post("/competitors/benchmark")
def benchmark_competitors_api(body: dict, db: Session = Depends(get_db)):
    """Benchmark metrics across competitors."""
    from backend.services.competitor_spy import benchmark_competitors
    ids = body.get("competitor_ids", [])
    if not ids:
        raise HTTPException(status_code=400, detail="competitor_ids obrigatorio")
    return benchmark_competitors(db, ids)


@router.get("/competitors/{competitor_id}/engagement")
def competitor_engagement(competitor_id: int, db: Session = Depends(get_db)):
    """Detailed engagement metrics."""
    from backend.services.competitor_spy import compare_engagement
    sc = _get_sc()
    results = compare_engagement(db, [competitor_id], sc)
    if not results:
        raise HTTPException(status_code=404, detail="Competidor nao encontrado")
    return results[0]


@router.post("/competitors/check-viral-alerts")
def check_viral_alerts_api(db: Session = Depends(get_db)):
    """Check for new viral videos from tracked competitors."""
    from backend.services.competitor_spy import check_viral_alerts
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    return {"alerts": check_viral_alerts(db, sc)}


@router.post("/competitors/refresh-all")
def refresh_all_competitors_api(db: Session = Depends(get_db)):
    """Refresh all tracked competitors."""
    from backend.services.competitor_spy import refresh_all_competitors
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    return refresh_all_competitors(db, sc)


# ─── ScriptGenius ──────────────────────────────────────────────


@router.post("/scripts/generate")
async def generate_script_api(body: dict):
    """Generate a video script using AI."""
    from backend.services.script_genius import generate_script
    topic = body.get("topic", "")
    if not topic:
        raise HTTPException(status_code=400, detail="topic obrigatorio")
    return await generate_script(
        topic, body.get("platform", "tiktok"), body.get("style", "tutorial"),
        body.get("duration", 30), body.get("language", "pt-BR"),
    )


@router.get("/scripts/templates")
def get_script_templates_api():
    """Get built-in script templates."""
    from backend.services.script_genius import get_script_templates
    return {"templates": get_script_templates()}


@router.post("/scripts/rewrite-viral")
async def rewrite_viral_api(body: dict):
    """Rewrite script for maximum virality."""
    from backend.services.script_genius import rewrite_for_viral
    text = body.get("text", "")
    if not text:
        raise HTTPException(status_code=400, detail="text obrigatorio")
    return await rewrite_for_viral(text)


@router.post("/scripts/adapt-platform")
def adapt_platform_api(body: dict):
    """Adapt script for target platform."""
    from backend.services.script_genius import adapt_for_platform
    return adapt_for_platform(body.get("text", ""), body.get("platform", "tiktok"))


@router.post("/scripts/improve")
async def improve_script_api(body: dict):
    """Improve script with AI focus."""
    from backend.services.script_genius import improve_script
    text = body.get("text", "")
    if not text:
        raise HTTPException(status_code=400, detail="text obrigatorio")
    return await improve_script(text, body.get("focus", "engagement"))


@router.get("/scripts")
def list_scripts_api(status: str = "", platform: str = "", limit: int = 50, db: Session = Depends(get_db)):
    """List saved scripts."""
    from backend.services.script_genius import list_scripts
    return {"scripts": list_scripts(db, status, platform, limit)}


@router.get("/scripts/{script_id}")
def get_script_api(script_id: int, db: Session = Depends(get_db)):
    """Get script by ID."""
    from backend.services.script_genius import get_script
    s = get_script(db, script_id)
    if not s:
        raise HTTPException(status_code=404, detail="Script nao encontrado")
    return s


@router.post("/scripts")
def save_script_api(body: dict, db: Session = Depends(get_db)):
    """Save a script."""
    from backend.services.script_genius import save_script
    return save_script(db, body)


@router.put("/scripts/{script_id}")
def update_script_api(script_id: int, body: dict, db: Session = Depends(get_db)):
    """Update a script."""
    from backend.services.script_genius import update_script
    s = update_script(db, script_id, body)
    if not s:
        raise HTTPException(status_code=404, detail="Script nao encontrado")
    return s


@router.delete("/scripts/{script_id}")
def delete_script_api(script_id: int, db: Session = Depends(get_db)):
    """Delete a script."""
    from backend.services.script_genius import delete_script
    if delete_script(db, script_id):
        return {"status": "deleted"}
    raise HTTPException(status_code=404, detail="Script nao encontrado")


@router.post("/hooks/seed")
def seed_hooks_api(db: Session = Depends(get_db)):
    """Seed hook bank with 500+ hooks."""
    from backend.services.script_genius import seed_hook_bank
    return seed_hook_bank(db)


@router.post("/hooks/generate")
async def generate_hooks_api(body: dict):
    """Generate hooks with AI."""
    from backend.services.script_genius import generate_hooks
    topic = body.get("topic", "")
    if not topic:
        raise HTTPException(status_code=400, detail="topic obrigatorio")
    return {"hooks": await generate_hooks(topic, body.get("category", "curiosidade"), body.get("count", 5))}


@router.get("/hooks")
def search_hooks_api(query: str = "", category: str = "", limit: int = 20, db: Session = Depends(get_db)):
    """Search hooks."""
    from backend.services.script_genius import search_hooks
    return {"hooks": search_hooks(db, query, category, limit)}


@router.get("/hooks/categories")
def hooks_by_category_api(db: Session = Depends(get_db)):
    """Get hooks grouped by category."""
    from backend.services.script_genius import get_hooks_by_category
    return get_hooks_by_category(db)


@router.post("/hooks/{hook_id}/rate")
def rate_hook_api(hook_id: int, rating: float = 5.0, db: Session = Depends(get_db)):
    """Rate a hook."""
    from backend.services.script_genius import rate_hook
    return rate_hook(db, hook_id, rating)


@router.post("/scripts/cta")
async def generate_cta_api(body: dict):
    """Generate CTAs."""
    from backend.services.script_genius import generate_cta
    return await generate_cta(body.get("topic", ""), body.get("goal", "seguir"), body.get("platform", "tiktok"))


@router.post("/scripts/readability")
def readability_api(body: dict):
    """Analyze script readability."""
    from backend.services.script_genius import analyze_readability
    return analyze_readability(body.get("text", ""))


@router.post("/scripts/retention-risks")
def retention_risks_api(body: dict):
    """Flag retention risks."""
    from backend.services.script_genius import flag_retention_risks
    return flag_retention_risks(body.get("text", ""))


@router.post("/scripts/seo")
def seo_api(body: dict):
    """Optimize for SEO."""
    from backend.services.script_genius import optimize_for_seo
    return optimize_for_seo(body.get("title", ""), body.get("description", ""), body.get("platform", "tiktok"))


@router.post("/tts/generate")
async def tts_generate_api(body: dict):
    """Generate TTS audio."""
    from backend.services.script_genius import text_to_speech
    text = body.get("text", "")
    if not text:
        raise HTTPException(status_code=400, detail="text obrigatorio")
    return await text_to_speech(text, body.get("voice", "pt-BR-AntonioNeural"))


@router.get("/tts/voices")
async def tts_voices_api(language: str = "pt"):
    """List TTS voices."""
    from backend.services.script_genius import list_tts_voices
    return {"voices": await list_tts_voices(language)}


@router.get("/tts/download/{filename}")
def tts_download_api(filename: str):
    """Download TTS audio file."""
    from backend.core.config import settings
    path = settings.data_path / filename
    if not path.exists():
        raise HTTPException(status_code=404, detail="Arquivo nao encontrado")
    return FileResponse(str(path), media_type="audio/mpeg", filename=filename)


# ─── ViralAcademy ──────────────────────────────────────────────


@router.get("/academy/stats")
def academy_stats_api(user_id: str = "default", db: Session = Depends(get_db)):
    """Get user academy stats."""
    from backend.services.viral_academy import get_user_stats
    return get_user_stats(db, user_id)


@router.post("/academy/xp")
def add_xp_api(body: dict, db: Session = Depends(get_db)):
    """Add XP to user."""
    from backend.services.viral_academy import add_xp
    return add_xp(db, body.get("amount", 10), body.get("user_id", "default"))


@router.post("/academy/audit")
async def channel_audit_api(body: dict, db: Session = Depends(get_db)):
    """AI channel audit."""
    from backend.services.viral_academy import channel_audit
    return await channel_audit(db, body.get("platform", "tiktok"), body.get("username", ""))


@router.get("/academy/recommendations")
async def recommendations_api(user_id: str = "default", db: Session = Depends(get_db)):
    """Personalized recommendations."""
    from backend.services.viral_academy import personalized_recommendations
    return await personalized_recommendations(db, user_id)


@router.post("/academy/growth-plan")
async def growth_plan_api(body: dict, db: Session = Depends(get_db)):
    """Generate growth plan."""
    from backend.services.viral_academy import generate_growth_plan
    return await generate_growth_plan(
        db, body.get("goal", "10k seguidores"), body.get("platform", "tiktok"),
        body.get("days", 90), body.get("user_id", "default"),
    )


@router.get("/academy/growth-plans")
def list_growth_plans_api(user_id: str = "default", db: Session = Depends(get_db)):
    """List growth plans."""
    from backend.services.viral_academy import get_growth_plans
    return {"plans": get_growth_plans(db, user_id)}


@router.put("/academy/growth-plan/{plan_id}/progress")
def update_plan_progress_api(plan_id: int, body: dict, db: Session = Depends(get_db)):
    """Update growth plan progress."""
    from backend.services.viral_academy import update_growth_plan_progress
    return update_growth_plan_progress(db, plan_id, body.get("progress", 0), body.get("user_id", "default"))


@router.get("/academy/weekly-report")
async def weekly_report_api(user_id: str = "default", db: Session = Depends(get_db)):
    """Weekly performance report."""
    from backend.services.viral_academy import weekly_performance_report
    return await weekly_performance_report(db, user_id)


@router.post("/academy/seed-achievements")
def seed_achievements_api(db: Session = Depends(get_db)):
    """Seed achievements."""
    from backend.services.viral_academy import seed_achievements
    return seed_achievements(db)


@router.get("/academy/achievements")
def achievements_api(user_id: str = "default", db: Session = Depends(get_db)):
    """Get all achievements with earned status."""
    from backend.services.viral_academy import get_user_achievements
    return get_user_achievements(db, user_id)


@router.post("/academy/check-achievements")
def check_achievements_api(body: dict = {}, db: Session = Depends(get_db)):
    """Check and award achievements."""
    from backend.services.viral_academy import check_and_award_achievements
    return {"new_achievements": check_and_award_achievements(db, body.get("user_id", "default"))}


@router.get("/academy/challenges")
def active_challenges_api(user_id: str = "default", db: Session = Depends(get_db)):
    """Get active challenges."""
    from backend.services.viral_academy import get_active_challenges
    return get_active_challenges(db, user_id)


@router.post("/academy/challenges/daily")
def daily_challenges_api(body: dict = {}, db: Session = Depends(get_db)):
    """Generate daily challenges."""
    from backend.services.viral_academy import generate_daily_challenges
    return {"challenges": generate_daily_challenges(db, body.get("user_id", "default"))}


@router.post("/academy/challenges/weekly")
def weekly_challenge_api(body: dict = {}, db: Session = Depends(get_db)):
    """Generate weekly challenge."""
    from backend.services.viral_academy import generate_weekly_challenge
    return generate_weekly_challenge(db, body.get("user_id", "default"))


@router.post("/academy/challenges/{challenge_id}/complete")
def complete_challenge_api(challenge_id: int, body: dict = {}, db: Session = Depends(get_db)):
    """Complete a challenge."""
    from backend.services.viral_academy import complete_challenge
    return complete_challenge(db, challenge_id, body.get("user_id", "default"))


@router.get("/academy/course")
def course_progress_api(user_id: str = "default", db: Session = Depends(get_db)):
    """Get course progress."""
    from backend.services.viral_academy import get_course_progress
    return get_course_progress(db, user_id)


@router.post("/academy/course/{module_id}/complete")
def complete_module_api(module_id: int, body: dict = {}, db: Session = Depends(get_db)):
    """Mark module as complete."""
    from backend.services.viral_academy import mark_module_complete
    return mark_module_complete(db, module_id, body.get("user_id", "default"))


@router.post("/academy/skill-assessment")
async def skill_assessment_api(body: dict):
    """AI skill assessment."""
    from backend.services.viral_academy import skill_assessment
    from backend.database.connection import SessionLocal
    db = SessionLocal()
    try:
        return await skill_assessment(db, body.get("skill", "hooks"), body.get("user_id", "default"))
    finally:
        db.close()


@router.get("/academy/learning-paths")
def learning_paths_api():
    """Get learning paths."""
    from backend.services.viral_academy import get_learning_paths
    return {"paths": get_learning_paths()}


# ─── Viral Patterns & Script Generator ─────────────────────────


@router.get("/patterns/analyze")
def analyze_patterns(platform: str = "", days: int = 7, min_score: int = 70, db: Session = Depends(get_db)):
    from backend.services.viral_patterns import analyze_viral_patterns
    return analyze_viral_patterns(db, platform, days, min_score)


@router.get("/patterns/script")
def generate_video_script(topic: str, platform: str = "tiktok", style: str = "tutorial", db: Session = Depends(get_db)):
    from backend.services.viral_patterns import generate_script
    return generate_script(db, topic, platform, style)


@router.get("/patterns/viral-probability")
def viral_probability(
    title: str,
    hashtags: str = "",
    platform: str = "tiktok",
    duration: int = 0,
    hour: int = -1,
    db: Session = Depends(get_db),
):
    from backend.services.viral_patterns import calculate_viral_probability
    tags = [t.strip() for t in hashtags.split(",") if t.strip()] if hashtags else []
    return calculate_viral_probability(db, title, tags, platform, duration, hour)


# ─── Trend Lifecycle ───────────────────────────────────────────


@router.get("/trends/lifecycle")
def get_trend_lifecycle(keyword: str, platform: str = "tiktok", db: Session = Depends(get_db)):
    from backend.services.trend_lifecycle import analyze_trend
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    return analyze_trend(db, sc, keyword, platform)


@router.get("/trends/tracked")
def tracked_trends(db: Session = Depends(get_db)):
    from backend.services.trend_lifecycle import get_all_tracked_trends
    return {"trends": get_all_tracked_trends(db)}


@router.get("/trends/emerging")
def emerging_trends(db: Session = Depends(get_db)):
    from backend.services.trend_lifecycle import get_emerging_trends
    return {"trends": get_emerging_trends(db)}


# ─── Sound Predictor ───────────────────────────────────────────


@router.get("/sounds/trending")
def trending_sounds(db: Session = Depends(get_db)):
    from backend.services.sound_predictor import get_trending_sounds
    return {"sounds": get_trending_sounds(db)}


@router.get("/sounds/emerging")
def emerging_sounds(db: Session = Depends(get_db)):
    from backend.services.sound_predictor import get_emerging_sounds
    return {"sounds": get_emerging_sounds(db)}


@router.get("/sounds/search")
def search_sounds(keyword: str = "viral sound", platform: str = "tiktok", db: Session = Depends(get_db)):
    from backend.services.sound_predictor import search_emerging_sounds
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    kw_list = [k.strip() for k in keyword.split(",") if k.strip()]
    return {"sounds": search_emerging_sounds(db, sc, kw_list)}


# ─── Cross-Platform Replicator ─────────────────────────────────


@router.get("/cross-platform/opportunities")
def cross_platform_opportunities(keyword: str, source: str = "tiktok", count: int = 15):
    from backend.services.cross_platform import find_replicable_content
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    return find_replicable_content(sc, keyword, source, count)


@router.get("/cross-platform/affiliate-match")
def affiliate_match(keywords: str = "skincare,gadgets,moda", db: Session = Depends(get_db)):
    from backend.services.cross_platform import match_affiliate_products
    sc = _get_sc()
    if not sc:
        raise HTTPException(status_code=400, detail="ScrapeCreators nao configurado")
    kw_list = [k.strip() for k in keywords.split(",") if k.strip()]
    return {"matches": match_affiliate_products(sc, db, kw_list)}


@router.get("/engagement/heatmap")
def get_engagement_heatmap(platform: str = "", niche: str = "", days: int = 30, db: Session = Depends(get_db)):
    from backend.services.cross_platform import engagement_heatmap
    return engagement_heatmap(db, platform, niche, days)


# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
#  Viral Scanner
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

@router.get("/scanner/videos")
def scanner_get_videos(
    min_views: int = 0, max_views: int = 0,
    min_likes: int = 0, min_comments: int = 0, min_shares: int = 0,
    min_engagement: float = 0, max_engagement: float = 0,
    min_viral_score: float = 0, max_viral_score: float = 0,
    viral_level: str = "",
    min_outlier: float = 0, min_replicability: float = 0,
    min_duration: int = 0, max_duration: int = 0,
    has_product: str = "",
    hashtag_contains: str = "", description_contains: str = "",
    creator_tier: str = "",
    min_views_per_follower: float = 0,
    small_creator_viral: bool = False,
    published_within_hours: int = 0,
    min_velocity: float = 0,
    sort_by: str = "viral_score",
    limit: int = 48, offset: int = 0,
    platform: str = "",
    language: str = "",
    category: str = "",
    style: str = "",
    db: Session = Depends(get_db),
):
    from backend.services.viral_scanner import get_scanner_videos
    videos, total = get_scanner_videos(
        db, min_views=min_views, max_views=max_views,
        min_likes=min_likes, min_comments=min_comments, min_shares=min_shares,
        min_engagement=min_engagement, max_engagement=max_engagement,
        min_viral_score=min_viral_score, max_viral_score=max_viral_score,
        viral_level=viral_level,
        min_outlier=min_outlier, min_replicability=min_replicability,
        min_duration=min_duration, max_duration=max_duration,
        has_product=has_product,
        hashtag_contains=hashtag_contains, description_contains=description_contains,
        creator_tier=creator_tier,
        min_views_per_follower=min_views_per_follower,
        small_creator_viral=small_creator_viral,
        published_within_hours=published_within_hours,
        min_velocity=min_velocity,
        sort_by=sort_by, limit=limit, offset=offset, platform=platform,
        language=language, category=category, style=style,
    )
    return {"videos": videos, "total": total, "limit": limit, "offset": offset}


@router.post("/scanner/scan")
def scanner_run_scan(
    keywords: str = "",
    platforms: str = "",
    max_results: int = 30,
    db: Session = Depends(get_db),
):
    """Run a manual scan with custom keywords or use configured ones."""
    from backend.services.viral_scanner import scan_keywords
    from backend.models.settings import AppSettings

    # Get scanner settings
    settings_rows = db.query(AppSettings).filter(AppSettings.category == "scanner").all()
    settings = {s.key: s.value for s in settings_rows}

    if keywords:
        kw_list = [k.strip() for k in keywords.split(",") if k.strip()]
    else:
        kw_str = settings.get("scanner_keywords", "")
        kw_list = [k.strip() for k in kw_str.split(",") if k.strip()]

    if not kw_list:
        return {"error": "Nenhuma keyword configurada. Digite keywords no campo acima ou configure em Configuracoes > Scanner."}

    # Override max results if provided
    if max_results:
        settings["scanner_max_results_per_keyword"] = str(max_results)

    # Pass platforms if specified
    if platforms:
        settings["scanner_platforms"] = platforms

    result = scan_keywords(kw_list, settings)
    return result


@router.post("/scanner/scan-creative-center")
def scanner_run_creative_center(db: Session = Depends(get_db)):
    """Run a scan using FREE Creative Center keywords."""
    from backend.services.viral_scanner import scan_with_creative_center
    from backend.models.settings import AppSettings

    settings_rows = db.query(AppSettings).filter(AppSettings.category == "scanner").all()
    settings = {s.key: s.value for s in settings_rows}

    return scan_with_creative_center(settings)


@router.get("/scanner/status")
def scanner_get_status(db: Session = Depends(get_db)):
    from backend.services.viral_scanner import get_scanner_status
    from backend.services.api_usage_tracker import get_usage_stats
    from datetime import timedelta

    status = get_scanner_status()
    usage = get_usage_stats(db)

    # Add real DB counts
    since_90d = datetime.utcnow() - timedelta(days=90)
    status["total_videos"] = db.query(Video).filter(Video.collected_at >= since_90d).count()
    status["total_all"] = db.query(Video).count()

    return {"scanner": status, "usage": usage}


@router.get("/scanner/usage")
def scanner_get_usage(days: int = 30, db: Session = Depends(get_db)):
    from backend.services.api_usage_tracker import get_usage_stats
    return get_usage_stats(db, days)


@router.get("/scanner/history")
def scanner_history(
    days: int = 30, page: int = 1, limit: int = 50,
    service: str = "", status: str = "",
    db: Session = Depends(get_db),
):
    """Full scanner history with per-service breakdown and charts."""
    from backend.services.api_usage_tracker import get_usage_history
    return get_usage_history(db, days=days, page=page, limit=limit, service=service, status=status)


@router.post("/scanner/pause")
def scanner_pause():
    """Emergency pause - stop scanner immediately."""
    from backend.services.scheduler import scheduler
    jobs = scheduler.get_jobs()
    paused = 0
    for job in jobs:
        if "scanner" in job.id:
            job.pause()
            paused += 1
    return {"paused": paused, "message": f"{paused} jobs pausados"}


@router.post("/scanner/resume")
def scanner_resume():
    """Resume paused scanner jobs."""
    from backend.services.scheduler import scheduler
    jobs = scheduler.get_jobs()
    resumed = 0
    for job in jobs:
        if "scanner" in job.id:
            job.resume()
            resumed += 1
    return {"resumed": resumed, "message": f"{resumed} jobs retomados"}


# ─── Data Population ──────────────────────────────────────────


@router.post("/scanner/scan-hashtag")
def scanner_scan_hashtag(hashtag: str = "", max_results: int = 30):
    """Scan videos by TikTok hashtag. Cost: 1 credit."""
    from backend.services.viral_scanner import scan_hashtag
    if not hashtag:
        raise HTTPException(status_code=400, detail="Hashtag e obrigatoria")
    return scan_hashtag(hashtag, max_results=max_results)


@router.post("/scanner/scan-sound")
def scanner_scan_sound(sound_url: str = "", max_results: int = 30):
    """Scan videos by TikTok sound URL. Cost: 1 credit."""
    from backend.services.viral_scanner import scan_sound
    if not sound_url:
        raise HTTPException(status_code=400, detail="URL do som e obrigatoria")
    return scan_sound(sound_url, max_results=max_results)


@router.post("/scanner/transcribe/{video_id}")
async def scanner_transcribe_video(video_id: int, db: Session = Depends(get_db)):
    """Transcribe video audio using local Whisper (FREE). Downloads audio, transcribes, returns text."""
    video = db.query(Video).filter(Video.id == video_id).first()
    if not video:
        raise HTTPException(status_code=404, detail="Video nao encontrado")
    if not video.url:
        raise HTTPException(status_code=400, detail="Video sem URL")
    from backend.services.whisper_transcriber import transcribe_url
    result = transcribe_url(video.url)
    return result


@router.post("/scanner/populate")
def scanner_populate_all(db: Session = Depends(get_db)):
    """Populate all sections (Trends, Creators, Sounds, Lifecycle) from collected videos. FREE."""
    from backend.services.data_populator import populate_all
    results = populate_all(db)
    return {"message": "Dados populados com sucesso", "results": results}


@router.post("/scanner/recalculate-scores")
def scanner_recalculate(db: Session = Depends(get_db)):
    """Recalculate viral scores for videos with updated creator data. FREE."""
    from backend.services.data_populator import recalculate_video_scores
    results = recalculate_video_scores(db)
    return {"message": "Scores recalculados", "results": results}


# ─── Trends Scanner ────────────────────────────────────────────


@router.get("/trends-scanner/videos")
def trends_scanner_get_videos(
    min_views: int = 0, max_views: int = 0,
    min_viral_score: float = 0, min_engagement: float = 0,
    min_duration: int = 0, max_duration: int = 0,
    has_product: str = "", description_contains: str = "",
    creator_tier: str = "", published_within_hours: int = 0,
    sort_by: str = "collected", limit: int = 48, offset: int = 0,
    platform: str = "", language: str = "",
    db: Session = Depends(get_db),
):
    """Get trending videos with filters."""
    from backend.services.trends_scanner import get_trends_videos
    videos, total = get_trends_videos(
        db, min_views=min_views, max_views=max_views,
        min_viral_score=min_viral_score, min_engagement=min_engagement,
        min_duration=min_duration, max_duration=max_duration,
        has_product=has_product, description_contains=description_contains,
        creator_tier=creator_tier, published_within_hours=published_within_hours,
        sort_by=sort_by, limit=limit, offset=offset,
        platform=platform, language=language,
    )
    return {"videos": videos, "total": total}


@router.post("/trends-scanner/scan")
def trends_scanner_run(db: Session = Depends(get_db)):
    """Run a manual trends scan (TikTok trending + YouTube Shorts)."""
    from backend.services.trends_scanner import scan_trends
    from backend.models.settings import AppSettings
    settings_rows = db.query(AppSettings).filter(
        AppSettings.category.in_(["scanner", "trends"])
    ).all()
    settings = {s.key: s.value for s in settings_rows}
    result = scan_trends(settings)
    return result


@router.get("/trends-scanner/status")
def trends_scanner_status(db: Session = Depends(get_db)):
    """Get trends scanner status + usage stats."""
    from backend.services.trends_scanner import get_trends_status
    from backend.services.api_usage_tracker import get_usage_today
    status = get_trends_status()
    status["credits_today"] = get_usage_today(db)
    return status


@router.post("/trends-scanner/toggle")
def trends_scanner_toggle(enabled: bool = True, interval_minutes: int = 15, db: Session = Depends(get_db)):
    """Enable/disable trends scanner automation."""
    from backend.models.settings import AppSettings
    from backend.services.scheduler import update_schedule, get_schedule_config

    # Save to DB
    for key, val in [
        ("trends_scanner_enabled", str(enabled).lower()),
        ("trends_scanner_interval_minutes", str(interval_minutes)),
    ]:
        row = db.query(AppSettings).filter_by(key=key).first()
        if row:
            row.value = val
        else:
            db.add(AppSettings(key=key, value=val, category="trends"))
    db.commit()

    # Update scheduler
    config = get_schedule_config()
    config["trends_scanner"] = {"enabled": enabled, "interval_minutes": interval_minutes}
    update_schedule(config)

    return {"enabled": enabled, "interval_minutes": interval_minutes}


# ─── Settings ──────────────────────────────────────────────────


@router.get("/settings/all")
def get_all_settings(db: Session = Depends(get_db)):
    """Get all platform settings grouped by category."""
    from backend.models.settings import AppSettings, DEFAULT_SETTINGS
    _ensure_defaults(db)
    rows = db.query(AppSettings).order_by(AppSettings.category, AppSettings.key).all()
    grouped = {}
    for r in rows:
        if r.category not in grouped:
            grouped[r.category] = {}
        grouped[r.category][r.key] = r.value
    return {"settings": grouped}


@router.get("/settings/{key}")
def get_setting(key: str, db: Session = Depends(get_db)):
    """Get a single setting value."""
    from backend.models.settings import AppSettings, DEFAULT_SETTINGS
    _ensure_defaults(db)
    row = db.query(AppSettings).filter(AppSettings.key == key).first()
    if not row:
        raise HTTPException(status_code=404, detail=f"Setting '{key}' not found")
    return {"key": row.key, "value": row.value, "category": row.category}


@router.put("/settings/{key}")
def update_setting(key: str, value: str = Query(...), db: Session = Depends(get_db)):
    """Update a single setting."""
    from backend.models.settings import AppSettings
    row = db.query(AppSettings).filter(AppSettings.key == key).first()
    if not row:
        raise HTTPException(status_code=404, detail=f"Setting '{key}' not found")
    row.value = value
    db.commit()
    # If it's an API key, update env at runtime
    if key == "scrapecreators_api_key" and value:
        settings.SCRAPECREATORS_API_KEY = value
    elif key == "youtube_api_key" and value:
        settings.YOUTUBE_API_KEY = value
    elif key == "apify_api_token" and value:
        settings.APIFY_API_TOKEN = value
    # Reload scheduler if scanner settings changed
    if key.startswith("scanner_"):
        from backend.services.scheduler import load_settings_from_db
        load_settings_from_db()
    return {"status": "ok", "key": key, "value": value}


@router.put("/settings/bulk/update")
def update_settings_bulk(updates: dict, db: Session = Depends(get_db)):
    """Update multiple settings at once. Body: {"key1": "value1", "key2": "value2"}"""
    from backend.models.settings import AppSettings
    updated = 0
    has_scanner_change = False
    for key, value in updates.items():
        row = db.query(AppSettings).filter(AppSettings.key == key).first()
        if row:
            row.value = str(value)
            updated += 1
            if key.startswith("scanner_"):
                has_scanner_change = True
    db.commit()
    # Reload scheduler if any scanner settings changed
    if has_scanner_change:
        from backend.services.scheduler import load_settings_from_db
        load_settings_from_db()
    return {"status": "ok", "updated": updated}


@router.post("/settings/reset")
def reset_settings(db: Session = Depends(get_db)):
    """Reset all settings to defaults."""
    from backend.models.settings import AppSettings, DEFAULT_SETTINGS
    for key, info in DEFAULT_SETTINGS.items():
        row = db.query(AppSettings).filter(AppSettings.key == key).first()
        if row:
            row.value = info["value"]
        else:
            db.add(AppSettings(key=key, value=info["value"], category=info["category"]))
    db.commit()
    return {"status": "ok", "message": "Configuracoes resetadas para o padrao"}


@router.post("/settings/export")
def export_settings(db: Session = Depends(get_db)):
    """Export all settings as JSON."""
    from backend.models.settings import AppSettings
    rows = db.query(AppSettings).all()
    return {"settings": {r.key: {"value": r.value, "category": r.category} for r in rows}}


@router.post("/settings/import")
def import_settings(data: dict, db: Session = Depends(get_db)):
    """Import settings from JSON. Body: {"settings": {"key": {"value": "...", "category": "..."}}}"""
    from backend.models.settings import AppSettings
    imported = 0
    for key, info in data.get("settings", {}).items():
        value = info if isinstance(info, str) else info.get("value", "")
        category = info.get("category", "general") if isinstance(info, dict) else "general"
        row = db.query(AppSettings).filter(AppSettings.key == key).first()
        if row:
            row.value = str(value)
        else:
            db.add(AppSettings(key=key, value=str(value), category=category))
        imported += 1
    db.commit()
    return {"status": "ok", "imported": imported}


def _ensure_defaults(db: Session):
    """Ensure all default settings exist in the database."""
    from backend.models.settings import AppSettings, DEFAULT_SETTINGS
    existing = {r.key for r in db.query(AppSettings.key).all()}
    for key, info in DEFAULT_SETTINGS.items():
        if key not in existing:
            # Populate API keys from env if available
            value = info["value"]
            if key == "scrapecreators_api_key" and settings.SCRAPECREATORS_API_KEY:
                value = settings.SCRAPECREATORS_API_KEY
            elif key == "youtube_api_key" and settings.YOUTUBE_API_KEY:
                value = settings.YOUTUBE_API_KEY
            elif key == "apify_api_token" and getattr(settings, "APIFY_API_TOKEN", ""):
                value = settings.APIFY_API_TOKEN
            db.add(AppSettings(key=key, value=value, category=info["category"]))
    db.commit()


# ─── YouTube OAuth ─────────────────────────────────────────────


@router.get("/youtube/auth/status")
def youtube_auth_status():
    """Get YouTube OAuth status."""
    from backend.services.youtube_auth import yt_auth_manager
    return yt_auth_manager.get_status()


@router.post("/youtube/auth/start")
def youtube_auth_start():
    """Start YouTube OAuth device code flow."""
    from backend.services.youtube_auth import yt_auth_manager
    return yt_auth_manager.start_auth()


@router.post("/youtube/auth/revoke")
def youtube_auth_revoke():
    """Revoke YouTube OAuth tokens."""
    from backend.services.youtube_auth import yt_auth_manager
    yt_auth_manager.revoke()
    return {"status": "ok", "message": "YouTube desconectado"}


# ─── Backup / Download ─────────────────────────────────────────


@router.get("/backup/download")
def download_backup():
    """Download the latest database backup."""
    import shutil
    import tempfile
    from datetime import datetime as dt

    db_path = Path("data/viral_social.db")
    if not db_path.exists():
        raise HTTPException(status_code=404, detail="Banco de dados nao encontrado")

    # Create a fresh compressed backup
    backup_dir = Path("backups")
    backup_dir.mkdir(exist_ok=True)
    date_str = dt.now().strftime("%Y-%m-%d_%H%M")
    backup_name = f"viral_social_{date_str}.db"
    backup_path = backup_dir / backup_name

    shutil.copy2(db_path, backup_path)

    return FileResponse(
        path=str(backup_path),
        filename=backup_name,
        media_type="application/octet-stream",
    )


@router.get("/backup/download-full")
def download_full_backup():
    """Download full project backup (code + database) as zip."""
    import zipfile
    import tempfile
    from datetime import datetime as dt

    project_dir = Path(".")
    date_str = dt.now().strftime("%Y-%m-%d_%H%M")
    zip_name = f"viral_social_full_{date_str}.zip"
    zip_path = Path("backups") / zip_name
    zip_path.parent.mkdir(exist_ok=True)

    exclude = {"venv", "__pycache__", ".git", "downloads", "backups", ".env"}

    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
        # Add source code
        for p in project_dir.rglob("*"):
            if p.is_file() and not any(ex in p.parts for ex in exclude):
                zf.write(p, p)
        # Add database
        db_path = Path("data/viral_social.db")
        if db_path.exists():
            zf.write(db_path, db_path)

    return FileResponse(
        path=str(zip_path),
        filename=zip_name,
        media_type="application/zip",
    )


@router.post("/backup/push-github")
def push_to_github():
    """Trigger a backup and push to GitHub."""
    import subprocess
    result = subprocess.run(
        ["/home/glauko/viral-social/backup_db.sh"],
        capture_output=True,
        text=True,
        timeout=120,
    )
    return {
        "status": "ok" if result.returncode == 0 else "error",
        "output": result.stdout,
        "error": result.stderr if result.returncode != 0 else "",
    }


@router.get("/calendar/best-times")
def get_best_posting_times(
    platform: str = "",
    days: int = Query(default=30, le=90),
    db: Session = Depends(get_db),
):
    return calendar_service.get_best_times(db, platform, days)


@router.get("/calendar/weekly-plan")
def get_weekly_plan(
    platform: str = "",
    posts_per_day: int = Query(default=1, le=5),
    db: Session = Depends(get_db),
):
    plan = calendar_service.generate_weekly_plan(db, platform, posts_per_day)
    return {"plan": plan}


# ─── PostPilot Smart Queue ─────────────────────────────────────

@router.post("/calendar/queue")
def add_to_queue_endpoint(data: dict):
    """Add item to smart publishing queue."""
    from backend.services.content_calendar import add_to_queue
    return add_to_queue(**data)


@router.get("/calendar/queue")
def list_queue_endpoint(status: str = "", platform: str = ""):
    """List queue items."""
    from backend.services.content_calendar import list_queue
    return {"items": list_queue(status, platform)}


@router.put("/calendar/queue/{item_id}")
def update_queue_endpoint(item_id: str, data: dict):
    """Update queue item."""
    from backend.services.content_calendar import update_queue_item
    return update_queue_item(item_id, **data)


@router.delete("/calendar/queue/{item_id}")
def remove_queue_endpoint(item_id: str):
    """Remove from queue."""
    from backend.services.content_calendar import remove_from_queue
    if not remove_from_queue(item_id):
        raise HTTPException(status_code=404, detail="Item nao encontrado")
    return {"success": True}


@router.post("/calendar/queue/reorder")
def reorder_queue_endpoint(data: dict):
    """Reorder queue by item IDs."""
    from backend.services.content_calendar import reorder_queue
    ids = data.get("item_ids", [])
    return {"items": reorder_queue(ids)}


@router.post("/calendar/queue/{item_id}/publish")
def publish_item_endpoint(item_id: str):
    """Mark item as published."""
    from backend.services.content_calendar import publish_item
    result = publish_item(item_id)
    if "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
    return result


@router.post("/calendar/auto-schedule")
async def auto_schedule_endpoint(
    platform: str = "",
    posts_per_day: int = Query(default=2, le=5),
    db: Session = Depends(get_db),
):
    """AI auto-schedule unscheduled queue items."""
    from backend.services.content_calendar import auto_schedule_queue
    return await auto_schedule_queue(db, platform, posts_per_day)


@router.get("/calendar/recycle")
async def content_recycling_endpoint(
    days: int = Query(default=90, le=180),
    limit: int = Query(default=10, le=30),
    db: Session = Depends(get_db),
):
    """Suggest content for recycling."""
    from backend.services.content_calendar import suggest_content_recycling
    return {"suggestions": await suggest_content_recycling(db, days, limit)}


@router.post("/calendar/smart-caption")
async def smart_caption_endpoint(data: dict):
    """Generate AI-powered caption."""
    from backend.services.content_calendar import generate_smart_caption
    title = data.get("title", "")
    if not title:
        raise HTTPException(status_code=400, detail="title obrigatorio")
    return await generate_smart_caption(
        title, data.get("platform", "tiktok"),
        data.get("tone", "engajante"), data.get("niche", ""),
    )


@router.post("/calendar/ab-test")
async def ab_test_endpoint(
    data: dict,
    db: Session = Depends(get_db),
):
    """Create A/B test schedule."""
    from backend.services.content_calendar import ab_test_schedule
    title = data.get("title", "")
    if not title:
        raise HTTPException(status_code=400, detail="title obrigatorio")
    return await ab_test_schedule(
        db, title, data.get("platform", "tiktok"),
        data.get("variations", 2),
    )


@router.get("/calendar/queue/stats")
def queue_stats_endpoint():
    """Get queue statistics."""
    from backend.services.content_calendar import get_queue_stats
    return get_queue_stats()


# ─── Champion Videos (Vyral-style) ─────────────────────────────

@router.get("/champion/videos")
def get_champion_videos_endpoint(
    limit: int = Query(default=50, le=200),
    offset: int = Query(default=0, ge=0),
    country: str = "all",
    niche: str = "",
    sort_by: str = "revenue",
    min_views: int = Query(default=10000, ge=0),
    min_revenue: float = Query(default=0, ge=0),
    search: str = "",
    days: int = Query(default=90, le=365),
    db: Session = Depends(get_db),
):
    from backend.services.champion_videos import get_champion_videos
    videos, total = get_champion_videos(
        db, limit=limit, offset=offset, country=country,
        niche=niche, sort_by=sort_by, min_views=min_views,
        min_revenue=min_revenue, search=search, days=days,
    )
    return {"videos": videos, "total": total, "limit": limit, "offset": offset}


@router.get("/champion/stats")
def get_champion_stats_endpoint(db: Session = Depends(get_db)):
    from backend.services.champion_videos import get_champion_stats
    return get_champion_stats(db)


@router.get("/champion/analyze/{video_id}")
def analyze_video_script(video_id: int, db: Session = Depends(get_db)):
    from backend.services.champion_videos import analyze_script, estimate_revenue, classify_niche
    video = db.query(Video).filter(Video.id == video_id).first()
    if not video:
        raise HTTPException(status_code=404, detail="Video nao encontrado")
    hashtags_list = video.hashtags if isinstance(video.hashtags, list) else []
    niche = classify_niche(video.title or "", video.description or "", hashtags_list)
    script = analyze_script(video.title or "", video.description or "")
    revenue = estimate_revenue(video.views, "", niche)
    return {
        "video_id": video.id,
        "title": video.title,
        "niche": niche,
        "script": script,
        "revenue": revenue,
    }


@router.post("/champion/save/{video_id}")
def save_champion_video(
    video_id: int,
    notes: str = "",
    tags: str = "",
    folder: str = "geral",
    db: Session = Depends(get_db),
):
    from backend.services.champion_videos import save_video
    return save_video(db, video_id, notes, tags, folder)


@router.delete("/champion/save/{video_id}")
def unsave_champion_video(video_id: int, db: Session = Depends(get_db)):
    from backend.services.champion_videos import unsave_video
    success = unsave_video(db, video_id)
    if not success:
        raise HTTPException(status_code=404, detail="Video nao esta salvo")
    return {"status": "removed"}


@router.get("/champion/saved")
def get_saved_champion_videos(
    folder: str = "",
    limit: int = Query(default=50, le=200),
    offset: int = Query(default=0, ge=0),
    db: Session = Depends(get_db),
):
    from backend.services.champion_videos import get_saved_videos
    videos, total = get_saved_videos(db, folder=folder, limit=limit, offset=offset)
    return {"videos": videos, "total": total}


@router.get("/champion/folders")
def get_saved_folders_endpoint(db: Session = Depends(get_db)):
    from backend.services.champion_videos import get_saved_folders
    return get_saved_folders(db)


# ─── SociaVault routes removidos - EchoTik e a fonte exclusiva de TikTok Shop ──


# ═══════════════════════════════════════════════════════════════
# EchoTik API Endpoints (TikTok Shop Analytics - Kalodata-style)
# ═══════════════════════════════════════════════════════════════

def _get_echotik():
    """Get TikTok Shop cache service (Apify-based, replaces EchoTik)."""
    from backend.services.tiktok_shop_cache import TikTokShopCacheService
    from backend.core.config import settings as app_settings
    token = app_settings.APIFY_API_TOKEN
    if not token:
        # Fallback: check DB settings
        from backend.models.settings import AppSettings
        from backend.database.connection import SessionLocal
        db = SessionLocal()
        try:
            row = db.query(AppSettings).filter(AppSettings.key == "apify_api_token").first()
            token = row.value if row else ""
        finally:
            db.close()
    if not token:
        raise HTTPException(status_code=400, detail="APIFY_API_TOKEN nao configurado. Va em Configuracoes > API Keys.")
    return TikTokShopCacheService(token)


@router.get("/echotik/product/ranking")
def echotik_product_ranking(
    date: str = "",
    rank_field: int = Query(default=1, ge=1, le=3),
    page: int = Query(default=1, ge=1),
    page_size: int = Query(default=10, ge=1, le=10),
    category_id: str = "",
):
    """Ranking de produtos mais vendidos no TikTok Shop BR."""
    client = _get_echotik()
    products = client.product_ranking(date, rank_field, page=page, page_size=page_size, category_id=category_id)
    return {"products": products, "total": len(products)}


@router.get("/echotik/product/search")
def echotik_product_search(
    keyword: str = "",
    page: int = Query(default=1, ge=1),
    page_size: int = Query(default=10, ge=1, le=10),
):
    """Buscar produtos no TikTok Shop BR."""
    client = _get_echotik()
    try:
        products = client.product_search(keyword, page, page_size)
    except Exception as e:
        logger.warning(f"EchoTik product search failed: {e}")
        products = []
    return {"products": products, "total": len(products)}


@router.get("/echotik/product/detail")
def echotik_product_detail(product_id: str):
    """Detalhes completos de um produto (vendas, GMV, estoque, SKUs)."""
    client = _get_echotik()
    try:
        return client.product_detail(product_id)
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=502, detail=f"Erro EchoTik: {e}")


@router.get("/echotik/product/trend")
def echotik_product_trend(product_id: str, days: int = Query(default=7, ge=1, le=30)):
    """Historico de vendas de um produto (trend) - dados locais via snapshots."""
    client = _get_echotik()
    try:
        return {"trend": client.product_trend(product_id, days), "product_id": product_id}
    except Exception as e:
        return {"trend": [], "product_id": product_id}


@router.post("/echotik/product/snapshot")
def echotik_product_snapshot(product_id: str):
    """Take a snapshot of product metrics for trend tracking."""
    client = _get_echotik()
    try:
        snapshot = client.take_snapshot(product_id)
        return {"status": "ok", "snapshot": snapshot}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/echotik/product/videos")
def echotik_product_videos(
    product_id: str,
    page: int = Query(default=1, ge=1),
    page_size: int = Query(default=10, ge=1, le=10),
):
    """Videos que promovem um produto."""
    client = _get_echotik()
    try:
        return {"videos": client.product_videos(product_id, page, page_size)}
    except Exception as e:
        return {"videos": []}


@router.get("/echotik/product/influencers")
def echotik_product_influencers(
    product_id: str,
    page: int = Query(default=1, ge=1),
    page_size: int = Query(default=10, ge=1, le=10),
):
    """Influencers que vendem um produto."""
    client = _get_echotik()
    try:
        return {"influencers": client.product_influencers(product_id, page, page_size)}
    except Exception as e:
        return {"influencers": []}


@router.get("/echotik/seller/ranking")
def echotik_seller_ranking(
    date: str = "",
    rank_field: int = Query(default=1, ge=1, le=2),
    page: int = Query(default=1, ge=1),
    page_size: int = Query(default=10, ge=1, le=10),
):
    """Ranking das melhores lojas do TikTok Shop BR."""
    client = _get_echotik()
    sellers = client.seller_ranking(date, rank_field, page=page, page_size=page_size)
    return {"sellers": sellers, "total": len(sellers)}


@router.get("/echotik/seller/detail")
def echotik_seller_detail(seller_id: str):
    """Detalhes completos de uma loja."""
    client = _get_echotik()
    try:
        return client.seller_detail(seller_id)
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=502, detail=f"Erro EchoTik: {e}")


@router.get("/echotik/seller/products")
def echotik_seller_products(
    seller_id: str,
    page: int = Query(default=1, ge=1),
    page_size: int = Query(default=10, ge=1, le=10),
):
    """Produtos de uma loja."""
    client = _get_echotik()
    try:
        return {"products": client.seller_products(seller_id, page, page_size)}
    except Exception as e:
        return {"products": []}


@router.get("/echotik/seller/search")
def echotik_seller_search(
    keyword: str = "",
    page: int = Query(default=1, ge=1),
    page_size: int = Query(default=10, ge=1, le=10),
):
    """Buscar lojas no TikTok Shop BR."""
    client = _get_echotik()
    try:
        return {"sellers": client.seller_search(keyword, page, page_size)}
    except Exception as e:
        return {"sellers": []}


@router.get("/echotik/influencer/ranking")
def echotik_influencer_ranking(
    date: str = "",
    rank_field: int = Query(default=1, ge=1, le=3),
    page: int = Query(default=1, ge=1),
    page_size: int = Query(default=20, ge=1, le=50),
    days: int = Query(default=30, ge=7, le=90),
):
    """Ranking dos top creators/influencers do TikTok BR (dados locais)."""
    client = _get_echotik()
    influencers = client.influencer_ranking(date, rank_field, page=page, page_size=page_size, days=days)
    return {"influencers": influencers, "total": len(influencers), "days": days}


@router.get("/echotik/video/ranking")
def echotik_video_ranking(
    date: str = "",
    rank_field: int = Query(default=1, ge=1, le=3),
    page: int = Query(default=1, ge=1),
    page_size: int = Query(default=20, ge=1, le=50),
    days: int = Query(default=30, ge=7, le=90),
):
    """Ranking dos videos mais virais do TikTok BR (dados locais)."""
    client = _get_echotik()
    videos = client.video_ranking(date, rank_field, page=page, page_size=page_size, days=days)
    return {"videos": videos, "total": len(videos), "days": days}


@router.get("/echotik/trends/daily")
def echotik_daily_trends(
    days: int = Query(default=30, ge=7, le=90),
):
    """Tendencias diarias de videos BR - dados para graficos."""
    client = _get_echotik()
    trends = client.daily_trends(days)
    return {"trends": trends, "days": days, "total": len(trends)}


@router.post("/echotik/sync")
def echotik_force_sync():
    """Force re-sync TikTok Shop data via Apify."""
    svc = _get_echotik()
    count = svc.sync_rankings()
    svc.clear_expired()
    return {"status": "ok", "synced": count, "message": f"{count} keywords sincronizados via Apify"}


@router.get("/echotik/cache/stats")
def echotik_cache_stats():
    """Get TikTok Shop cache statistics."""
    from backend.services.tiktok_shop_cache import TikTokShopCacheService
    return TikTokShopCacheService.get_cache_stats()


@router.get("/reports/{filename}")
def serve_report(filename: str):
    """Serve generated HTML/JSON reports from data/ folder."""
    import re
    if not re.match(r'^[\w\-\.]+\.(html|json)$', filename):
        raise HTTPException(status_code=400, detail="Invalid filename")
    filepath = Path("data") / filename
    if not filepath.exists():
        raise HTTPException(status_code=404, detail="Report not found")
    media = "text/html" if filename.endswith(".html") else "application/json"
    return FileResponse(str(filepath), media_type=media)


# ─── Video Analysis (AI-powered) ──────────────────────────────


@router.get("/analysis/video/{video_id}")
async def analyze_video(video_id: int, db: Session = Depends(get_db)):
    """Full AI-powered analysis of a video: hook score, shareability, velocity, etc."""
    from backend.services.video_analyzer import analyze_video_full, _video_to_dict
    video = db.query(Video).filter(Video.id == video_id).first()
    if not video:
        raise HTTPException(status_code=404, detail="Video nao encontrado")
    vdata = _video_to_dict(video)
    analysis = await analyze_video_full(vdata, db)
    analysis["video"] = vdata
    return analysis


@router.get("/analysis/video/{video_id}/hook")
def analyze_video_hook(video_id: int, db: Session = Depends(get_db)):
    """Hook strength analysis for a video."""
    from backend.services.video_analyzer import calculate_hook_score
    video = db.query(Video).filter(Video.id == video_id).first()
    if not video:
        raise HTTPException(status_code=404, detail="Video nao encontrado")
    return calculate_hook_score(video.title or "", video.description or "")


@router.get("/analysis/video/{video_id}/shareability")
def analyze_video_shareability(video_id: int, db: Session = Depends(get_db)):
    """Shareability prediction for a video."""
    from backend.services.video_analyzer import calculate_shareability, _video_to_dict
    video = db.query(Video).filter(Video.id == video_id).first()
    if not video:
        raise HTTPException(status_code=404, detail="Video nao encontrado")
    return calculate_shareability(_video_to_dict(video))


@router.get("/analysis/emerging")
def get_emerging_videos(
    hours: int = Query(default=24, le=168),
    min_velocity: float = 30,
    db: Session = Depends(get_db),
):
    """Find emerging videos: published recently with high engagement velocity."""
    from backend.services.video_analyzer import detect_emerging_videos
    videos = detect_emerging_videos(db, hours=hours, min_velocity=min_velocity)
    return {"videos": videos, "total": len(videos), "hours": hours}


@router.get("/analysis/batch")
def analyze_videos_batch(
    limit: int = Query(default=50, le=200),
    min_viral_score: float = 0,
    sort_by: str = "viral_score",
    platform: str = "",
    db: Session = Depends(get_db),
):
    """Batch analysis: hook score + shareability + velocity for top videos."""
    from backend.services.video_analyzer import (
        calculate_hook_score, calculate_shareability,
        calculate_engagement_velocity, predict_completion_rate,
        calculate_monetization_potential, _video_to_dict,
    )
    q = db.query(Video)
    if min_viral_score > 0:
        q = q.filter(Video.viral_score >= min_viral_score)
    if platform:
        q = q.filter(Video.platform == platform)

    order_map = {
        "viral_score": Video.viral_score.desc(),
        "views": Video.views.desc(),
        "recent": Video.collected_at.desc(),
        "outlier": Video.outlier_ratio.desc(),
        "replicability": Video.replicability_score.desc(),
    }
    q = q.order_by(order_map.get(sort_by, Video.viral_score.desc()))
    videos = q.limit(limit).all()

    results = []
    for v in videos:
        vdata = _video_to_dict(v)
        hook = calculate_hook_score(v.title or "", v.description or "")
        shareability = calculate_shareability(vdata)
        velocity = calculate_engagement_velocity(vdata)
        completion = predict_completion_rate(vdata)
        monetization = calculate_monetization_potential(vdata)

        results.append({
            **vdata,
            "hook_score": hook["score"],
            "hook_type": hook["hook_type"],
            "shareability_score": shareability["score"],
            "shareability_label": shareability["label"],
            "velocity_score": velocity["velocity_score"],
            "velocity_label": velocity["label"],
            "completion_predicted": completion["predicted_rate"],
            "monetization_score": monetization["score"],
            "monetization_label": monetization["label"],
        })

    return {"videos": results, "total": len(results)}


@router.post("/analysis/hook-score")
def calculate_hook_score_api(title: str = "", description: str = ""):
    """Calculate hook score for custom text (for testing before posting)."""
    from backend.services.video_analyzer import calculate_hook_score
    if not title:
        raise HTTPException(status_code=400, detail="Titulo e obrigatorio")
    return calculate_hook_score(title, description)


@router.post("/analysis/hook-ai")
async def analyze_hook_ai_api(
    video_id: int = 0,
    transcript_text: str = "",
    title: str = "",
    db: Session = Depends(get_db),
):
    """AI-powered hook analysis using LLM on transcript text."""
    from backend.services.video_analyzer import analyze_hook_ai
    if video_id:
        video = db.query(Video).filter(Video.id == video_id).first()
        if not video:
            raise HTTPException(status_code=404, detail="Video nao encontrado")
        title = title or video.title or ""
        transcript_text = transcript_text or video.description or ""
    if not transcript_text and not title:
        raise HTTPException(status_code=400, detail="transcript_text ou video_id obrigatorio")
    return await analyze_hook_ai(transcript_text, title)


@router.post("/analysis/sentiment")
def analyze_sentiment_api(texts: list[str] = []):
    """Analyze sentiment of texts (comments, titles, etc.)."""
    from backend.services.local_ai import analyze_sentiment_batch
    if not texts:
        raise HTTPException(status_code=400, detail="Lista de textos vazia")
    return analyze_sentiment_batch(texts)


@router.get("/analysis/ai-status")
async def ai_status():
    """Check status of local AI services."""
    from backend.services.local_ai import llm_available
    ollama_ok = await llm_available()
    return {
        "ollama": {"available": ollama_ok, "model": "qwen2.5:3b"},
        "vader": {"available": True, "model": "VADER (NLTK)"},
        "embeddings": {"available": True, "model": "all-MiniLM-L6-v2"},
        "whisper": {"available": True, "model": "faster-whisper base"},
    }


# ─── Trend Intelligence (TrendRadar AI) ──────────────────────


@router.get("/trend-intelligence/alerts")
def get_trend_alerts_api(
    hours: int = Query(default=24, le=168),
    db: Session = Depends(get_db),
):
    """Get trend alerts: opportunities, explosions, cross-platform trends."""
    from backend.services.trend_intelligence import get_trend_alerts
    return {"alerts": get_trend_alerts(db, hours)}


@router.get("/trend-intelligence/creators")
def get_trending_creators_api(
    days: int = Query(default=7, le=90),
    platform: str = "",
    limit: int = Query(default=20, le=50),
    db: Session = Depends(get_db),
):
    """Find fastest-growing creators by viral score sum."""
    from backend.services.trend_intelligence import get_trending_creators
    return {"creators": get_trending_creators(db, days, limit, platform)}


@router.get("/trend-intelligence/niches")
def get_niche_trends_api(
    niche: str = "",
    days: int = Query(default=7, le=90),
    platform: str = "",
    db: Session = Depends(get_db),
):
    """Niche-specific trend radar with growth metrics."""
    from backend.services.trend_intelligence import get_niche_trends
    return get_niche_trends(db, niche, days, platform)


@router.get("/trend-intelligence/saturation")
def check_saturation_api(
    keyword: str = "",
    days: int = Query(default=14, le=90),
    db: Session = Depends(get_db),
):
    """Check if a keyword/trend is saturated."""
    from backend.services.trend_intelligence import check_saturation
    if not keyword:
        raise HTTPException(status_code=400, detail="Keyword obrigatoria")
    return check_saturation(db, keyword, days)


@router.get("/trend-intelligence/timeline")
def get_trend_timeline_api(
    keyword: str = "",
    days: int = Query(default=30, le=90),
    db: Session = Depends(get_db),
):
    """Trend lifecycle timeline: birth → growth → peak → decline."""
    from backend.services.trend_intelligence import get_trend_timeline
    if not keyword:
        raise HTTPException(status_code=400, detail="Keyword obrigatoria")
    return get_trend_timeline(db, keyword, days)


@router.get("/trend-intelligence/formats")
def get_format_trends_api(
    days: int = Query(default=7, le=90),
    platform: str = "",
    db: Session = Depends(get_db),
):
    """Analyze which video formats (tutorial, POV, challenge...) are trending."""
    from backend.services.trend_intelligence import analyze_format_trends
    return analyze_format_trends(db, days, platform)


@router.get("/trend-intelligence/best-time")
def get_best_time_api(
    days: int = Query(default=14, le=90),
    platform: str = "",
    niche: str = "",
    db: Session = Depends(get_db),
):
    """Predict best posting time based on high-scoring video data."""
    from backend.services.trend_intelligence import predict_best_time
    return predict_best_time(db, days, platform, niche)


@router.get("/trend-intelligence/best-platform")
def get_best_platform_api(
    keyword: str = "",
    days: int = Query(default=14, le=90),
    db: Session = Depends(get_db),
):
    """Predict which platform performs best for a keyword."""
    from backend.services.trend_intelligence import predict_best_platform
    return predict_best_platform(db, keyword, days)


@router.get("/trend-intelligence/cross-platform")
def get_cross_platform_api(
    days: int = Query(default=7, le=30),
    db: Session = Depends(get_db),
):
    """Find hashtags trending on multiple platforms simultaneously."""
    from backend.services.trend_intelligence import detect_cross_platform
    return {"trends": detect_cross_platform(db, days)}


# ─── Shop Analytics (ShopIntel AI) ───────────────────────────


@router.get("/shop-analytics/viral-products")
def get_viral_products_api(
    days: int = Query(default=7, le=90),
    limit: int = Query(default=20, le=50),
    db: Session = Depends(get_db),
):
    """Detect products with explosive sales growth."""
    from backend.services.shop_analytics import detect_viral_products
    return {"products": detect_viral_products(db, days, limit=limit)}


@router.get("/shop-analytics/lifecycle/{product_id}")
def get_product_lifecycle_api(product_id: str, db: Session = Depends(get_db)):
    """Analyze product lifecycle stage (launch/growth/maturity/decline)."""
    from backend.services.shop_analytics import analyze_product_lifecycle
    return analyze_product_lifecycle(db, product_id)


@router.get("/shop-analytics/alerts")
def get_shop_alerts_api(
    hours: int = Query(default=48, le=168),
    db: Session = Depends(get_db),
):
    """Get price changes, stock alerts, and sales spikes."""
    from backend.services.shop_analytics import get_price_stock_alerts
    return {"alerts": get_price_stock_alerts(db, hours)}


@router.get("/shop-analytics/affiliate-network")
def get_affiliate_network_api(
    days: int = Query(default=30, le=90),
    limit: int = Query(default=50, le=100),
    db: Session = Depends(get_db),
):
    """Map creator-product affiliate relationships."""
    from backend.services.shop_analytics import get_affiliate_network
    return get_affiliate_network(db, days, limit)


@router.post("/shop-analytics/commission")
def calculate_commission_api(
    price: float = 0,
    category: str = "outros",
    daily_sales: float = 10,
    commission_pct: float = 0,
):
    """Calculate estimated affiliate commission."""
    from backend.services.shop_analytics import calculate_commission
    if price <= 0:
        raise HTTPException(status_code=400, detail="Preco obrigatorio")
    return calculate_commission(price, category, daily_sales, commission_pct)


@router.get("/shop-analytics/top-commissions")
def get_top_commissions_api(
    days: int = Query(default=7, le=90),
    limit: int = Query(default=20, le=50),
    db: Session = Depends(get_db),
):
    """Find products with highest commission opportunity."""
    from backend.services.shop_analytics import get_top_commission_products
    return {"products": get_top_commission_products(db, days, limit)}


@router.get("/shop-analytics/category-heatmap")
def get_category_heatmap_api(
    days: int = Query(default=7, le=90),
    db: Session = Depends(get_db),
):
    """Category trend heatmap for products and videos."""
    from backend.services.shop_analytics import get_category_heatmap
    return get_category_heatmap(db, days)


@router.get("/shop-analytics/opportunity/{product_id}")
def get_product_opportunity_api(product_id: str, db: Session = Depends(get_db)):
    """Calculate product opportunity score (velocity + lifecycle + competition)."""
    from backend.services.shop_analytics import score_product_opportunity
    return score_product_opportunity(db, product_id)


@router.get("/shop-analytics/reviews/{product_id}")
def get_product_reviews_api(product_id: str, db: Session = Depends(get_db)):
    """Analyze product review sentiment using VADER."""
    from backend.services.shop_analytics import analyze_product_reviews
    return analyze_product_reviews(db, product_id)


@router.get("/shop-analytics/store-revenue")
def get_store_revenue_api(
    shop_name: str = "",
    days: int = Query(default=30, le=90),
    limit: int = Query(default=20, le=50),
    db: Session = Depends(get_db),
):
    """Estimate store/seller monthly revenue."""
    from backend.services.shop_analytics import estimate_store_revenue
    return estimate_store_revenue(db, shop_name, days, limit)


@router.get("/shop-analytics/match-affiliates")
def get_affiliate_matches_api(
    days: int = Query(default=14, le=90),
    limit: int = Query(default=30, le=50),
    db: Session = Depends(get_db),
):
    """Match viral videos with products for affiliate opportunities."""
    from backend.services.shop_analytics import match_affiliates
    return {"matches": match_affiliates(db, days, limit)}


@router.get("/shop-analytics/suggest-products")
async def get_product_suggestions_api(
    niche: str = "",
    limit: int = Query(default=10, le=30),
    db: Session = Depends(get_db),
):
    """AI-powered product suggestions by niche."""
    from backend.services.shop_analytics import suggest_products_by_niche
    return await suggest_products_by_niche(db, niche, limit)


@router.get("/shop-analytics/optimize-commission")
def get_commission_optimizer_api(
    budget_hours: int = Query(default=20, le=100),
    days: int = Query(default=7, le=90),
    db: Session = Depends(get_db),
):
    """Optimize product mix to maximize commission with limited time."""
    from backend.services.shop_analytics import optimize_commission_mix
    return optimize_commission_mix(db, budget_hours, days)


@router.get("/shop-analytics/seasonal")
def get_seasonal_predictions_api(
    months_ahead: int = Query(default=2, le=6),
    db: Session = Depends(get_db),
):
    """Predict seasonal product demand for upcoming events."""
    from backend.services.shop_analytics import predict_seasonal_products
    return predict_seasonal_products(db, months_ahead)


@router.get("/shop-analytics/predict-viral")
async def predict_viral_products_api(
    days: int = Query(default=14, le=30),
    limit: int = Query(default=10, le=50),
    db: Session = Depends(get_db),
):
    """Predict which products are about to go viral using acceleration scoring + AI."""
    from backend.services.shop_analytics import predict_viral_products
    return await predict_viral_products(db, days, limit)


@router.post("/shop-analytics/video-template")
async def generate_video_template_api(
    product_id: int = 0,
    style: str = "review",
    db: Session = Depends(get_db),
):
    """Generate a structured video script template for a product."""
    from backend.services.shop_analytics import generate_product_video_template
    if not product_id:
        raise HTTPException(status_code=400, detail="product_id obrigatorio")
    return await generate_product_video_template(db, product_id, style)


@router.post("/shop-analytics/sales-script")
async def generate_sales_script_api(
    product_id: int = 0,
    audience: str = "geral",
    tone: str = "conversacional",
    db: Session = Depends(get_db),
):
    """Generate a conversion-optimized sales script for a product."""
    from backend.services.shop_analytics import generate_sales_script
    if not product_id:
        raise HTTPException(status_code=400, detail="product_id obrigatorio")
    return await generate_sales_script(db, product_id, audience, tone)


@router.post("/shop-analytics/live-planner")
async def plan_live_commerce_api(
    product_ids: str = "",
    duration_minutes: int = 60,
    db: Session = Depends(get_db),
):
    """Plan a live commerce session with AI-generated schedule and scripts."""
    from backend.services.shop_analytics import plan_live_commerce
    ids = [int(x) for x in product_ids.split(",") if x.strip().isdigit()] if product_ids else None
    return await plan_live_commerce(db, ids, duration_minutes)


# ─── ViralScan Advanced Features ────────────────────────────


@router.get("/analysis/save-share/{video_id}")
def get_save_share_ratio_api(video_id: int, db: Session = Depends(get_db)):
    """Analyze save/share ratio and algorithmic boost signals."""
    from backend.services.video_analyzer import calculate_save_share_ratio, _video_to_dict
    from backend.models.collection import Collection, VideoCollection
    video = db.query(Video).filter(Video.id == video_id).first()
    if not video:
        raise HTTPException(status_code=404, detail="Video nao encontrado")
    return calculate_save_share_ratio(_video_to_dict(video))


@router.get("/analysis/emotional-arc/{video_id}")
async def get_emotional_arc_api(video_id: int, db: Session = Depends(get_db)):
    """Map emotional arc of a video using AI."""
    from backend.services.video_analyzer import map_emotional_arc
    from backend.models.collection import Collection, VideoCollection
    video = db.query(Video).filter(Video.id == video_id).first()
    if not video:
        raise HTTPException(status_code=404, detail="Video nao encontrado")
    return await map_emotional_arc(video.title or "", video.description or "")


@router.post("/analysis/emotional-arc")
async def analyze_emotional_arc_api(title: str = "", description: str = ""):
    """Map emotional arc of custom text using AI."""
    from backend.services.video_analyzer import map_emotional_arc
    if not title:
        raise HTTPException(status_code=400, detail="Titulo obrigatorio")
    return await map_emotional_arc(title, description)


@router.get("/analysis/geographic")
def get_geographic_scan_api(
    region: str = "",
    language: str = "",
    days: int = Query(default=7, le=30),
    limit: int = Query(default=50, le=100),
    db: Session = Depends(get_db),
):
    """Filter and analyze viral videos by geographic region."""
    from backend.services.video_analyzer import scan_by_region
    from backend.models.collection import Collection, VideoCollection
    return scan_by_region(db, region, language, days, limit)


# ─── TrendRadar Advanced Features ───────────────────────────


@router.get("/trend-intelligence/micro-trends")
def get_micro_trends_api(
    hours: int = Query(default=48, le=168),
    db: Session = Depends(get_db),
):
    """Detect micro-trends: brand new hashtags with strong engagement."""
    from backend.services.trend_intelligence import detect_micro_trends
    return {"trends": detect_micro_trends(db, hours)}


@router.get("/trend-intelligence/algorithm-changes")
def get_algorithm_changes_api(
    days: int = Query(default=14, le=30),
    db: Session = Depends(get_db),
):
    """Detect potential platform algorithm changes."""
    from backend.services.trend_intelligence import detect_algorithm_changes
    return detect_algorithm_changes(db, days)


@router.get("/trend-intelligence/music-patterns")
def get_music_patterns_api(
    days: int = Query(default=7, le=30),
    platform: str = "",
    db: Session = Depends(get_db),
):
    """Analyze music/sound patterns in viral videos."""
    from backend.services.trend_intelligence import analyze_music_patterns
    return analyze_music_patterns(db, days, platform)


@router.get("/trend-intelligence/global-map")
def get_global_map_api(
    days: int = Query(default=7, le=30),
    db: Session = Depends(get_db),
):
    """Global trend map by country/region."""
    from backend.services.trend_intelligence import get_global_trend_map
    return get_global_trend_map(db, days)


@router.get("/trend-intelligence/stepps")
def get_stepps_score_api(
    keyword: str = "",
    hashtag: str = "",
    days: int = Query(default=7, le=30),
    db: Session = Depends(get_db),
):
    """Calculate STEPPS virality score (Jonah Berger framework) for a keyword/hashtag."""
    from backend.services.trend_intelligence import calculate_stepps_score
    if not keyword and not hashtag:
        raise HTTPException(status_code=400, detail="keyword ou hashtag obrigatorio")
    return calculate_stepps_score(db, keyword, hashtag, days)


@router.get("/trend-intelligence/revenue-prediction")
def predict_revenue_api(
    keyword: str = "",
    platform: str = "tiktok",
    days: int = Query(default=14, le=30),
    db: Session = Depends(get_db),
):
    """Predict potential revenue from a trending keyword."""
    from backend.services.trend_intelligence import predict_trend_revenue
    if not keyword:
        raise HTTPException(status_code=400, detail="keyword obrigatorio")
    return predict_trend_revenue(db, keyword, platform, days)


@router.get("/trend-intelligence/sentiment-virality")
def get_sentiment_virality_api(
    keyword: str = "",
    days: int = Query(default=7, le=30),
    db: Session = Depends(get_db),
):
    """Analyze sentiment vs virality correlation for a keyword."""
    from backend.services.trend_intelligence import analyze_sentiment_virality
    if not keyword:
        raise HTTPException(status_code=400, detail="keyword obrigatorio")
    return analyze_sentiment_virality(db, keyword, days)


@router.get("/trend-intelligence/weekly-report")
async def get_weekly_report_api(db: Session = Depends(get_db)):
    """Generate comprehensive weekly trend report with AI narrative."""
    from backend.services.trend_intelligence import generate_weekly_report
    return await generate_weekly_report(db)


@router.post("/trend-intelligence/telegram-alert")
async def send_telegram_alert_api(
    bot_token: str = "",
    chat_id: str = "",
    db: Session = Depends(get_db),
):
    """Send trend alerts via Telegram."""
    from backend.services.trend_intelligence import (
        get_trend_alerts, send_telegram_alert, format_alert_for_telegram
    )
    if not bot_token or not chat_id:
        raise HTTPException(status_code=400, detail="bot_token e chat_id obrigatorios")
    alerts = get_trend_alerts(db, hours=24)
    message = format_alert_for_telegram(alerts)
    return await send_telegram_alert(message, bot_token, chat_id)


# ─── EngageBot ──────────────────────────────────────────────

@router.post("/engage/auto-reply")
async def engage_auto_reply(
    comment: str = "",
    video_title: str = "",
    tone: str = "friendly",
    language: str = "pt",
):
    """Generate AI auto-reply for a comment."""
    from backend.services.engage_bot import generate_auto_reply
    if not comment:
        raise HTTPException(status_code=400, detail="comment obrigatorio")
    return await generate_auto_reply(comment, video_title, tone, language)


@router.post("/engage/classify")
def engage_classify(comment: str = ""):
    """Classify a single comment (sentiment, spam, hate, question)."""
    from backend.services.engage_bot import classify_comment
    if not comment:
        raise HTTPException(status_code=400, detail="comment obrigatorio")
    return classify_comment(comment)


@router.post("/engage/batch-classify")
def engage_batch_classify(data: dict = None):
    """Batch classify multiple comments."""
    from backend.services.engage_bot import batch_classify_comments
    if not data or "comments" not in data:
        raise HTTPException(status_code=400, detail="comments obrigatorio (lista de strings)")
    return batch_classify_comments(data["comments"])


@router.post("/engage/detect-faq")
def engage_detect_faq(data: dict = None):
    """Detect FAQ patterns in comments."""
    from backend.services.engage_bot import detect_faq_patterns
    if not data or "comments" not in data:
        raise HTTPException(status_code=400, detail="comments obrigatorio (lista de strings)")
    min_freq = data.get("min_frequency", 3)
    return detect_faq_patterns(data["comments"], min_freq)


@router.post("/engage/detect-pain-points")
def engage_detect_pain_points(data: dict = None):
    """Detect pain points in comments."""
    from backend.services.engage_bot import detect_pain_points
    if not data or "comments" not in data:
        raise HTTPException(status_code=400, detail="comments obrigatorio (lista de strings)")
    return detect_pain_points(data["comments"])


@router.post("/engage/faq-content")
async def engage_faq_content(data: dict = None):
    """Generate content ideas from FAQs."""
    from backend.services.engage_bot import generate_faq_content
    if not data or "faqs" not in data:
        raise HTTPException(status_code=400, detail="faqs obrigatorio")
    return await generate_faq_content(data["faqs"])


@router.post("/engage/community-health")
def engage_community_health(data: dict = None):
    """Calculate community health score from comments."""
    from backend.services.engage_bot import calculate_community_health
    if not data or "comments" not in data:
        raise HTTPException(status_code=400, detail="comments obrigatorio (lista de strings)")
    engagement_data = data.get("engagement_data", None)
    return calculate_community_health(data["comments"], engagement_data)


@router.post("/engage/welcome-dm")
async def engage_welcome_dm(
    creator_name: str = "",
    new_follower: str = "",
    niche: str = "",
):
    """Generate personalized welcome DM."""
    from backend.services.engage_bot import generate_welcome_dm
    if not creator_name:
        raise HTTPException(status_code=400, detail="creator_name obrigatorio")
    return await generate_welcome_dm(creator_name, new_follower, niche)


@router.post("/engage/keyword-triggers")
def engage_keyword_triggers(data: dict = None):
    """Detect keyword triggers in text."""
    from backend.services.engage_bot import detect_keyword_triggers
    if not data or "text" not in data:
        raise HTTPException(status_code=400, detail="text obrigatorio")
    triggers = data.get("triggers", None)
    return detect_keyword_triggers(data["text"], triggers)


@router.get("/engage/comment-pipeline")
async def engage_comment_pipeline(
    days: int = Query(default=7, le=30),
    limit: int = Query(default=50, le=200),
    db: Session = Depends(get_db),
):
    """Full comment-to-content pipeline."""
    from backend.services.engage_bot import comment_to_content_pipeline
    return await comment_to_content_pipeline(db, days, limit)


@router.get("/engage/analytics")
def engage_analytics(
    days: int = Query(default=7, le=30),
    db: Session = Depends(get_db),
):
    """Get engagement analytics for recent videos."""
    from backend.services.engage_bot import get_engagement_analytics
    return get_engagement_analytics(db, days)


@router.post("/engage/batch-responses")
async def engage_batch_responses(data: dict = None):
    """Generate AI responses for multiple comments."""
    from backend.services.engage_bot import generate_comment_responses_batch
    if not data or "comments" not in data:
        raise HTTPException(status_code=400, detail="comments obrigatorio (lista de strings)")
    tone = data.get("tone", "friendly")
    return await generate_comment_responses_batch(data["comments"], tone)


# ─── DarkFactory Pipeline ──────────────────────────────────


@router.post("/dark-factory/pipeline")
async def dark_factory_start_pipeline(body: dict, db: Session = Depends(get_db)):
    """Start a full video production pipeline."""
    from backend.services.dark_factory import generate_video_pipeline
    topic = body.get("topic", "")
    if not topic:
        raise HTTPException(status_code=400, detail="topic obrigatorio")
    return await generate_video_pipeline(
        db=db,
        topic=topic,
        niche=body.get("niche", "curiosidades"),
        duration_minutes=body.get("duration_minutes", 10),
        voice=body.get("voice", "pt-BR-AntonioNeural"),
        style=body.get("style", "cinematic"),
    )


@router.get("/dark-factory/pipeline/{pipeline_id}")
def dark_factory_get_pipeline(pipeline_id: str):
    """Get status of a specific pipeline."""
    from backend.services.dark_factory import get_pipeline_status
    result = get_pipeline_status(pipeline_id)
    if result.get("error"):
        raise HTTPException(status_code=404, detail=result["error"])
    return result


@router.get("/dark-factory/pipelines")
def dark_factory_list_pipelines(limit: int = Query(default=20, le=50)):
    """List all pipelines."""
    from backend.services.dark_factory import list_pipelines
    return {"pipelines": list_pipelines(limit)}


@router.post("/dark-factory/script")
async def dark_factory_generate_script(body: dict):
    """Generate a dark channel script only (without full pipeline)."""
    from backend.services.dark_factory import generate_dark_script
    topic = body.get("topic", "")
    if not topic:
        raise HTTPException(status_code=400, detail="topic obrigatorio")
    return await generate_dark_script(
        topic=topic,
        niche=body.get("niche", "curiosidades"),
        duration_minutes=body.get("duration_minutes", 10),
        style=body.get("style", "informativo"),
    )


@router.post("/dark-factory/narration")
async def dark_factory_generate_narration(body: dict):
    """Generate TTS narration from script text."""
    from backend.services.dark_factory import generate_narration
    text = body.get("text", "")
    if not text:
        raise HTTPException(status_code=400, detail="text obrigatorio")
    return await generate_narration(
        script_text=text,
        voice=body.get("voice", "pt-BR-AntonioNeural"),
        output_dir=body.get("output_dir", "downloads/narrations"),
    )


@router.post("/dark-factory/footage")
async def dark_factory_select_footage(body: dict):
    """Search for stock footage based on keywords."""
    from backend.services.dark_factory import select_stock_footage
    keywords = body.get("keywords", [])
    if not keywords:
        raise HTTPException(status_code=400, detail="keywords obrigatorio (lista de strings)")
    return await select_stock_footage(
        keywords=keywords,
        count=body.get("count", 10),
    )


@router.post("/dark-factory/thumbnail-prompt")
async def dark_factory_thumbnail_prompt(body: dict):
    """Generate a thumbnail prompt/description."""
    from backend.services.dark_factory import generate_thumbnail_prompt
    title = body.get("title", "")
    if not title:
        raise HTTPException(status_code=400, detail="title obrigatorio")
    return await generate_thumbnail_prompt(
        title=title,
        niche=body.get("niche", "curiosidades"),
    )


@router.post("/dark-factory/batch")
async def dark_factory_batch(body: dict, db: Session = Depends(get_db)):
    """Queue multiple videos for batch production."""
    from backend.services.dark_factory import batch_produce
    topics = body.get("topics", [])
    if not topics:
        raise HTTPException(status_code=400, detail="topics obrigatorio (lista de strings)")
    return await batch_produce(
        db=db,
        topics=topics,
        niche=body.get("niche", "curiosidades"),
        duration_minutes=body.get("duration_minutes", 10),
    )


@router.get("/dark-factory/niches")
def dark_factory_niches(niche: str = ""):
    """Get info about available niches with RPM data."""
    from backend.services.dark_factory import get_niche_info
    return get_niche_info(niche)


@router.post("/dark-factory/seo")
async def dark_factory_seo(body: dict):
    """Generate SEO-optimized metadata for YouTube."""
    from backend.services.dark_factory import generate_seo_metadata
    title = body.get("title", "")
    if not title:
        raise HTTPException(status_code=400, detail="title obrigatorio")
    return await generate_seo_metadata(
        title=title,
        niche=body.get("niche", "curiosidades"),
        script_summary=body.get("script_summary", ""),
    )


@router.get("/dark-factory/cost-estimate")
async def dark_factory_cost_estimate(
    duration_minutes: int = Query(default=10, le=60),
    has_narration: bool = True,
    footage_clips: int = Query(default=10, le=50),
):
    """Estimate the cost of producing a video."""
    from backend.services.dark_factory import estimate_pipeline_cost
    return await estimate_pipeline_cost(duration_minutes, has_narration, footage_clips)


@router.get("/dark-factory/stats")
def dark_factory_stats():
    """Get DarkFactory production statistics."""
    from backend.services.dark_factory import get_production_stats
    return get_production_stats()


# ─── AutoFlow Workflows ─────────────────────────────────────────

@router.post("/autoflow/workflows")
def create_autoflow_workflow(
    name: str = "",
    description: str = "",
    trigger_type: str = "manual",
    trigger_config: dict = None,
    steps: list = None,
):
    """Create a new AutoFlow workflow."""
    from backend.services.workflow_engine import create_workflow
    if not name:
        raise HTTPException(status_code=400, detail="name obrigatorio")
    return create_workflow(name, description, trigger_type, trigger_config, steps)


@router.get("/autoflow/workflows")
def list_autoflow_workflows():
    """List all AutoFlow workflows."""
    from backend.services.workflow_engine import list_workflows
    return list_workflows()


@router.get("/autoflow/workflows/{workflow_id}")
def get_autoflow_workflow(workflow_id: str):
    """Get details of a specific workflow."""
    from backend.services.workflow_engine import get_workflow
    result = get_workflow(workflow_id)
    if "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
    return result


@router.delete("/autoflow/workflows/{workflow_id}")
def delete_autoflow_workflow(workflow_id: str):
    """Delete a workflow."""
    from backend.services.workflow_engine import delete_workflow
    success = delete_workflow(workflow_id)
    if not success:
        raise HTTPException(status_code=404, detail="Workflow nao encontrado")
    return {"success": True, "message": "Workflow deletado"}


@router.post("/autoflow/workflows/{workflow_id}/run")
async def run_autoflow_workflow(
    workflow_id: str,
    input_data: dict = None,
    db: Session = Depends(get_db),
):
    """Execute a workflow."""
    from backend.services.workflow_engine import execute_workflow
    result = await execute_workflow(workflow_id, db, input_data)
    if "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
    return result


@router.get("/autoflow/runs")
def list_autoflow_runs(
    workflow_id: str = "",
    limit: int = Query(default=20, le=100),
):
    """List workflow runs."""
    from backend.services.workflow_engine import list_workflow_runs
    return list_workflow_runs(workflow_id, limit)


@router.get("/autoflow/runs/{run_id}")
def get_autoflow_run(run_id: str):
    """Get details of a specific run."""
    from backend.services.workflow_engine import get_workflow_run
    result = get_workflow_run(run_id)
    if "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
    return result


@router.get("/autoflow/templates")
def get_autoflow_templates():
    """Get available workflow templates."""
    from backend.services.workflow_engine import get_workflow_templates
    return get_workflow_templates()


@router.post("/autoflow/templates/{template_id}/create")
async def create_from_autoflow_template(template_id: str, db: Session = Depends(get_db)):
    """Create a workflow from a template."""
    from backend.services.workflow_engine import create_from_template
    result = await create_from_template(template_id, db)
    if "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
    return result


@router.get("/autoflow/step-types")
def get_autoflow_step_types():
    """Get available step types."""
    from backend.services.workflow_engine import get_available_step_types
    return get_available_step_types()


@router.get("/autoflow/cost-estimate/{workflow_id}")
def get_autoflow_cost_estimate(workflow_id: str):
    """Estimate cost of running a workflow."""
    from backend.services.workflow_engine import estimate_workflow_cost
    result = estimate_workflow_cost(workflow_id)
    if "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
    return result


@router.get("/autoflow/stats")
def get_autoflow_stats():
    """Get automation statistics."""
    from backend.services.workflow_engine import get_automation_stats
    return get_automation_stats()


@router.post("/autoflow/content-factory")
async def run_content_factory(
    topics: list = None,
    count: int = Query(default=5, le=20),
    niche: str = "",
    db: Session = Depends(get_db),
):
    """Run the content factory pipeline."""
    from backend.services.workflow_engine import content_factory_pipeline
    return await content_factory_pipeline(db, topics, count, niche)


# ─── CreatorCRM ──────────────────────────────────────────────

@router.get("/crm/discover")
def crm_discover(
    niche: str = "",
    platform: str = "",
    min_followers: int = 0,
    max_followers: int = 0,
    limit: int = Query(default=20, le=50),
    db: Session = Depends(get_db),
):
    """Discover influencers by niche/platform/follower range."""
    from backend.services.creator_crm import discover_influencers
    return discover_influencers(db, niche, platform, min_followers, max_followers, limit)


@router.post("/crm/influence-score")
def crm_influence_score(data: dict):
    """Calculate influence score for a creator."""
    from backend.services.creator_crm import calculate_influence_score
    return calculate_influence_score(**data)


@router.get("/crm/fake-detection/{creator_id}")
def crm_fake_detection(creator_id: int, db: Session = Depends(get_db)):
    """Detect fake followers for a creator."""
    from backend.services.creator_crm import detect_fake_followers
    return detect_fake_followers(db, creator_id)


@router.get("/crm/media-kit/{creator_id}")
async def crm_media_kit(creator_id: int, db: Session = Depends(get_db)):
    """Generate AI media kit for a creator."""
    from backend.services.creator_crm import generate_media_kit
    return await generate_media_kit(db, creator_id)


@router.post("/crm/contacts")
def crm_add_contact(data: dict):
    """Add a contact to CRM."""
    from backend.services.creator_crm import add_contact
    creator_id = data.get("creator_id", 0)
    if not creator_id:
        raise HTTPException(status_code=400, detail="creator_id obrigatorio")
    return add_contact(**data)


@router.get("/crm/contacts")
def crm_list_contacts(
    status: str = "",
    tag: str = "",
    limit: int = Query(default=50, le=200),
):
    """List CRM contacts."""
    from backend.services.creator_crm import list_contacts
    return list_contacts(status, tag, limit)


@router.get("/crm/contacts/{contact_id}")
def crm_get_contact(contact_id: str):
    """Get a specific contact."""
    from backend.services.creator_crm import get_contact
    result = get_contact(contact_id)
    if not result:
        raise HTTPException(status_code=404, detail="Contato nao encontrado")
    return result


@router.put("/crm/contacts/{contact_id}")
def crm_update_contact(contact_id: str, data: dict):
    """Update a contact."""
    from backend.services.creator_crm import update_contact
    return update_contact(contact_id, **data)


@router.delete("/crm/contacts/{contact_id}")
def crm_delete_contact(contact_id: str):
    """Delete a contact."""
    from backend.services.creator_crm import delete_contact
    if not delete_contact(contact_id):
        raise HTTPException(status_code=404, detail="Contato nao encontrado")
    return {"success": True}


@router.post("/crm/contacts/{contact_id}/interactions")
def crm_add_interaction(contact_id: str, data: dict):
    """Add interaction to a contact."""
    from backend.services.creator_crm import add_interaction
    return add_interaction(
        contact_id,
        data.get("type", "note"),
        data.get("content", ""),
    )


@router.post("/crm/outreach")
async def crm_outreach(data: dict):
    """Generate AI outreach message."""
    from backend.services.creator_crm import generate_outreach_message
    username = data.get("creator_username", "")
    if not username:
        raise HTTPException(status_code=400, detail="creator_username obrigatorio")
    return await generate_outreach_message(
        username,
        data.get("brand_name", ""),
        data.get("campaign_type", "review"),
        data.get("tone", "profissional"),
    )


@router.post("/crm/campaigns")
def crm_create_campaign(data: dict):
    """Create a campaign."""
    from backend.services.creator_crm import create_campaign
    name = data.get("name", "")
    if not name:
        raise HTTPException(status_code=400, detail="name obrigatorio")
    return create_campaign(**data)


@router.get("/crm/campaigns")
def crm_list_campaigns(status: str = ""):
    """List campaigns."""
    from backend.services.creator_crm import list_campaigns
    return list_campaigns(status)


@router.get("/crm/campaigns/{campaign_id}")
def crm_get_campaign(campaign_id: str):
    """Get campaign details."""
    from backend.services.creator_crm import get_campaign
    result = get_campaign(campaign_id)
    if not result:
        raise HTTPException(status_code=404, detail="Campanha nao encontrada")
    return result


@router.get("/crm/campaigns/{campaign_id}/roi")
def crm_campaign_roi(campaign_id: str):
    """Calculate campaign ROI."""
    from backend.services.creator_crm import calculate_campaign_roi
    return calculate_campaign_roi(campaign_id)


@router.get("/crm/revenue-dashboard")
def crm_revenue_dashboard(
    creator_id: int = 0,
    days: int = Query(default=30, le=90),
    db: Session = Depends(get_db),
):
    """Get creator revenue dashboard."""
    from backend.services.creator_crm import get_creator_revenue_dashboard
    return get_creator_revenue_dashboard(db, creator_id, days)


@router.post("/crm/sponsorship-rate")
def crm_sponsorship_rate(data: dict):
    """Calculate sponsorship rates."""
    from backend.services.creator_crm import calculate_sponsorship_rate
    return calculate_sponsorship_rate(
        data.get("followers", 0),
        data.get("engagement_rate", 0),
        data.get("platform", "tiktok"),
        data.get("niche", "geral"),
    )


@router.get("/crm/stats")
def crm_stats():
    """Get CRM statistics."""
    from backend.services.creator_crm import get_crm_stats
    return get_crm_stats()


# ─── AgencyHub ──────────────────────────────────────────────

@router.post("/agency/workspaces")
def agency_create_workspace(data: dict):
    """Create a workspace."""
    from backend.services.agency_hub import create_workspace
    name = data.get("name", "")
    if not name:
        raise HTTPException(status_code=400, detail="name obrigatorio")
    return create_workspace(**data)


@router.get("/agency/workspaces")
def agency_list_workspaces(status: str = ""):
    """List all workspaces."""
    from backend.services.agency_hub import list_workspaces
    return list_workspaces(status)


@router.get("/agency/workspaces/{workspace_id}")
def agency_get_workspace(workspace_id: str):
    """Get workspace details."""
    from backend.services.agency_hub import get_workspace
    result = get_workspace(workspace_id)
    if not result:
        raise HTTPException(status_code=404, detail="Workspace nao encontrado")
    return result


@router.put("/agency/workspaces/{workspace_id}")
def agency_update_workspace(workspace_id: str, data: dict):
    """Update a workspace."""
    from backend.services.agency_hub import update_workspace
    return update_workspace(workspace_id, **data)


@router.delete("/agency/workspaces/{workspace_id}")
def agency_delete_workspace(workspace_id: str):
    """Delete a workspace."""
    from backend.services.agency_hub import delete_workspace
    if not delete_workspace(workspace_id):
        raise HTTPException(status_code=404, detail="Workspace nao encontrado")
    return {"success": True}


@router.post("/agency/workspaces/{workspace_id}/channels")
def agency_add_channel(workspace_id: str, data: dict):
    """Add channel to workspace."""
    from backend.services.agency_hub import add_channel_to_workspace
    return add_channel_to_workspace(
        workspace_id,
        data.get("platform", ""),
        data.get("username", ""),
        data.get("url", ""),
    )


@router.put("/agency/workspaces/{workspace_id}/branding")
def agency_update_branding(workspace_id: str, data: dict):
    """Update white-label branding."""
    from backend.services.agency_hub import update_branding
    return update_branding(workspace_id, **data)


@router.get("/agency/workspaces/{workspace_id}/branding")
def agency_get_branding(workspace_id: str):
    """Get workspace branding."""
    from backend.services.agency_hub import get_branding
    return get_branding(workspace_id)


@router.post("/agency/workspaces/{workspace_id}/team")
def agency_invite_member(workspace_id: str, data: dict):
    """Invite team member."""
    from backend.services.agency_hub import invite_team_member
    email = data.get("email", "")
    if not email:
        raise HTTPException(status_code=400, detail="email obrigatorio")
    return invite_team_member(
        workspace_id, email,
        data.get("name", ""),
        data.get("role", "editor"),
    )


@router.get("/agency/workspaces/{workspace_id}/team")
def agency_list_team(workspace_id: str):
    """List team members."""
    from backend.services.agency_hub import list_team_members
    return list_team_members(workspace_id)


@router.put("/agency/team/{member_id}/role")
def agency_update_role(member_id: str, data: dict):
    """Update team member role."""
    from backend.services.agency_hub import update_member_role
    return update_member_role(member_id, data.get("role", "editor"))


@router.delete("/agency/workspaces/{workspace_id}/team/{member_id}")
def agency_remove_member(workspace_id: str, member_id: str):
    """Remove team member."""
    from backend.services.agency_hub import remove_team_member
    if not remove_team_member(workspace_id, member_id):
        raise HTTPException(status_code=404, detail="Membro nao encontrado")
    return {"success": True}


@router.get("/agency/roles")
def agency_roles():
    """Get available roles and permissions."""
    from backend.services.agency_hub import get_available_roles
    return get_available_roles()


@router.post("/agency/approvals")
def agency_submit_approval(data: dict):
    """Submit content for approval."""
    from backend.services.agency_hub import submit_for_approval
    return submit_for_approval(
        data.get("workspace_id", ""),
        data.get("content_type", "post"),
        data.get("content", {}),
        data.get("submitter", ""),
    )


@router.get("/agency/approvals")
def agency_list_approvals(workspace_id: str = "", status: str = ""):
    """List approvals."""
    from backend.services.agency_hub import list_approvals
    return list_approvals(workspace_id, status)


@router.put("/agency/approvals/{approval_id}")
def agency_review_approval(approval_id: str, data: dict):
    """Review an approval (approve/reject/revision)."""
    from backend.services.agency_hub import review_approval
    return review_approval(
        approval_id,
        data.get("action", ""),
        data.get("reviewer", ""),
        data.get("feedback", ""),
    )


@router.post("/agency/workspaces/{workspace_id}/report")
async def agency_generate_report(
    workspace_id: str,
    report_type: str = "weekly",
    db: Session = Depends(get_db),
):
    """Generate workspace report with AI narrative."""
    from backend.services.agency_hub import generate_workspace_report
    return await generate_workspace_report(workspace_id, db, report_type)


@router.get("/agency/reports")
def agency_list_reports(workspace_id: str = "", limit: int = Query(default=20, le=50)):
    """List reports."""
    from backend.services.agency_hub import list_reports
    return list_reports(workspace_id, limit)


@router.get("/agency/reports/{report_id}")
def agency_get_report(report_id: str):
    """Get a specific report."""
    from backend.services.agency_hub import get_report
    result = get_report(report_id)
    if not result:
        raise HTTPException(status_code=404, detail="Report nao encontrado")
    return result


@router.post("/agency/onboarding")
def agency_start_onboarding(data: dict):
    """Start client onboarding."""
    from backend.services.agency_hub import start_onboarding
    return start_onboarding(
        data.get("workspace_id", ""),
        data.get("client_name", ""),
        data.get("client_email", ""),
    )


@router.put("/agency/onboarding/{onboarding_id}/step/{step_number}")
def agency_update_onboarding(onboarding_id: str, step_number: int, data: dict):
    """Update onboarding step."""
    from backend.services.agency_hub import update_onboarding_step
    return update_onboarding_step(
        onboarding_id, step_number,
        data.get("status", "completed"),
        data.get("notes", ""),
    )


@router.get("/agency/onboarding")
def agency_list_onboardings(workspace_id: str = ""):
    """List onboardings."""
    from backend.services.agency_hub import list_onboardings
    return list_onboardings(workspace_id)


@router.get("/agency/sla/{workspace_id}")
def agency_sla(workspace_id: str):
    """Check SLA compliance."""
    from backend.services.agency_hub import check_sla_compliance
    return check_sla_compliance(workspace_id)


@router.get("/agency/stats")
def agency_stats():
    """Get agency-wide statistics."""
    from backend.services.agency_hub import get_agency_stats
    return get_agency_stats()


# ─── YouTube Upload endpoints ──────────────────────────────────

@router.get("/youtube/upload/auth/status")
def yt_upload_auth_status():
    """Check YouTube Upload OAuth status."""
    from backend.services.youtube_uploader import youtube_upload_service
    return youtube_upload_service.get_auth_status()


@router.post("/youtube/upload/auth/start")
def yt_upload_auth_start(request_obj: dict | None = None):
    """Generate OAuth authorization URL."""
    from starlette.requests import Request
    from backend.services.youtube_uploader import youtube_upload_service
    # Build redirect URI dynamically
    redirect_uri = "/api/youtube/upload/oauth/callback"
    if request_obj and "base_url" in request_obj:
        redirect_uri = request_obj["base_url"].rstrip("/") + redirect_uri
    return youtube_upload_service.get_auth_url(redirect_uri)


@router.post("/youtube/upload/auth/start-with-url")
def yt_upload_auth_start_url(data: dict):
    """Generate OAuth authorization URL with explicit base URL."""
    from backend.services.youtube_uploader import youtube_upload_service
    base_url = data.get("base_url", "").rstrip("/")
    redirect_uri = f"{base_url}/api/youtube/upload/oauth/callback"
    return youtube_upload_service.get_auth_url(redirect_uri)


@router.get("/youtube/upload/oauth/callback")
def yt_upload_oauth_callback(code: str = "", error: str = ""):
    """OAuth2 callback from Google."""
    from fastapi.responses import RedirectResponse
    from backend.services.youtube_uploader import youtube_upload_service

    if error:
        return RedirectResponse(url=f"/youtube-upload?auth_error={error}")

    if not code:
        return RedirectResponse(url="/youtube-upload?auth_error=no_code")

    # We need the same redirect_uri used in auth_start
    # Since we don't know the base_url here, we reconstruct from the request
    # The callback itself is the redirect_uri
    from starlette.requests import Request
    # Use a workaround: read from the saved flow state or use a generic approach
    result = youtube_upload_service.handle_auth_callback(
        code=code,
        redirect_uri="",  # Will be set by the caller
    )

    if result.get("success"):
        return RedirectResponse(url="/youtube-upload?auth=success")
    return RedirectResponse(url=f"/youtube-upload?auth_error={result.get('error', 'unknown')}")


@router.post("/youtube/upload/auth/callback")
def yt_upload_auth_callback_post(data: dict):
    """Handle OAuth callback via POST (from frontend)."""
    from backend.services.youtube_uploader import youtube_upload_service
    code = data.get("code", "")
    redirect_uri = data.get("redirect_uri", "")
    if not code:
        return {"error": "Codigo de autorizacao nao fornecido"}
    return youtube_upload_service.handle_auth_callback(code=code, redirect_uri=redirect_uri)


@router.post("/youtube/upload/auth/revoke")
def yt_upload_auth_revoke():
    """Revoke YouTube Upload OAuth tokens."""
    from backend.services.youtube_uploader import youtube_upload_service
    return youtube_upload_service.revoke_auth()


@router.post("/youtube/upload/client-secret")
async def yt_upload_client_secret(file: UploadFile = File(...)):
    """Upload client_secret.json for YouTube OAuth."""
    from backend.services.youtube_uploader import CLIENT_SECRET_PATH
    try:
        content = await file.read()
        # Validate it's valid JSON with required fields
        data = json.loads(content)
        if "installed" not in data and "web" not in data:
            return {"error": "JSON invalido. Deve conter 'installed' ou 'web' credentials."}
        CLIENT_SECRET_PATH.parent.mkdir(parents=True, exist_ok=True)
        CLIENT_SECRET_PATH.write_bytes(content)
        return {"success": True, "message": "client_secret.json salvo com sucesso"}
    except json.JSONDecodeError:
        return {"error": "Arquivo nao e um JSON valido"}
    except Exception as e:
        return {"error": str(e)}


@router.post("/youtube/upload/scan")
def yt_upload_scan(data: dict):
    """Scan a folder for video files."""
    from backend.services.youtube_uploader import youtube_upload_service
    folder = data.get("folder_path", "")
    if not folder:
        return {"error": "folder_path e obrigatorio"}
    return youtube_upload_service.scan_folder(folder)


@router.post("/youtube/upload/batch")
def yt_upload_create_batch(data: dict):
    """Create a new upload batch."""
    from backend.services.youtube_uploader import youtube_upload_service

    folder = data.get("folder_path", "")
    start_dt_str = data.get("start_datetime", "")
    if not folder or not start_dt_str:
        return {"error": "folder_path e start_datetime sao obrigatorios"}

    try:
        start_dt = datetime.fromisoformat(start_dt_str)
    except ValueError:
        return {"error": "start_datetime invalido. Use formato ISO (YYYY-MM-DDTHH:MM:SS)"}

    return youtube_upload_service.create_batch(
        folder_path=folder,
        start_datetime=start_dt,
        interval_minutes=data.get("interval_minutes", 120),
        name=data.get("name", ""),
        default_description=data.get("default_description", ""),
        default_tags=data.get("default_tags", ""),
        default_category_id=data.get("default_category_id", "22"),
        default_privacy=data.get("default_privacy", "private"),
        use_publish_at=data.get("use_publish_at", True),
    )


@router.get("/youtube/upload/batches")
def yt_upload_list_batches():
    """List all upload batches."""
    from backend.services.youtube_uploader import youtube_upload_service
    return youtube_upload_service.list_batches()


@router.get("/youtube/upload/batch/{batch_id}")
def yt_upload_get_batch(batch_id: int):
    """Get batch details with items."""
    from backend.services.youtube_uploader import youtube_upload_service
    return youtube_upload_service.get_batch(batch_id)


@router.post("/youtube/upload/batch/{batch_id}/pause")
def yt_upload_pause_batch(batch_id: int):
    """Pause a batch."""
    from backend.services.youtube_uploader import youtube_upload_service
    return youtube_upload_service.pause_batch(batch_id)


@router.post("/youtube/upload/batch/{batch_id}/resume")
def yt_upload_resume_batch(batch_id: int):
    """Resume a paused batch."""
    from backend.services.youtube_uploader import youtube_upload_service
    return youtube_upload_service.resume_batch(batch_id)


@router.post("/youtube/upload/batch/{batch_id}/cancel")
def yt_upload_cancel_batch(batch_id: int):
    """Cancel a batch."""
    from backend.services.youtube_uploader import youtube_upload_service
    return youtube_upload_service.cancel_batch(batch_id)


@router.post("/youtube/upload/batch/{batch_id}/retry")
def yt_upload_retry_batch(batch_id: int):
    """Retry failed items in a batch."""
    from backend.services.youtube_uploader import youtube_upload_service
    return youtube_upload_service.retry_failed(batch_id)


@router.delete("/youtube/upload/batch/{batch_id}")
def yt_upload_delete_batch(batch_id: int):
    """Delete a batch."""
    from backend.services.youtube_uploader import youtube_upload_service
    return youtube_upload_service.delete_batch(batch_id)


@router.get("/youtube/upload/categories")
def yt_upload_categories(region: str = "BR"):
    """Get YouTube video categories."""
    from backend.services.youtube_uploader import youtube_upload_service
    return youtube_upload_service.get_categories(region)


# ─── TikTok Shop Multi-Account Dashboard ──────────────────────


@router.get("/shop-accounts")
def list_shop_accounts(active_only: bool = True, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import list_accounts
    return {"accounts": list_accounts(db, active_only)}


@router.post("/shop-accounts")
def add_shop_account(body: dict, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import add_account
    username = body.get("username", "")
    if not username:
        raise HTTPException(status_code=400, detail="username obrigatorio")
    return add_account(db, username, body.get("category", ""), body.get("notes", ""))


@router.post("/shop-accounts/bulk")
def add_shop_accounts_bulk(body: dict, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import add_accounts_bulk
    usernames = body.get("usernames", "")
    if not usernames:
        raise HTTPException(status_code=400, detail="usernames obrigatorio")
    return add_accounts_bulk(db, usernames, body.get("category", ""))


@router.delete("/shop-accounts/{account_id}")
def delete_shop_account(account_id: int, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import remove_account
    if remove_account(db, account_id):
        return {"status": "deleted"}
    raise HTTPException(status_code=404, detail="Conta nao encontrada")


@router.post("/shop-accounts/{account_id}/refresh")
def refresh_shop_account(account_id: int, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import refresh_account
    return refresh_account(db, account_id)


@router.post("/shop-accounts/refresh-all")
def refresh_all_shop_accounts(db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import refresh_all_accounts
    return refresh_all_accounts(db)


@router.get("/shop-accounts/dashboard")
def shop_accounts_dashboard(db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import get_dashboard_summary
    return get_dashboard_summary(db)


@router.get("/shop-accounts/{account_id}")
def get_shop_account(account_id: int, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import get_account
    account = get_account(db, account_id)
    if not account:
        raise HTTPException(status_code=404, detail="Conta nao encontrada")
    return account


@router.get("/shop-accounts/{account_id}/growth")
def shop_account_growth(account_id: int, days: int = 30, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import get_account_growth
    return get_account_growth(db, account_id, days)


@router.get("/shop-accounts/{account_id}/products")
def shop_account_products(account_id: int, sort_by: str = "sold_count", limit: int = 50, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import get_account_products
    return {"products": get_account_products(db, account_id, sort_by, limit)}


@router.post("/shop-accounts/compare")
def compare_shop_accounts(body: dict, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import compare_accounts
    ids = body.get("account_ids", [])
    if not ids:
        raise HTTPException(status_code=400, detail="account_ids obrigatorio")
    return compare_accounts(db, ids)


@router.get("/shop-accounts/{account_id}/content-analysis")
def shop_account_content_analysis(account_id: int, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import get_account_content_analysis
    result = get_account_content_analysis(db, account_id)
    if "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
    return result


@router.get("/shop-accounts/{account_id}/ai-report")
def shop_account_ai_report(account_id: int, force: bool = False, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import get_account_ai_report
    result = get_account_ai_report(db, account_id, force)
    if isinstance(result, dict) and "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
    return result


@router.get("/shop-accounts/{account_id}/revenue-detail")
def shop_account_revenue_detail(account_id: int, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import get_account_revenue_detail
    result = get_account_revenue_detail(db, account_id)
    if "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
    return result


@router.get("/shop-accounts/{account_id}/viral-videos")
def shop_account_viral_videos(account_id: int, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import get_account_viral_videos
    result = get_account_viral_videos(db, account_id)
    if "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
    return result


@router.get("/shop-accounts/{account_id}/product-trends")
def shop_account_product_trends(account_id: int, days: int = 30, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import get_product_trends
    result = get_product_trends(db, account_id, days)
    if "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
    return result


@router.get("/shop-accounts/{account_id}/commerce-analysis")
def shop_account_commerce_analysis(account_id: int, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import get_account_commerce_analysis
    result = get_account_commerce_analysis(db, account_id)
    if "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
    return result


@router.get("/shop-accounts/{account_id}/transcripts")
def shop_account_transcripts(account_id: int, max_videos: int = 10, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import get_account_transcripts
    result = get_account_transcripts(db, account_id, max_videos)
    if "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
    return result


@router.get("/shop-accounts/{account_id}/product-video-map")
def shop_account_product_video_map(account_id: int, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import get_product_video_map
    result = get_product_video_map(db, account_id)
    if "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
    return result


@router.get("/shop-accounts/{account_id}/insights")
def shop_account_insights(account_id: int, force: bool = False, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import get_account_insights
    result = get_account_insights(db, account_id, force)
    if isinstance(result, dict) and "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
    return result


@router.get("/shop-accounts/{account_id}/video-ideas")
def shop_account_video_ideas(account_id: int, force: bool = False, db: Session = Depends(get_db)):
    from backend.services.tiktok_shop_monitor import get_account_video_ideas
    result = get_account_video_ideas(db, account_id, force)
    if isinstance(result, dict) and "error" in result:
        raise HTTPException(status_code=404, detail=result["error"])
    return result


# ─── TikTok Profile Viral ────────────────────────────────────────────────────

@router.post("/tiktok/profile-videos")
def tiktok_profile_videos(data: dict):
    """Busca os 50 videos mais virais de um perfil TikTok, ordenados por views."""
    username = (data.get("username") or "").strip().lstrip("@")
    if not username:
        raise HTTPException(status_code=400, detail="Username obrigatorio")

    from backend.scrapers.tiktok import TikTokScraper
    from backend.core.config import settings

    scraper = TikTokScraper()
    videos = scraper.get_user_videos(username, max_results=50)

    # Fallback para Apify se yt-dlp não retornar nada
    if not videos:
        apify_token = getattr(settings, "APIFY_API_TOKEN", None)
        if apify_token:
            from backend.scrapers.apify_scraper import ApifyScraper
            try:
                apify = ApifyScraper(apify_token)
                videos = apify.tiktok_user_videos(username, max_results=50)
            except Exception as e:
                print(f"[TikTok Profile] Apify fallback error: {e}")

    if not videos:
        return {"username": username, "total": 0, "videos": [], "error": "Nenhum video encontrado. Verifique o nome do perfil."}

    # Serializar datas para JSON e ordenar por views
    for v in videos:
        if hasattr(v.get("published_at"), "isoformat"):
            v["published_at"] = v["published_at"].isoformat()

    videos.sort(key=lambda v: v.get("views", 0), reverse=True)
    videos = videos[:50]

    return {"username": username, "total": len(videos), "videos": videos}
