"""Request validation for the backtest alert-config API. Separate from the router so the rules -- which fields are required, how a legacy condition normalizes into the tree, and which detector types the engine supports -- can be read and tested without an HTTP client. HTTP 400s are raised here because this is the boundary for those rules; the router only calls these functions. """ from typing import Any, cast from fastapi import HTTPException from core.detectors.alert_elements import ( condition_from_fields, detector_types_for, lint_condition, resolve_alert_elements, resolve_condition, ) from core.shared.deps import data_manager from modules.backtest.models import SUPPORTED_DETECTORS, AlertConfigRequest, AlertPreviewRequest def normalize_request_condition(req: AlertConfigRequest | AlertPreviewRequest) -> dict[str, Any] | None: """The effective condition of a request, from whichever field carries it. ``condition`` wins when present; otherwise the legacy fields are normalized into an equivalent tree so old clients and old saved rows go down the same code path as new ones. Returns None when nothing was sent. """ return condition_from_fields( cast("dict[str, Any] | None", getattr(req, "condition", None)), cast("list[dict[str, Any]] | None", getattr(req, "alert_elements", None)), cast("str | None", getattr(req, "detector_expression", None)), ) def validate_alert_config_request(req: AlertConfigRequest) -> tuple[list[str], dict[str, Any] | None]: """Validate the request and return ``(effective detector_types, condition)``. A tree is resolved (which is where an unknown key or an out-of-range param raises) and its lint is checked: structural errors are rejected, warnings are not -- a very tight AND is allowed to be the user's deliberate call. """ if not req.name.strip(): raise HTTPException(status_code=400, detail="Name is required") condition = normalize_request_condition(req) if condition is None and not req.detector_types: raise HTTPException(status_code=400, detail="An alert condition is required") if condition is not None: try: groups = resolve_condition(condition) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc detector_types = detector_types_for(groups) for issue in lint_condition(condition): if issue.severity == "error": raise HTTPException(status_code=400, detail=issue.message) else: detector_types = req.detector_types unsupported = set(detector_types) - SUPPORTED_DETECTORS if unsupported: raise HTTPException(status_code=400, detail=f"Unsupported detector_type(s): {sorted(unsupported)}") if req.filter_expression: try: data_manager.expr_parser.validate_filter_expr(req.filter_expression) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc if req.detector_expression and condition is None: try: parsed = data_manager.expr_parser.parse(req.detector_expression) data_manager.expr_parser.compile_safe(parsed.remaining_filter) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc if req.alert_elements and condition is None: try: resolve_alert_elements(req.alert_elements) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc return detector_types, condition