package com.foxx.androidcast.remoteaccess;

import android.content.Context;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Locale;

/** Human-readable remote-access failure text for status store and diagnostics. */
public final class RemoteAccessFailureReason {
    private RemoteAccessFailureReason() {}

    public static String fromPollException(Context context, Exception e) {
        String host = heartbeatHost(context);
        if (e instanceof SocketTimeoutException) {
            return "heartbeat HTTP timeout — device→" + host + " (15s connect/read)";
        }
        if (e instanceof UnknownHostException) {
            return "heartbeat DNS failed — " + host + " (" + safeMsg(e) + ")";
        }
        if (e instanceof ConnectException) {
            return "heartbeat TCP connect failed — " + host + " (" + safeMsg(e) + ")";
        }
        if (e instanceof IllegalStateException) {
            String msg = safeMsg(e);
            if ("no_backend_url".equals(msg)) {
                return "no crash/OTA URL configured — cannot resolve heartbeat.php";
            }
            if (msg.startsWith("http_")) {
                return "heartbeat HTTP " + msg.substring(5) + " — " + host;
            }
            return "heartbeat error — " + msg;
        }
        return e.getClass().getSimpleName() + ": " + safeMsg(e);
    }

    public static boolean isControlPlaneMethod(String method) {
        if (method == null || method.isEmpty()) {
            return false;
        }
        return method.contains("runPoll")
                || method.contains("RemoteAccessHeartbeatClient")
                || method.contains("postRa");
    }

    public static boolean isTunnelMethod(String method) {
        if (method == null || method.isEmpty()) {
            return false;
        }
        return method.contains("VpnServiceClient")
                || method.contains("ReverseSshTunnelBridge")
                || method.contains("handleConnect");
    }

    public static String heartbeatHost(Context context) {
        String url = RemoteAccessHeartbeatClient.resolveHeartbeatUrl(context);
        if (url.isEmpty()) {
            return "(no URL configured)";
        }
        try {
            String host = new java.net.URL(url).getHost();
            if (host != null && !host.isEmpty()) {
                return host;
            }
        } catch (Exception ignored) {
        }
        return url.length() > 48 ? url.substring(0, 48) + "…" : url;
    }

    public static String heartbeatUrlForDiagnostics(Context context) {
        String url = RemoteAccessHeartbeatClient.resolveHeartbeatUrl(context);
        if (url.isEmpty()) {
            return "(unset — set crash upload or OTA URL in dev settings)";
        }
        return url;
    }

    private static String safeMsg(Exception e) {
        String m = e.getMessage();
        if (m == null || m.isEmpty()) {
            return e.getClass().getSimpleName();
        }
        if ("timeout".equalsIgnoreCase(m)) {
            return "timeout";
        }
        return m;
    }

    /** Legacy bare "timeout" from old builds — expand for diagnostics display. */
    public static String expandForDisplay(Context context, String method, String failReason) {
        if (failReason == null || failReason.isEmpty()) {
            return failReason;
        }
        if (isControlPlaneMethod(method)
                && ("timeout".equalsIgnoreCase(failReason)
                || failReason.toLowerCase(Locale.US).contains("timed out"))) {
            return fromPollException(context, new SocketTimeoutException(failReason));
        }
        if (failReason.equals("RSSH connect failed or timed out")) {
            return failReason + " — device→bastion (JSch 30s + 35s wait; check ra.apps.f0xx.org:443)";
        }
        return failReason;
    }
}
