package com.foxx.androidcast.remoteaccess;

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

import com.foxx.androidcast.BuildConfig;
import com.foxx.androidcast.crash.CrashSettingsStore;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/** POST heartbeat type:ra to BE (shared by RemoteAccessService). */
public final class RemoteAccessHeartbeatClient {
    private static final String TAG = "RemoteAccessHB";
    private static final int HTTP_TIMEOUT_MS = 15_000;

    private RemoteAccessHeartbeatClient() {}

    public static String resolveHeartbeatUrl(Context context) {
        String crash = CrashSettingsStore.load(context).uploadUrl;
        if (crash != null && !crash.trim().isEmpty()) {
            return toHeartbeatUrl(crash.trim());
        }
        String ota = com.foxx.androidcast.AppPreferences.getOtaChannelUrl(context);
        if (ota != null && !ota.trim().isEmpty()) {
            return toHeartbeatUrl(ota.trim());
        }
        if (BuildConfig.OTA_CHANNEL_URL_DEFAULT != null && !BuildConfig.OTA_CHANNEL_URL_DEFAULT.trim().isEmpty()) {
            return toHeartbeatUrl(BuildConfig.OTA_CHANNEL_URL_DEFAULT.trim());
        }
        return "";
    }

    public static String toHeartbeatUrl(String backend) {
        if (backend.contains("/api/upload.php")) {
            return backend.replace("/api/upload.php", "/api/heartbeat.php");
        }
        if (backend.endsWith("/")) {
            return backend + "api/heartbeat.php";
        }
        return backend + "/api/heartbeat.php";
    }

    /** @return parsed heartbeat object from response, or null on failure */
    public static JSONObject postRa(Context context, JSONObject heartbeatBody) throws Exception {
        String url = resolveHeartbeatUrl(context);
        if (url.isEmpty()) {
            throw new IllegalStateException("no_backend_url");
        }
        JSONObject req = new JSONObject();
        req.put("heartbeat", heartbeatBody);
        String text = httpPostJson(url, req.toString());
        JSONObject resp = new JSONObject(text);
        return resp.optJSONObject("heartbeat");
    }

    private static String httpPostJson(String url, String body) throws Exception {
        HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
        c.setRequestMethod("POST");
        c.setConnectTimeout(HTTP_TIMEOUT_MS);
        c.setReadTimeout(HTTP_TIMEOUT_MS);
        c.setDoOutput(true);
        c.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
        try (OutputStream os = c.getOutputStream()) {
            os.write(bytes);
        }
        int code = c.getResponseCode();
        String resp = readBody(c);
        c.disconnect();
        if (code < 200 || code >= 300) {
            Log.w(TAG, "heartbeat HTTP " + code + " body=" + resp);
            throw new IllegalStateException("http_" + code);
        }
        return resp;
    }

    private static String readBody(HttpURLConnection c) {
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(c.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
                if (sb.length() > 8192) {
                    break;
                }
            }
            return sb.toString();
        } catch (Exception e) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(c.getErrorStream(), StandardCharsets.UTF_8))) {
                String line = br.readLine();
                return line != null ? line : "";
            } catch (Exception ignored) {
                return "";
            }
        }
    }
}
