import fs from "node:fs";
import path from "node:path";

/**
 * Drop in photography.
 *
 * The site ships with designed SVG artwork in every image position, so it looks
 * finished today. When Three Stars have their own factory photography, they drop
 * a file into /public/media named after the slot id and it takes over. No code
 * edit, no config entry.
 *
 * public/media/knitwear-floor.jpg  ->  fills the slot with id "knitwear-floor"
 */

const MEDIA_DIR = path.join(process.cwd(), "public", "media");
const EXTENSIONS = [".jpg", ".jpeg", ".png", ".webp", ".avif"];

let cache: Map<string, string> | null = null;

/**
 * Maps a slot id to the public path of a matching file in /public/media.
 * Read once per server process. Restart dev or rebuild after adding photos.
 */
export function getMediaMap(): Map<string, string> {
  if (cache) return cache;

  const map = new Map<string, string>();

  try {
    for (const entry of fs.readdirSync(MEDIA_DIR)) {
      const ext = path.extname(entry).toLowerCase();
      if (!EXTENSIONS.includes(ext)) continue;

      const id = path.basename(entry, ext).toLowerCase();
      // First match wins, so a jpg and a webp of the same slot do not fight.
      if (!map.has(id)) map.set(id, `/media/${entry}`);
    }
  } catch {
    // No media directory yet is a normal state, not an error. Every slot then
    // renders its designed fallback.
  }

  cache = map;
  return map;
}

export function resolveMedia(id: string): string | null {
  return getMediaMap().get(id.toLowerCase()) ?? null;
}
