# file: integrations/flask.py
# pyright: reportGeneralTypeIssues=false
# pyright: reportAttributeAccessIssue=false

import json
import random
import time
from datetime import datetime, timezone

from flask import Flask, g, request  # type: ignore

from ..apiTelemetry import (
    MAX_BODY_CAPTURE,
    TelemetryClient,
    capture_exception,
    extract_trace_id,
    get_trace_id,
    sanitize_payload,
    spans_var,
    start_trace,
    trace_id_var,
)


def setup(app: Flask, client: TelemetryClient):
    """
    Sets up telemetry hooks for a Flask application.

    This function registers `before_request`, `after_request`, and `teardown_request`
    handlers to automatically instrument incoming HTTP requests.

    Args:
        app (Flask): The Flask application instance.
        client (TelemetryClient): The active telemetry client instance.
    """

    @app.before_request
    def before_request_hook():
        """
        Hook executed before each request.

        Responsibilities:
        1. Sampling Decision: Decides if the current request should be traced.
        2. Trace Initialization: If sampled, it starts a new trace, sets up
           the context for spans, and initializes timers in `g`.
        """
        method = request.method.upper()

        # Priority sample rate for critical methods (POST, PUT, PATCH, DELETE);
        # general rate for everything else.
        if method in ["POST", "PUT", "PATCH", "DELETE"]:
            sample_rate = client.config.priority_sample_rate
        else:
            sample_rate = client.config.general_sample_rate

        is_sampled = random.random() < sample_rate
        g.telemetry_is_sampled = is_sampled

        if not is_sampled:
            return

        # Adopt an incoming trace id when present so distributed traces stay
        # continuous across services; otherwise start a brand-new trace.
        incoming_trace_id = extract_trace_id(request.headers)
        if incoming_trace_id is not None:
            trace_id_var.set(incoming_trace_id)
        else:
            start_trace()
        g.telemetry_start_time = time.perf_counter()
        spans_var.set([])

    @app.after_request
    def after_request_hook(response):
        """
        Hook executed after each request, before the response is sent.

        Builds and submits the trace payload for sampled requests. Request and
        response bodies are only read when capture is explicitly enabled
        (TELEMETRY_CAPTURE_BODIES); by default they stay untouched, which also
        preserves streaming responses and large payloads.
        """
        if g.get("telemetry_is_sampled", False):
            duration_ms = (time.perf_counter() - g.telemetry_start_time) * 1000
            collected_spans = spans_var.get() or []

            req_body_str = None
            res_body_str = None

            if client.config.capture_bodies:
                # --- Request body (methods that carry one) ---
                if request.method in ["POST", "PUT", "PATCH", "DELETE"]:
                    try:
                        if request.is_json and hasattr(request, "_cached_json"):
                            req_body_str = json.dumps(request.get_json())
                        else:
                            req_body_str = request.get_data(as_text=True)[
                                :MAX_BODY_CAPTURE
                            ]
                    except Exception:
                        req_body_str = "[Request body could not be decoded]"

                # --- Response body ---
                if response.is_sequence and not response.is_streamed:
                    try:
                        if response.mimetype == "application/json":
                            res_body_str = json.dumps(response.json)
                        else:
                            res_body_str = response.get_data(as_text=True)[
                                :MAX_BODY_CAPTURE
                            ]
                    except Exception:
                        res_body_str = "[Could not decode response body]"
                else:
                    res_body_str = "[Streaming Response - Body Not Captured]"

            # Errors: an unhandled exception (captured in teardown) does not reach
            # after_request, so a 5xx status is the reliable signal here.
            has_error = response.status_code >= 500

            end_dt = datetime.now(timezone.utc)
            start_dt = datetime.fromtimestamp(
                end_dt.timestamp() - (duration_ms / 1000), tz=timezone.utc
            )

            # Never let a malformed duration crash the request path.
            try:
                duration_ms_int = int(duration_ms)
            except (TypeError, ValueError):
                duration_ms_int = 0

            trace_payload = {
                "trace": {
                    "id": get_trace_id(),
                    "http_method": request.method,
                    "http_path": request.path,
                    "http_host": request.host,
                    "http_status_code": response.status_code,
                    "request_body": sanitize_payload(req_body_str),
                    "response_body": sanitize_payload(res_body_str),
                    "duration_ms": duration_ms_int,
                    "has_error": has_error,
                    "start_timestamp": start_dt.isoformat(),
                    "end_timestamp": end_dt.isoformat(),
                },
                "logs_and_spans": collected_spans,
            }
            client.capture_trace(trace_payload)

        return response

    @app.teardown_request
    def teardown_request_hook(exception):
        """
        Hook executed at the very end of a request regardless of success.

        Exceptions are ALWAYS reported — even for requests that were not
        sampled — because errors are the most valuable telemetry data.
        Context cleanup runs only for sampled requests (the only ones that
        initialized the context), and also clears the trace id so a reused
        worker thread cannot label later requests with a stale trace.
        """
        if exception:
            error_context = {
                "method": request.method,
                "path": request.path,
                "ip": request.remote_addr,
            }
            capture_exception(exception, error_context)

        if g.get("telemetry_is_sampled", False):
            if spans_var.get() is not None:
                spans_var.set(None)
            trace_id_var.set(None)
