import type { AdConfigCSAI, AdConfigDAI } from 'react-native-video';
import { getSdkToken } from '../player/spallaSdk';
import { HttpError, httpGetText, parseJson } from './http';

const ASSETS_PREFIX = 'https://assets.spalla.io/';

function authHeaders(): Record<string, string> {
  const token = getSdkToken();
  return token ? { Authorization: `Bearer ${token}` } : {};
}

export interface Cdn {
  Nome: string;
  URL: string;
  DVR: boolean;
  Peso: number;
}

export interface StreamConfig {
  lm_video_id: string;
  lm_live_nome: string;
  lm_live_status: string;
  lm_live_thumbnail: string;
  lm_live_vod: boolean;
  lm_live_cdns: Cdn[];
  lm_live_jwt: boolean;
  lm_live_jwt_token: string;
  sp_ads_vast:
    | { url: string; offset?: string }
    | Array<{ url: string; offset?: string }>
    | null;
  sp_ads_vmap: { url: string } | Array<{ url: string }> | null;
  sp_ads_google_dai: {
    enabled: boolean;
    type: string;
    apiKey: string | null;
    contentSourceId?: string;
    videoId?: string;
    assetKey?: string;
  } | null;
  sp_ads_google_ima?: boolean | null;
  sp_player_autoplay: boolean;
  sp_duracao: number;
  sp_sinais_tem_a: boolean;
  sp_sinais_tem_b: boolean;
  lm_live_terminada?: boolean;
  lm_live_banner_fim?: string;
  lm_live_dvr?: boolean;
  /** Expected HLS segment duration in seconds (web player's lm_live_delay). */
  lm_live_delay?: number;
  sp_vertical?: boolean;
  sp_llhls?: boolean;
  sp_player_legendas?: boolean;
  sp_player_legendas_idiomas?: string[] | null;
  /** Spalla account id, forwarded to the cast receiver. */
  sp_conta?: string;
  sp_diretorio_id?: string | number;
  sp_caminho_diretorio?: string[];
  lm_geo_regiao_codigo?: string;
  lm_geo_regiao_nome?: string;
  lm_geo_isp?: string;
  lm_geo_asn?: string;
  lm_geo_ip?: string;
  lm_geo_pais_codigo?: string;
  lm_geo_pais_nome?: string;
  lm_geo_cidade?: string;
  lm_geo_latitude?: number | string;
  lm_geo_longitude?: number | string;
}

export function getThumbnailUrl(config: StreamConfig): string {
  const thumbnail = config.lm_live_thumbnail;
  if (!thumbnail) {
    return '';
  }
  if (/^https?:\/\//.test(thumbnail)) {
    return thumbnail;
  }
  // The API returns the path with or without the images/ segment.
  const path = thumbnail.replace(/^\/+/, '');
  return path.startsWith('images/')
    ? `${ASSETS_PREFIX}${path}`
    : `${ASSETS_PREFIX}images/${path}`;
}

export function getBannerFimUrl(config: StreamConfig): string {
  if (!config.lm_live_banner_fim) {
    return '';
  }
  return `${ASSETS_PREFIX}${config.lm_live_banner_fim}`;
}

function normalizeToArray<T>(value: T | T[] | null | undefined): T[] {
  if (!value) {
    return [];
  }
  return Array.isArray(value) ? value : [value];
}

function parseSignalFlag(value: unknown): boolean {
  return (
    value === true ||
    value === 'true' ||
    value === 1 ||
    value === '1' ||
    value === 'True' ||
    value === 'TRUE'
  );
}

// String-based on purpose: RN's URL polyfill inserts a "/" before the query.
function appendAuthParams(url: string, jwt?: string, uid?: string): string {
  const params: string[] = [];
  if (jwt) {
    params.push(`sjwt=${encodeURIComponent(jwt)}`);
  }
  if (uid) {
    params.push(`uid=${encodeURIComponent(uid)}`);
  }
  if (params.length === 0) {
    return url;
  }
  const separator = url.includes('?') ? '&' : '?';
  return `${url}${separator}${params.join('&')}`;
}

export function getLiveSignal(config: StreamConfig): 's1' | 's2' | null {
  if (parseSignalFlag(config.sp_sinais_tem_a)) {
    return 's1';
  }
  if (parseSignalFlag(config.sp_sinais_tem_b)) {
    return 's2';
  }
  return null;
}

function sortedCdns(config: StreamConfig): Cdn[] {
  const cdns = config.lm_live_cdns;
  if (!cdns || cdns.length === 0) {
    return [];
  }
  // Lowest weight = highest priority
  return [...cdns].sort((a, b) => a.Peso - b.Peso);
}

function pickCdn(config: StreamConfig, cdnName?: string): Cdn | null {
  const sorted = sortedCdns(config);
  if (cdnName) {
    const named = sorted.find((c) => c.Nome === cdnName);
    if (named) {
      return named;
    }
  }
  return sorted[0] ?? null;
}

function normalizeCdnUrl(url: string): string {
  return url.trim().replace(/\/+$/, '').toLowerCase();
}

// Round-robin over the weight-ordered list, wrapping at the end; null when
// there is no alternative to switch to. Entries resolving to the same base URL
// as the current one are skipped: getStreamUrl only uses Cdn.URL, so switching
// between them would re-request the exact same manifest.
export function getNextCdn(
  config: StreamConfig,
  currentName: string | null | undefined
): Cdn | null {
  const sorted = sortedCdns(config);
  if (sorted.length < 2) {
    return null;
  }
  // Unknown/absent current means the player is on the primary (index 0).
  const currentIndex = Math.max(
    0,
    sorted.findIndex((c) => c.Nome === currentName)
  );
  const currentUrl = normalizeCdnUrl(sorted[currentIndex]?.URL ?? '');
  for (let step = 1; step < sorted.length; step++) {
    const candidate = sorted[(currentIndex + step) % sorted.length];
    if (candidate && normalizeCdnUrl(candidate.URL) !== currentUrl) {
      return candidate;
    }
  }
  return null;
}

export function getCdnName(config: StreamConfig, cdnName?: string): string {
  return pickCdn(config, cdnName)?.Nome ?? '';
}

export function isVerticalVideo(config: StreamConfig): boolean {
  return config.sp_vertical === true;
}

export function isDvrEnabled(config: StreamConfig): boolean {
  if (config.lm_live_vod) {
    return false;
  }
  if (config.lm_live_dvr != null) {
    return config.lm_live_dvr === true;
  }
  return pickCdn(config)?.DVR === true;
}

export function getSubtitleLanguages(config: StreamConfig): string[] {
  if (config.sp_player_legendas === false) {
    return [];
  }
  return config.sp_player_legendas_idiomas ?? [];
}

// VoD sidecar files live next to the manifest: <CDN>/vod/<id>/<fileName>?sjwt&uid
function buildVodAssetUrl(
  config: StreamConfig,
  fileName: string,
  uid?: string
): string {
  if (!config.lm_live_vod) {
    return '';
  }
  const cdn = pickCdn(config);
  if (!cdn) {
    return '';
  }
  let url = cdn.URL;
  if (!url.endsWith('/')) {
    url += '/';
  }
  url += `${config.lm_video_id}/${fileName}`;

  return appendAuthParams(url, config.lm_live_jwt_token, uid);
}

export interface SubtitleTrack {
  language: string;
  uri: string;
}

export function getSubtitleTracks(
  config: StreamConfig,
  uid?: string
): SubtitleTrack[] {
  return getSubtitleLanguages(config)
    .map((language) => ({
      language,
      uri: buildVodAssetUrl(config, `${language}.srt`, uid),
    }))
    .filter((track) => track.uri !== '');
}

export function getThumbnailVttUrl(config: StreamConfig, uid?: string): string {
  return buildVodAssetUrl(config, 'thumbnail.vtt', uid);
}

export function getStreamUrl(
  config: StreamConfig,
  uid?: string,
  cdnName?: string
): string {
  const cdn = pickCdn(config, cdnName);
  if (!cdn) {
    return '';
  }

  const videoId = config.lm_video_id;
  const isLive = !config.lm_live_vod;

  let url = cdn.URL;
  if (!url.endsWith('/')) {
    url += '/';
  }

  if (isLive) {
    const signalPath = parseSignalFlag(config.sp_sinais_tem_a)
      ? 's1/playlist_nova-a.m3u8'
      : parseSignalFlag(config.sp_sinais_tem_b)
        ? 's2/playlist-nova-b.m3u8'
        : 'index.m3u8';

    url += `${videoId}/${signalPath}`;
  } else {
    url += `${videoId}/playlist.m3u8`;
  }

  return appendAuthParams(url, config.lm_live_jwt_token, uid);
}

export interface FailoverThresholds {
  /** Continuous rebuffer stall that triggers a CDN switch, in ms. */
  stallLimitMs: number;
  /** Buffer-ahead floor that triggers a CDN switch, in seconds. */
  bufferMinS: number;
  /** How long the post-switch minimum-quality cap lasts, in ms. */
  qualityRestoreMs: number;
}

// Mirrors the web player's tempoDelay()/bufferMinimo(): thresholds scale with
// the expected HLS segment duration (lm_live_delay), VoD uses a fixed base.
export function getFailoverThresholds(
  config: StreamConfig
): FailoverThresholds {
  const delay = config.lm_live_delay || 10;
  const base = config.lm_live_vod ? 10 : delay;
  const diff = (base / 10) * 1000;
  let stallLimitMs = base * 1000 - diff;
  if (config.lm_live_vod) {
    stallLimitMs *= 2;
  }
  return {
    stallLimitMs,
    bufferMinS: delay < 5 ? 1 : 3,
    qualityRestoreMs: stallLimitMs * 5,
  };
}

// Cachebusting macros the ad server expects the player to fill in. GAM keys the
// pod request off the correlator, so shipping a literal "[timestamp]" makes
// every request look like the same playback session and returns the same ad.
const AD_CACHEBUSTER_MACRO =
  /\[(?:timestamp|cachebuster|cachebusting)\]|%%CACHEBUSTER%%/gi;

function fillAdMacros(url: string | undefined): string | undefined {
  return url ? url.replace(AD_CACHEBUSTER_MACRO, String(Date.now())) : url;
}

export function getAdTagUrl(config: StreamConfig): string | undefined {
  const firstVmap = normalizeToArray(config.sp_ads_vmap)[0];
  if (firstVmap) {
    return fillAdMacros(firstVmap.url);
  }

  const firstVast = normalizeToArray(config.sp_ads_vast)[0];
  if (firstVast) {
    return fillAdMacros(firstVast.url);
  }

  return undefined;
}

export function getCsaiAdConfig(
  config: StreamConfig
): AdConfigCSAI | undefined {
  const adTagUrl = getAdTagUrl(config);
  if (!adTagUrl) {
    return undefined;
  }
  return {
    type: 'csai',
    adTagUrl,
    adLanguage: 'pt',
    ...(config.sp_vertical === true
      ? { linearAdSlotSize: 'container' as const }
      : {}),
  };
}

export function getDaiAdConfig(config: StreamConfig): AdConfigDAI | undefined {
  if (!config.sp_ads_google_dai?.enabled) {
    return undefined;
  }
  const dai = config.sp_ads_google_dai;
  const linearAdSlot =
    config.sp_vertical === true
      ? { linearAdSlotSize: 'container' as const }
      : {};
  if (dai.type === 'vod' && dai.contentSourceId && dai.videoId) {
    return {
      type: 'ssai',
      streamType: 'vod',
      format: 'hls',
      contentSourceId: dai.contentSourceId,
      videoId: dai.videoId,
      adLanguage: 'pt',
      ...linearAdSlot,
    };
  }

  if (dai.type === 'live' && dai.assetKey) {
    return {
      type: 'ssai',
      streamType: 'live',
      format: 'hls',
      assetKey: dai.assetKey,
      adLanguage: 'pt',
      ...linearAdSlot,
    };
  }

  return undefined;
}

const CONFIG_MAX_BYTES = 1024 * 1024;
const RETRY_DELAY_MS = 700;

function isTransient(e: unknown): boolean {
  return (
    e instanceof HttpError && (e.kind === 'timeout' || e.kind === 'network')
  );
}

// One retry only, and only for failures a retry can actually fix: a 4xx means
// geo-block or expired token and would just burn another round trip.
async function fetchJson<T>(
  url: string,
  what: string,
  signal?: AbortSignal
): Promise<T> {
  for (let attempt = 0; ; attempt++) {
    const canRetry = attempt === 0;
    try {
      const response = await httpGetText(url, authHeaders(), {
        signal,
        maxBytes: CONFIG_MAX_BYTES,
      });
      if (!response.ok) {
        const error = new HttpError(
          'http',
          `Failed to fetch ${what}: ${response.status}`,
          response.status
        );
        if (canRetry && response.status >= 500) {
          await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));
          continue;
        }
        throw error;
      }
      return parseJson<T>(response.text, what);
    } catch (e) {
      if (canRetry && isTransient(e)) {
        await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));
        continue;
      }
      throw e;
    }
  }
}

export async function fetchStreamConfig(
  streamId: string,
  uid: string,
  signal?: AbortSignal
): Promise<StreamConfig> {
  const url = `https://beyond.spalla.io/cache/config/${encodeURIComponent(streamId)}?&uid=${encodeURIComponent(uid)}`;
  const config = await fetchJson<StreamConfig>(url, 'config', signal);
  // Without these the player would build empty URLs and fail much later, with
  // an error that points at the CDN instead of at the malformed config.
  if (!config?.lm_video_id || !Array.isArray(config.lm_live_cdns)) {
    throw new HttpError('parse', 'Stream config is missing required fields');
  }
  return config;
}

export function fetchLiveStatus(
  streamId: string,
  uid: string,
  signal?: AbortSignal
): Promise<
  Partial<
    Pick<
      StreamConfig,
      | 'lm_live_terminada'
      | 'lm_live_banner_fim'
      | 'sp_sinais_tem_a'
      | 'sp_sinais_tem_b'
    >
  >
> {
  const url = `https://beyond.spalla.io/beyond/status/${encodeURIComponent(streamId)}?&uid=${encodeURIComponent(uid)}`;
  return fetchJson(url, 'live status', signal);
}
