package com.foxx.androidcast.network;

/** Canonical production BE URLs on {@code apps.f0xx.org} (network self-test + defaults). */
public final class BackendEndpoints {
    public static final String APPS_HOST = "apps.f0xx.org";
    public static final String ISSUES_BASE =
            "https://" + APPS_HOST + "/app/androidcast_project/issues";
    /** @deprecated use {@link #ISSUES_BASE}; nginx 301 redirects legacy path. */
    public static final String CRASHES_BASE = ISSUES_BASE;
    public static final String GRAPHS_BASE =
            "https://" + APPS_HOST + "/app/androidcast_project/graphs";
    public static final String HEARTBEAT_URL = CRASHES_BASE + "/api/heartbeat.php";
    public static final String UPLOAD_URL = CRASHES_BASE + "/api/upload.php";
    public static final String GRAPH_UPLOAD_URL = GRAPHS_BASE + "/api/graph_upload.php";
    public static final String ENTITLEMENTS_BASE =
            "https://" + APPS_HOST + "/app/androidcast_project/entitlements";
    /** GET — returns JSON {@code {key, file_url|file_base64, etag}} for RBAC-authenticated user. */
    public static final String ENTITLEMENTS_FETCH_URL = ENTITLEMENTS_BASE + "/api/fetch.php";

    private BackendEndpoints() {}

    /** Maps legacy {@code f0xx.org}/{@code foxx.org} crash paths to {@link #APPS_HOST}. */
    public static String normalizeCrashesUrl(String url) {
        if (url == null) {
            return "";
        }
        String trimmed = url.trim();
        if (trimmed.isEmpty()) {
            return trimmed;
        }
        if (trimmed.contains("://f0xx.org/app/androidcast_project/crashes")
                || trimmed.contains("://foxx.org/app/androidcast_project/crashes")
                || trimmed.contains("://f0xx.org/app/androidcast_project/issues")
                || trimmed.contains("://foxx.org/app/androidcast_project/issues")) {
            return trimmed.replace("://f0xx.org/", "://" + APPS_HOST + "/")
                    .replace("://foxx.org/", "://" + APPS_HOST + "/")
                    .replace("/crashes/", "/issues/");
        }
        if (trimmed.contains("/crashes/")) {
            return trimmed.replace("/crashes/", "/issues/");
        }
        return trimmed;
    }

    /** Maps a crashes upload URL to the graphs session ingest endpoint. */
    public static String graphUploadUrlFromCrashesUrl(String crashesUrl) {
        if (crashesUrl == null || crashesUrl.isEmpty()) {
            return GRAPH_UPLOAD_URL;
        }
        String trimmed = normalizeCrashesUrl(crashesUrl.trim());
        if (trimmed.contains("/issues/")) {
            return trimmed.replace("/issues/", "/graphs/")
                    .replace("/api/upload.php", "/api/graph_upload.php");
        }
        return GRAPH_UPLOAD_URL;
    }
}
