from fastapi import APIRouter, HTTPException

from core.schemas import PredictRequest, PredictResponse
from integrations.codeigniter_client import CodeIgniterClient
from ml.feature_engineering import build_features
from ml.random_forest_service import RandomForestRiskService

router = APIRouter(tags=["prediction"])
predictor = RandomForestRiskService()
ci = CodeIgniterClient()


@router.post("/predict", response_model=PredictResponse)
def predict(req: PredictRequest) -> PredictResponse:
    payload = req.model_dump()
    features = build_features(payload)
    threshold = 0.60
    try:
        prob, blocked, top = predictor.predict(features, threshold=threshold)
    except FileNotFoundError:
        raise HTTPException(status_code=503, detail="Random Forest model not trained. Run scripts/train_models.py")

    risk_class = "high" if prob >= 0.75 else ("medium" if prob >= 0.5 else "low")
    if blocked:
        try:
            ci.post_alert(
                event_id=req.event_id,
                severity="critical",
                message="High theft risk detected by AI",
                evidence={"probability": prob, "top_contributors": top},
            )
            ci.block_workflow(req.event_id, "AI theft risk threshold exceeded", prob)
        except Exception:
            # Keep prediction endpoint non-fatal when callback is unavailable.
            pass

    return PredictResponse(
        event_id=req.event_id,
        theft_risk_probability=prob,
        risk_class=risk_class,
        threshold=threshold,
        top_contributors=top,
        blocked=blocked,
    )
