#!/usr/bin/env python3
from __future__ import annotations

import os
import socket
from pathlib import Path
from urllib.parse import urlparse

from dotenv import load_dotenv

ROOT = Path(__file__).resolve().parents[1]
load_dotenv(ROOT / ".env", override=False)

NAMES = [
    "TIM_COMPLETE_INVOICES_URL", "TIM_URL_CONSULTA_VAS", "TIM_VAS_HISTORY_URL",
    "TIM_URL_BLOQUEIO_VAS", "TIM_CANCELAMENTO_URL", "TIM_CONTRATO_URL",
    "TIM_CUSTOMER_CONTESTATION_URL", "TIM_PROTOCOL_URL",
    "TIM_SERVICE_REQUEST_STATUS_URL", "TIM_TRACKING_ACTIVITIES_URL",
    "TIM_SMS_URL", "TIM_URL_INVOICE_RECOVER", "TIM_PROFILE_FULL_URL",
    "TIM_DIVERGENCIA_URL", "LANGFUSE_HOST", "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
]


def probe(url: str) -> str:
    if not url:
        return "NOT_CONFIGURED"
    parsed = urlparse(url if "://" in url else "http://" + url)
    host = parsed.hostname
    port = parsed.port or (443 if parsed.scheme == "https" else 80)
    if not host:
        return "INVALID_URL"
    try:
        socket.getaddrinfo(host, port)
    except OSError as exc:
        return f"DNS_FAIL: {exc}"
    try:
        with socket.create_connection((host, port), timeout=3):
            return "TCP_OK"
    except OSError as exc:
        return f"TCP_FAIL: {exc}"


print(f"TIM_GATEWAY_MODE={os.getenv('TIM_GATEWAY_MODE')} TIM_USE_MOCK_GATEWAY={os.getenv('TIM_USE_MOCK_GATEWAY')}")
for name in NAMES:
    value = os.getenv(name, "")
    print(f"{name:38} {probe(value)}  {value}")
