package com.foxx.androidcast.remoteaccess;

import android.content.Context;
import android.util.Log;

import org.json.JSONObject;

import com.foxx.androidcast.AppPreferences;

/** Build wireguard-quick style config from BE connect credentials + dev VPN routing prefs. */
public final class WireGuardConfigBuilder {
    private static final String TAG = "WireGuardCfg";

    private WireGuardConfigBuilder() {}

    public static String fromConnectCredentials(Context context, JSONObject credentials) {
        if (context == null) {
            return fromConnectCredentials(
                    credentials,
                    RemoteAccessVpnRouting.RouteScope.HUB_ONLY,
                    RemoteAccessVpnRouting.AppScope.ALL_APPS,
                    null);
        }
        return fromConnectCredentials(
                credentials,
                AppPreferences.getDevRemoteAccessVpnRouteScope(context),
                AppPreferences.getDevRemoteAccessVpnAppScope(context),
                context.getPackageName());
    }

    public static String fromConnectCredentials(
            JSONObject credentials,
            RemoteAccessVpnRouting.RouteScope routeScope,
            RemoteAccessVpnRouting.AppScope appScope,
            String packageName) {
        if (credentials == null) {
            return "";
        }
        String priv = credentials.optString("interface_private_key", "");
        String addr = credentials.optString("interface_address", "172.200.2.10/32");
        String peerPub = credentials.optString("peer_public_key", "");
        String endpoint = credentials.optString("peer_endpoint", "");
        String beAllowed = credentials.optString("peer_allowed_ips", "");
        if (priv.isEmpty() || peerPub.isEmpty()) {
            Log.w(TAG, "missing wg keys in credentials");
            return "";
        }
        if (routeScope == null) {
            routeScope = RemoteAccessVpnRouting.RouteScope.HUB_ONLY;
        }
        if (appScope == null) {
            appScope = RemoteAccessVpnRouting.AppScope.ALL_APPS;
        }
        String allowed = RemoteAccessVpnRouting.resolveAllowedIps(routeScope, beAllowed);

        StringBuilder sb = new StringBuilder();
        sb.append("[Interface]\n");
        sb.append("PrivateKey = ").append(priv).append('\n');
        sb.append("Address = ").append(addr).append('\n');
        RemoteAccessVpnRouting.appendInterfaceExtras(sb, appScope, packageName);
        sb.append('\n');
        sb.append("[Peer]\n");
        sb.append("PublicKey = ").append(peerPub).append('\n');
        if (!endpoint.isEmpty()) {
            sb.append("Endpoint = ").append(endpoint).append('\n');
        }
        sb.append("AllowedIPs = ").append(allowed).append('\n');
        sb.append("PersistentKeepalive = 25\n");
        return sb.toString();
    }
}
