from flask import got_request_exception, request
from ..exceptions import capture_exception
from ..payload import base_payload
from ..client import send_sync


def init_flask(app):
    """
    Flask integration for AIOps SDK.

    Captures:
    1. Unhandled Flask exceptions (got_request_exception)
    2. Handled HTTP error responses (4xx / 5xx)
       even when exceptions are swallowed by user code
    """

    # --------------------------------------------------
    # 1️⃣ Capture REAL Flask exceptions (raised errors)
    # --------------------------------------------------
    @got_request_exception.connect_via(app)
    def _handle_exception(sender, exception, **extra):
        capture_exception(exception)

    # --------------------------------------------------
    # 2️⃣ Capture HTTP error responses (status-based)
    # --------------------------------------------------
    @app.after_request
    def _after_request(response):
        try:
            status_code = response.status_code

            # Capture ALL relevant error responses
            if status_code in (401, 403, 404, 500, 503):
                payload = base_payload()
                payload.update({
                    "error_type": "HTTPError",
                    "message": (
                        f"{request.method} {request.path} "
                        f"returned HTTP {status_code}"
                    ),
                    "stack_trace": "",
                    "source": "http",
                    "status_code": status_code
                })

                # Send synchronously but safely
                send_sync("/v1/sdk/exception", payload)

        except Exception:
            # NEVER break the client application
            pass

        return response
