import { access, readdir } from "node:fs/promises";
import { dirname, join, relative } from "node:path";
import { fileURLToPath } from "node:url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export const PHOTOS_DIRECTORY = join(__dirname, "../content/photos/albums");

export interface PhotoDirectory {
  name: string;
  imagePaths: string[];
}

async function findJpgFiles(dir: string, baseDir: string): Promise<string[]> {
  const results: string[] = [];
  const entries = await readdir(dir, { withFileTypes: true });
  for (const entry of entries) {
    const fullPath = join(dir, entry.name);
    if (entry.isDirectory()) {
      const nested = await findJpgFiles(fullPath, baseDir);
      results.push(...nested);
    } else if (entry.isFile() && entry.name.toLowerCase().endsWith(".jpg")) {
      results.push(relative(baseDir, fullPath));
    }
  }
  return results;
}

export async function getPhotoDirectories(
  photosDirectory: string,
): Promise<PhotoDirectory[]> {
  const entries = await readdir(photosDirectory, { withFileTypes: true });
  const dirs = entries.filter((e) => e.isDirectory());

  const result: PhotoDirectory[] = [];
  for (const dir of dirs) {
    const dirPath = join(photosDirectory, dir.name);
    const imagePaths = await findJpgFiles(dirPath, photosDirectory);
    if (imagePaths.length > 0) {
      result.push({ name: dir.name, imagePaths });
    }
  }
  return result;
}

export async function getImagesMissingMetadata(
  photosDirectory: string,
): Promise<string[]> {
  const allImagePaths = await findJpgFiles(photosDirectory, photosDirectory);
  const missing: string[] = [];

  for (const imagePath of allImagePaths) {
    const jsonPath = getMetadataPathForImage(imagePath, photosDirectory);
    try {
      await access(jsonPath);
    } catch {
      missing.push(imagePath);
    }
  }
  return missing;
}

export function getMetadataPathForImage(
  relativeImagePath: string,
  photosDirectory: string,
): string {
  const jsonRelativePath = relativeImagePath.replace(/\.jpg$/i, ".json");
  return join(photosDirectory, jsonRelativePath);
}

export function getPhotoAbsolutePath(
  relativeImagePath: string,
  photosDirectory: string,
): string {
  return join(photosDirectory, relativeImagePath);
}
