from __future__ import annotations

import json
from typing import Any
from urllib.error import URLError
from urllib.request import urlopen

from flask import jsonify

from .. import settings


def register(app) -> None:
    """Expose the Monero node health endpoint through Flask."""

    @app.route("/api/monero/get_info")
    def monero_get_info() -> Any:
        """Proxy `get_info` from the Monero daemon with a predictable response."""

        try:
            with urlopen(settings.MONERO_GET_INFO_URL, timeout=2) as resp:
                payload = json.loads(resp.read().decode("utf-8"))
            return jsonify(payload)
        except (URLError, TimeoutError, ValueError) as exc:
            return jsonify({"error": str(exc), "url": settings.MONERO_GET_INFO_URL}), 503
