import {
  CLAUDECRAFT_WEAPON_CATALOG,
  weaponDefinition,
  type WeaponCatalogId,
} from "../game/weaponCatalog";
import { selectedGameAssetUrl } from "./GameAssetProvider";

const WEAPON_ASSET_PREFIX = "../assets/game/models/claudecraft/weapons/";
const WEAPON_ASSET_URLS = import.meta.glob<string>(
  "../assets/game/models/claudecraft/weapons/*.glb",
  { eager: true, import: "default", query: "?url" },
);

function importedWeaponUrl(fileName: string) {
  const url = WEAPON_ASSET_URLS[`${WEAPON_ASSET_PREFIX}${fileName}`];
  if (!url) throw new Error(`Missing imported Claudecraft weapon asset: ${fileName}`);
  return url;
}

/** Resolves one selected asset. Creating the URL table does not fetch or decode every GLB. */
export function characterEquipmentAssetUrl(modelId: WeaponCatalogId) {
  const definition = weaponDefinition(modelId);
  const sourceUrl = importedWeaponUrl(definition.sourceFile);
  const optimizedUrl = definition.optimizedFile
    ? importedWeaponUrl(definition.optimizedFile)
    : sourceUrl;
  return selectedGameAssetUrl(sourceUrl, optimizedUrl);
}

export function characterEquipmentAssetUrls() {
  return Object.fromEntries(CLAUDECRAFT_WEAPON_CATALOG.map((definition) => [
    definition.id,
    characterEquipmentAssetUrl(definition.id),
  ])) as Record<WeaponCatalogId, string>;
}
