package dev.supastaq.telemetry;

import android.app.ActivityManager;
import android.app.Application;
import android.app.ApplicationExitInfo;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.util.AtomicFile;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.net.ssl.HttpsURLConnection;

/**
 * Android 11+. Call at main-process startup, when consent changes, or to retry after reconnecting.
 * Up to 128 pending reports from the last 30 UTC days are kept outside Android backups.
 * Withdrawing consent or switching tenants clears the queue.
 */
public final class SupastaqCrashReports {
    private static final int MAGIC = 0x53514331;
    private static final String LABEL = "[A-Za-z0-9_.-]{1,64}";
    private static final int MAX_PENDING = 128;
    private static final ExecutorService worker = Executors.newSingleThreadExecutor();
    private static String armedEpoch;

    private SupastaqCrashReports() {}

    public static synchronized void configure(Context context, String tenantUrl, String anonKey,
                                              String release, boolean consent) {
        if (Build.VERSION.SDK_INT < 30 || !context.getPackageName().equals(Application.getProcessName())) return;
        SharedPreferences prefs = context.getSharedPreferences("supastaq_crash_reports", Context.MODE_PRIVATE);
        AtomicFile queue = new AtomicFile(new File(context.getNoBackupFilesDir(), "supastaq-pending-crashes.json"));
        ActivityManager manager = context.getSystemService(ActivityManager.class);
        if (!consent) {
            // A new consent period cannot recover reports from an earlier one.
            prefs.edit().clear().commit();
            queue.delete();
            armedEpoch = null;
            return;
        }
        URI origin = URI.create(tenantUrl);
        if (!"https".equals(origin.getScheme()) || origin.getHost() == null || origin.getUserInfo() != null
                || origin.getQuery() != null || origin.getFragment() != null
                || !("".equals(origin.getPath()) || "/".equals(origin.getPath()))
                || anonKey == null || anonKey.isEmpty() || release == null || !release.matches(LABEL)) {
            throw new IllegalArgumentException("Expected tenant HTTPS origin, public anon key and fixed release label");
        }
        String endpoint = origin.resolve("/rest/v1/rpc/supastaq_android_crash").toString();
        String epoch = prefs.getString("epoch", null);
        if (epoch == null || !endpoint.equals(prefs.getString("endpoint", null))) {
            epoch = UUID.randomUUID().toString();
            if (!prefs.edit().clear().putString("epoch", epoch).putString("endpoint", endpoint).commit()) return;
            queue.delete();
        }
        if (!epoch.equals(armedEpoch)) {
            UUID generation = UUID.fromString(epoch);
            UUID eventId = UUID.randomUUID();
            byte[] label = release.getBytes(StandardCharsets.US_ASCII);
            ByteBuffer marker = ByteBuffer.allocate(36 + label.length).putInt(MAGIC);
            marker.putLong(generation.getMostSignificantBits()).putLong(generation.getLeastSignificantBits());
            marker.putLong(eventId.getMostSignificantBits()).putLong(eventId.getLeastSignificantBits()).put(label);
            try {
                manager.setProcessStateSummary(marker.array());
                armedEpoch = epoch;
            } catch (RuntimeException unavailable) {
                // Android can temporarily throttle updates to the exit summary.
            }
        }
        String currentEpoch = epoch;
        String packageName = context.getPackageName();
        worker.execute(() -> {
            try {
                collect(manager, packageName, prefs, queue, currentEpoch, endpoint, anonKey);
            } catch (IOException | JSONException | RuntimeException unavailable) {
                // A later configure call retries retained reports with their original IDs.
            }
        });
    }

    private static void collect(ActivityManager manager, String packageName, SharedPreferences prefs, AtomicFile queue,
                                String epoch, String endpoint, String anonKey) throws IOException, JSONException {
        UUID generation = UUID.fromString(epoch);
        LocalDate today = LocalDate.now(ZoneOffset.UTC);
        Map<String, JSONObject> pending;
        synchronized (SupastaqCrashReports.class) {
            if (!epoch.equals(prefs.getString("epoch", null))) return;
            pending = readPending(queue, epoch, today);
        }
        Set<String> previous = new HashSet<>(prefs.getStringSet("delivered", java.util.Collections.emptySet()));
        Set<String> delivered = new HashSet<>();
        List<ApplicationExitInfo> history;
        try {
            history = manager.getHistoricalProcessExitReasons(packageName, 0, 0);
        } catch (RuntimeException unavailable) {
            history = java.util.Collections.emptyList();
            delivered.addAll(previous);
        }
        for (ApplicationExitInfo exit : history) {
            if (!packageName.equals(exit.getProcessName())) continue;
            String code;
            if (exit.getReason() == ApplicationExitInfo.REASON_CRASH) code = "java-crash";
            else if (exit.getReason() == ApplicationExitInfo.REASON_CRASH_NATIVE) code = "native-crash";
            else continue;
            LocalDate day = Instant.ofEpochMilli(exit.getTimestamp()).atZone(ZoneOffset.UTC).toLocalDate();
            if (day.isBefore(today.minusDays(29)) || day.isAfter(today)) continue;
            byte[] bytes = exit.getProcessStateSummary();
            if (bytes == null || bytes.length < 37 || bytes.length > 100) continue;
            ByteBuffer record = ByteBuffer.wrap(bytes);
            if (record.getInt() != MAGIC || !new UUID(record.getLong(), record.getLong()).equals(generation)) continue;
            String id = new UUID(record.getLong(), record.getLong()).toString();
            String release = new String(bytes, record.position(), record.remaining(), StandardCharsets.US_ASCII);
            if (!release.matches(LABEL)) continue;
            if (!epoch.equals(prefs.getString("epoch", null))) return;
            if (previous.contains(id)) {
                delivered.add(id);
                pending.remove(id);
            } else if (pending.size() < MAX_PENDING && !pending.containsKey(id)) {
                pending.put(id, new JSONObject().put("p_event_id", id).put("p_day", day.toString())
                        .put("p_release", release).put("p_code", code));
            }
        }
        synchronized (SupastaqCrashReports.class) {
            if (!epoch.equals(prefs.getString("epoch", null))) return;
            writePending(queue, epoch, pending);
        }
        Iterator<Map.Entry<String, JSONObject>> items = pending.entrySet().iterator();
        while (items.hasNext()) {
            Map.Entry<String, JSONObject> item = items.next();
            if (!epoch.equals(prefs.getString("epoch", null))) return;
            try {
                if (submit(endpoint, anonKey, item.getValue())) {
                    delivered.add(item.getKey());
                    items.remove();
                }
            } catch (IOException offline) {
                break;
            }
        }
        synchronized (SupastaqCrashReports.class) {
            if (!epoch.equals(prefs.getString("epoch", null))) return;
            prefs.edit().putStringSet("delivered", delivered).apply();
            writePending(queue, epoch, pending);
        }
    }

    // Keep metadata on this installation until acknowledged, for at most 30 UTC days.
    private static Map<String, JSONObject> readPending(AtomicFile queue, String epoch, LocalDate today)
            throws IOException, JSONException {
        Map<String, JSONObject> pending = new LinkedHashMap<>();
        byte[] bytes;
        try { bytes = queue.readFully(); }
        catch (FileNotFoundException missing) { return pending; }
        JSONObject saved = new JSONObject(new String(bytes, StandardCharsets.UTF_8));
        if (!epoch.equals(saved.getString("epoch"))) return pending;
        JSONArray events = saved.getJSONArray("events");
        for (int i = 0; i < events.length() && pending.size() < MAX_PENDING; i++) {
            JSONObject event = events.getJSONObject(i);
            LocalDate day = LocalDate.parse(event.getString("p_day"));
            if (!day.isBefore(today.minusDays(29)) && !day.isAfter(today)) {
                pending.put(event.getString("p_event_id"), event);
            }
        }
        return pending;
    }

    private static void writePending(AtomicFile queue, String epoch, Map<String, JSONObject> pending)
            throws IOException, JSONException {
        if (pending.isEmpty()) { queue.delete(); return; }
        JSONObject saved = new JSONObject().put("epoch", epoch).put("events", new JSONArray(pending.values()));
        byte[] bytes = saved.toString().getBytes(StandardCharsets.UTF_8);
        FileOutputStream out = queue.startWrite();
        try {
            out.write(bytes);
            queue.finishWrite(out);
        } catch (IOException failure) {
            queue.failWrite(out);
            throw failure;
        }
    }

    private static boolean submit(String endpoint, String anonKey, JSONObject event) throws IOException {
        HttpsURLConnection connection = (HttpsURLConnection) new URL(endpoint).openConnection();
        try {
            connection.setInstanceFollowRedirects(false);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("apikey", anonKey);
            connection.setRequestProperty("Authorization", "Bearer " + anonKey);
            byte[] body = event.toString().getBytes(StandardCharsets.UTF_8);
            connection.setFixedLengthStreamingMode(body.length);
            try (OutputStream out = connection.getOutputStream()) { out.write(body); }
            if (connection.getResponseCode() != 200) return false;
            try (InputStream in = connection.getInputStream()) {
                return in.read() == 't' && in.read() == 'r' && in.read() == 'u' && in.read() == 'e' && in.read() == -1;
            }
        } finally {
            connection.disconnect();
        }
    }
}
