import { Assets, Texture } from 'pixi.js';
import {
  fetchGameTextureManifest,
  tryResolveGameAssetFile,
  type GameTextureManifest,
} from './resolveGameAssetUrl';
import { getRequiredSpriteKeys } from './spriteMapping';

export class GameSpriteRegistry {
  private _manifest: GameTextureManifest | null = null;
  private _textures = new Map<string, Texture>();
  private _ready = false;

  get ready(): boolean {
    return this._ready;
  }

  get manifest(): GameTextureManifest | null {
    return this._manifest;
  }

  async loadAll(): Promise<void> {
    const requiredKeys = getRequiredSpriteKeys();
    this._manifest = await fetchGameTextureManifest();
    for (const key of requiredKeys) {
      if (!this._manifest.textures[key]) {
        console.warn(`[Assets] Missing manifest entry for sprite key: ${key}`);
      }
    }
    const entries = Object.entries(this._manifest.textures);
    await Promise.all(
      entries.map(async ([key, entry]) => {
        const url = tryResolveGameAssetFile(entry.file);
        if (!url) {
          console.warn(`[Assets] Missing sprite file in bundle: ${entry.file}`);
          return;
        }
        const texture = await Assets.load<Texture>(url);
        // Pixel-art tiles/props: nearest filtering avoids subpixel seam artifacts on tile borders.
        texture.source.scaleMode = 'nearest';
        this._textures.set(key, texture);
      }),
    );
    this._ready = true;
  }

  getTexture(key: string): Texture | null {
    return this._textures.get(key) ?? null;
  }
}
