from fastapi import APIRouter, Request, Depends
from fastapi.responses import RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from pathlib import Path

from backend.database.connection import get_db
from backend.services import video_service
from backend.services.viral_detector import ViralDetector

router = APIRouter()
templates = Jinja2Templates(directory=Path(__file__).resolve().parent.parent.parent / "frontend" / "templates")
detector = ViralDetector()


@router.get("/")
def dashboard(request: Request, db: Session = Depends(get_db)):
    stats = video_service.get_stats(db)
    videos, _ = video_service.get_videos(db, platform="tiktok", sort_by="viral_score", limit=12)
    return templates.TemplateResponse(
        "dashboard.html",
        {"request": request, "stats": stats, "videos": videos, "detector": detector},
    )


@router.get("/feed")
def feed_page(request: Request):
    return RedirectResponse(url="/viral-scanner", status_code=302)


@router.get("/discover")
def discover(request: Request):
    return RedirectResponse(url="/viral-scanner", status_code=302)


@router.get("/scrape")
def scrape_page(request: Request):
    return templates.TemplateResponse("scrape.html", {"request": request})


@router.get("/downloads-page")
def downloads_page(request: Request):
    return templates.TemplateResponse("downloads.html", {"request": request})


@router.get("/collections-page")
def collections_page(request: Request, db: Session = Depends(get_db)):
    from backend.models.collection import Collection
    collections = db.query(Collection).all()
    return templates.TemplateResponse("collections.html", {"request": request, "collections": collections})


@router.get("/trends")
def trends_page(request: Request, platform: str = "", db: Session = Depends(get_db)):
    from backend.services.trend_analyzer import TrendAnalyzer
    analyzer = TrendAnalyzer()
    hashtags = analyzer.analyze_hashtags(db, platform=platform, days=30, limit=30)
    patterns = analyzer.analyze_content_patterns(db, platform=platform, days=30)
    return templates.TemplateResponse(
        "trends.html",
        {"request": request, "hashtags": hashtags, "patterns": patterns, "platform": platform},
    )


@router.get("/intelligence")
def intelligence_page(request: Request):
    return templates.TemplateResponse("intelligence.html", {"request": request})


@router.get("/ideas")
def ideas_page(request: Request):
    return templates.TemplateResponse("ideas.html", {"request": request})


@router.get("/sounds")
def sounds_page(request: Request):
    return templates.TemplateResponse("sounds.html", {"request": request})


@router.get("/opportunities")
def opportunities_page(request: Request):
    return templates.TemplateResponse("opportunities.html", {"request": request})


@router.get("/competitors-spy")
def competitors_spy_page(request: Request):
    return templates.TemplateResponse("competitors_spy.html", {"request": request})


@router.get("/script-genius")
def script_genius_page(request: Request):
    return templates.TemplateResponse("script_genius.html", {"request": request})


@router.get("/academy")
def academy_page(request: Request):
    return templates.TemplateResponse("academy.html", {"request": request})


@router.get("/creators-page")
def creators_page(
    request: Request, platform: str = "", tracked_only: bool = False,
    search: str = "", db: Session = Depends(get_db),
):
    from backend.services.creator_service import CreatorService
    svc = CreatorService()
    creators, total = svc.get_creators(db, platform=platform, tracked_only=tracked_only, search=search, limit=50)
    return templates.TemplateResponse(
        "creators.html",
        {"request": request, "creators": creators, "total": total,
         "platform": platform, "tracked_only": tracked_only, "search": search},
    )


@router.get("/scheduler-page")
def scheduler_page(request: Request):
    return templates.TemplateResponse("scheduler.html", {"request": request})


@router.get("/alerts-page")
def alerts_page(request: Request):
    return templates.TemplateResponse("alerts.html", {"request": request})


@router.get("/hashtags-page")
def hashtags_page(request: Request):
    return templates.TemplateResponse("hashtags.html", {"request": request})


@router.get("/shop")
def shop_page(request: Request):
    return templates.TemplateResponse("shop.html", {"request": request})


@router.get("/viral-scanner")
def viral_scanner_page(request: Request):
    return templates.TemplateResponse("viral_scanner.html", {"request": request})


@router.get("/trends-discovery")
def trends_discovery_page(request: Request):
    return templates.TemplateResponse("trends_discovery.html", {"request": request})


@router.get("/scanner-history")
def scanner_history_page(request: Request):
    return templates.TemplateResponse("scanner_history.html", {"request": request})


@router.get("/tutorial")
def tutorial_page(request: Request):
    return templates.TemplateResponse("tutorial.html", {"request": request})


@router.get("/settings-page")
def settings_page(request: Request):
    return templates.TemplateResponse("settings.html", {"request": request})


@router.get("/videos-campeoes")
def videos_campeoes_page(request: Request):
    return templates.TemplateResponse("videos_campeoes.html", {"request": request})


@router.get("/mega-plano")
def mega_plano_page(request: Request):
    import markdown
    md_path = Path(__file__).resolve().parent.parent.parent / "docs" / "MEGA-PLANO-VIRAL-SOCIAL-PRO.md"
    md_content = md_path.read_text(encoding="utf-8")
    html_content = markdown.markdown(md_content, extensions=["tables", "toc", "fenced_code", "nl2br"])
    return templates.TemplateResponse(
        "mega_plano.html",
        {"request": request, "html_content": html_content},
    )


@router.get("/ciencia-viralizacao")
def ciencia_viralizacao_page(request: Request):
    import markdown
    md_path = Path(__file__).resolve().parent.parent.parent / "docs" / "CURSO-CIENCIA-DA-VIRALIZACAO-2026.md"
    md_content = md_path.read_text(encoding="utf-8")
    html_content = markdown.markdown(md_content, extensions=["tables", "toc", "fenced_code", "nl2br"])
    return templates.TemplateResponse(
        "ciencia_viralizacao.html",
        {"request": request, "html_content": html_content},
    )


@router.get("/roadmap-dev")
def roadmap_dev_page(request: Request):
    import markdown
    md_path = Path(__file__).resolve().parent.parent.parent / "docs" / "ROADMAP-MICROSAAS-2026.md"
    md_content = md_path.read_text(encoding="utf-8")
    html_content = markdown.markdown(md_content, extensions=["tables", "toc", "fenced_code", "nl2br"])
    return templates.TemplateResponse(
        "roadmap_dev.html",
        {"request": request, "html_content": html_content},
    )


@router.get("/transcribe")
def transcribe_page(request: Request):
    return templates.TemplateResponse("transcribe.html", {"request": request})


@router.get("/calendar-page")
def calendar_page(request: Request, platform: str = "", db: Session = Depends(get_db)):
    from backend.services.content_calendar import ContentCalendar
    cal = ContentCalendar()
    best_times = cal.get_best_times(db, platform)
    plan = cal.generate_weekly_plan(db, platform)
    return templates.TemplateResponse(
        "calendar.html",
        {"request": request, "best_times": best_times, "plan": plan, "platform": platform},
    )


@router.get("/engage")
def engage_page(request: Request):
    return templates.TemplateResponse("engage.html", {"request": request})


@router.get("/dark-factory")
def dark_factory_page(request: Request):
    return templates.TemplateResponse("dark_factory.html", {"request": request})


@router.get("/automate")
def automate_page(request: Request):
    return templates.TemplateResponse("automate.html", {"request": request})


@router.get("/crm")
def crm_page(request: Request):
    return templates.TemplateResponse("crm.html", {"request": request})


@router.get("/agency")
def agency_page(request: Request):
    return templates.TemplateResponse("agency.html", {"request": request})


@router.get("/youtube-upload")
def youtube_upload_page(request: Request):
    return templates.TemplateResponse("youtube_upload.html", {"request": request})


@router.get("/shop-dashboard")
def shop_dashboard_page(request: Request):
    return templates.TemplateResponse("tiktok_shop_dashboard.html", {"request": request})


@router.get("/tiktok-profile")
def tiktok_profile_page(request: Request):
    return templates.TemplateResponse("tiktok_profile.html", {"request": request})
