/**
 * Stream-proxy URL builder.
 *
 * Restream policy (May 2026 brief):
 *   • Profiles whose `id` starts with `shared:` AND that have
 *     `managed === true` are admin-curated SHARED Profiles. Their
 *     stream URLs MUST flow through `/api/proxy/...` so the backend
 *     can deduplicate upstream connections (single-fetch hub) and
 *     keep the provider credentials hidden from the client.
 *   • Every other profile (per-user managed creds, user-uploaded M3U,
 *     manually-typed Xtream creds) connects DIRECTLY to its provider.
 *
 * Token TTL is 30 min server-side (see core/proxy_signer.py). When a
 * stream URL expires mid-playback the player will get a 403 and we
 * silently re-sign + retry. For a clean UX we proactively re-sign at
 * playback start every time — there's no per-stream caching here.
 */
import { getToken } from "@/lib/nadiAuth";
import type { XtreamProfile } from "@/types/xtream";

/** True for profiles whose stream URLs MUST be proxied.
 *  Also emits a diagnostic so adb logcat / Chrome remote-debug can
 *  prove whether the substitution path actually fires on a given APK.
 */
/** Proxy disabled — all streams play DIRECT on device for maximum speed.
 *  No server restreaming, no latency, no buffering through backend. */
export const isProxiedProfile = (_p: XtreamProfile): boolean => {
  return false;
};

/** Pull REACT_APP_BACKEND_URL via the same Vite envPrefix shim used elsewhere. */
const apiBase = (): string => {
  const env: any = (import.meta as any).env || {};
  return (
    env.VITE_REACT_APP_BACKEND_URL ||
    env.REACT_APP_BACKEND_URL ||
    env.VITE_BACKEND_URL ||
    ""
  );
};

interface SignBody {
  profile_id: string;
  kind: "live" | "vod";
  stream_id: string;
  stream_type?: "movie" | "series";
  ext?: string;
}

interface SignResp {
  proxy_url: string;
  expires_in: number;
}

const sign = async (body: SignBody): Promise<string> => {
  const token = getToken();
  const r = await fetch(`${apiBase()}/api/proxy/sign`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    body: JSON.stringify(body),
  });
  if (!r.ok) throw new Error(`/api/proxy/sign HTTP ${r.status}`);
  const j = (await r.json()) as SignResp;
  return `${apiBase()}${j.proxy_url}`;
};

/**
 * If the active profile is a Shared Profile, return a freshly-signed
 * proxy URL for the given LIVE stream id. Otherwise return null —
 * the caller should keep the direct upstream URL in that case.
 */
export const liveProxyUrl = async (
  p: XtreamProfile,
  streamId: string,
): Promise<string | null> => {
  if (!isProxiedProfile(p)) return null;
  return sign({ profile_id: p.id, kind: "live", stream_id: streamId });
};

/** Same shape, for movies + series episodes. */
export const vodProxyUrl = async (
  p: XtreamProfile,
  streamId: string,
  streamType: "movie" | "series",
  ext: string = "mp4",
): Promise<string | null> => {
  if (!isProxiedProfile(p)) return null;
  return sign({
    profile_id: p.id,
    kind: "vod",
    stream_id: streamId,
    stream_type: streamType,
    ext,
  });
};
