/**
 * DDragon version resolver for Data Dragon asset URLs.
 *
 * Resolves the appropriate patch version with the following priority:
 * 1. Game-specific version (from recorded timeline data)
 * 2. Latest version fetched from the DDragon API
 * 3. Hardcoded fallback version
 */

import { ref } from "vue";

/** DDragon versions API endpoint. */
const DDRAGON_VERSIONS_URL = "https://ddragon.leagueoflegends.com/api/versions.json";

/** Fallback version used when the DDragon API is unreachable. */
const FALLBACK_VERSION = "16.10.1";

/** Latest version from DDragon API (reactive — updates trigger Vue re-renders). */
export const ddragonVersion = ref<string>(FALLBACK_VERSION);

/** Whether the version has been fetched at least once. */
let versionInitialized = false;

/**
 * Fetch the latest game version from the DDragon API.
 * Results are cached after the first call — subsequent calls return immediately.
 * Safe to call multiple times (deduplicated).
 */
export async function fetchLatestDdragonVersion(): Promise<string> {
  if (versionInitialized) {
    return ddragonVersion.value;
  }

  try {
    const response = await fetch(DDRAGON_VERSIONS_URL);
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    const versions: string[] = await response.json();
    if (versions.length > 0) {
      ddragonVersion.value = versions[0];
    }
  } catch (err) {
    console.warn("[ddragon] Failed to fetch versions, using fallback:", err);
  } finally {
    versionInitialized = true;
  }

  return ddragonVersion.value;
}

/**
 * Get the current DDragon version (synchronous).
 * Returns the cached latest version, or the fallback if not yet fetched.
 */
export function getDdragonVersion(): string {
  return ddragonVersion.value;
}

/**
 * Convert a League game version string to DDragon format.
 *
 * The League Client reports versions like "16.10.1" or "16.10.1.1234".
 * DDragon uses the first three components (e.g., "16.10.1").
 *
 * @returns The DDragon-formatted version string, or null if the input is invalid.
 */
export function gameVersionToDdragonVersion(gameVersion: string | null | undefined): string | null {
  if (!gameVersion || typeof gameVersion !== "string") {
    return null;
  }

  const trimmed = gameVersion.trim();
  if (!trimmed) {
    return null;
  }

  // DDragon versions are in the format "XX.YY.ZZ" (e.g., "16.10.1")
  // The game client may report "XX.YY.ZZ.WWWW" — we take the first 3 parts
  const parts = trimmed.split(".");
  if (parts.length >= 3) {
    return `${parts[0]}.${parts[1]}.${parts[2]}`;
  }

  // Two-part version — unlikely but handle gracefully
  if (parts.length === 2) {
    return trimmed;
  }

  return null;
}
