import { createMockLibraryItems, normalizeLibraryItem } from "./libraryModel.js";

export const getTauriCore = async () => {
  const globalCore = window.__TAURI__?.core;
  if (typeof globalCore?.invoke === "function") {
    return {
      invoke: globalCore.invoke,
      convertFileSrc: typeof globalCore.convertFileSrc === "function" ? globalCore.convertFileSrc : null,
    };
  }

  try {
    const tauriCore = await import("@tauri-apps/api/core");
    return {
      invoke: typeof tauriCore.invoke === "function" ? tauriCore.invoke : null,
      convertFileSrc: typeof tauriCore.convertFileSrc === "function" ? tauriCore.convertFileSrc : null,
    };
  } catch (_error) {
    return { invoke: null, convertFileSrc: null };
  }
};

const defaultLocalFolders = () => ["C:/Games", "D:/Games"];

export const loadLibraryItems = async () => {
  const { invoke, convertFileSrc } = await getTauriCore();
  if (!invoke) {
    return {
      items: createMockLibraryItems(),
      status: "Mock data",
      message: "Run inside Tauri to scan real installed apps into library.db.",
      providers: [],
    };
  }

  try {
    const games = await invoke("list_library_games");
    const scannedItems = Array.isArray(games)
      ? games.map((game, index) => normalizeLibraryItem(game, index, convertFileSrc))
      : [];

    return {
      items: scannedItems.length ? scannedItems : createMockLibraryItems(),
      status: scannedItems.length ? "Synced with library.db" : "Mock data",
      message: scannedItems.length
        ? "Showing installed apps scanned into the separate NebulaOS library database."
        : "No scanned apps yet. Mock cards are shown until Start Scan finds installed apps.",
      providers: [],
    };
  } catch (error) {
    return {
      items: createMockLibraryItems(),
      status: "Library bridge fallback",
      message: String(error),
      providers: [],
    };
  }
};

export const scanLibraryItems = async () => {
  const { invoke, convertFileSrc } = await getTauriCore();
  if (!invoke) {
    return {
      items: createMockLibraryItems(),
      status: "Desktop bridge unavailable",
      message: "Start Scan will call Tauri when NebulaOS is running as a desktop app.",
      providers: [],
    };
  }

  const summary = await invoke("scan_library_command", {
    request: { localFolders: defaultLocalFolders() },
  });

  const items = Array.isArray(summary?.games)
    ? summary.games.map((game, index) => normalizeLibraryItem(game, index, convertFileSrc))
    : [];

  return {
    items: items.length ? items : createMockLibraryItems(),
    status: `${summary?.discovered ?? 0} discovered`,
    message: `${summary?.insertedOrUpdated ?? 0} saved · ${summary?.metadataMatched ?? 0} metadata matches · ${
      summary?.unmatched ?? 0
    } need review`,
    providers: summary?.providers ?? [],
  };
};

export const launchLibraryItem = async (item) => {
  if (!item?.installed) {
    console.info("[NebulaOS] Install/details state requested", item);
    return { launched: false, action: "details", message: "This app is not installed yet." };
  }

  const { invoke } = await getTauriCore();
  const numericId = Number(item.backendId ?? item.id);
  if (invoke && Number.isFinite(numericId)) {
    return invoke("launch_library_game", { gameId: numericId });
  }

  console.info("[NebulaOS] Launch placeholder", {
    id: item.id,
    title: item.title,
    executablePath: item.executablePath,
    installPath: item.installPath,
  });
  return { launched: true, action: "mock", message: `Launch queued for ${item.title}.` };
};

export const hideLibraryItem = async (item) => {
  const { invoke } = await getTauriCore();
  const numericId = Number(item?.backendId ?? item?.id);
  if (invoke && Number.isFinite(numericId)) {
    await invoke("update_library_game", {
      request: {
        gameId: numericId,
        title: null,
        executablePath: null,
        hidden: true,
        favourite: null,
      },
    });
  }
};
