#!/usr/bin/env python3
"""JV 逆トンネル（Linux 127.0.0.1:PORT）の TCP 到達性だけ確認する。"""

from __future__ import annotations

import os
import socket
import sys
import time


def main() -> int:
    host = os.environ.get("JV_TUNNEL_HOST", "127.0.0.1")
    port = int(os.environ.get("JV_TUNNEL_PORT", os.environ.get("SSH_REMOTE_PORT", "18765")))
    timeout = float(os.environ.get("JV_TUNNEL_TIMEOUT_SEC", "5"))

    started = time.perf_counter()
    try:
        with socket.create_connection((host, port), timeout=timeout):
            pass
    except OSError as exc:
        print(f"NG jv_tcp host={host} port={port} error={exc}", file=sys.stderr)
        return 1

    ms = int((time.perf_counter() - started) * 1000)
    print(f"OK jv_tcp host={host} port={port} connect_ms={ms}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
