from __future__ import annotations

from fastapi import APIRouter, BackgroundTasks, HTTPException
from pydantic import BaseModel, HttpUrl

from backend.app.core.scheduler import get_scheduler_status, trigger_next_run
from backend.app.scraper.runner import scrape_all, scrape_preview, scrape_product

router = APIRouter(prefix="/scrape", tags=["scrape"])


class PreviewRequest(BaseModel):
    url: HttpUrl


@router.post("/preview")
def preview_scrape(payload: PreviewRequest):
    """
    Scrape une URL Amazon sans enregistrer en base.
    Retourne les données pour prévisualisation avant ajout.
    """
    result = scrape_preview(str(payload.url))
    if not result["success"] and result["error"]:
        raise HTTPException(status_code=422, detail=result["error"])
    return result


@router.post("/product/{product_id}")
def trigger_single(product_id: int, background_tasks: BackgroundTasks):
    # on délègue le vrai travail à un background task rapide
    background_tasks.add_task(scrape_product, product_id)
    return {"statut": "planifie", "cible": product_id}


@router.post("/all")
def trigger_all(background_tasks: BackgroundTasks):
    background_tasks.add_task(scrape_all)
    return {"statut": "planifie_tout"}


@router.get("/scheduler/status")
def scheduler_status():
    """Retourne l'état actuel du scheduler de scraping automatique."""
    return get_scheduler_status()


@router.post("/scheduler/trigger")
def scheduler_trigger():
    """Force le prochain scrape planifié à s'exécuter maintenant."""
    return trigger_next_run()
