import all_clips_raw from "../src/app/clips_dpo.json";
import all_clips_raw2 from "../src/app/groove_manifest_crow.json";

const all_clips: string[] = all_clips_raw as unknown as string[];

export const fetchGenreID = async (
  genreName: string
): Promise<string | null> => {
  try {
    const entry = all_clips.find((entryString) => {
      try {
        const entryObject = JSON.parse(entryString);
        return entryObject.metadata?.tags?.includes(genreName.toLowerCase());
      } catch (error) {
        console.error("Error parsing entry:", error);
        return false;
      }
    });

    if (entry) {
      const parsedEntry = JSON.parse(entry);
      return parsedEntry.id;
    }
    return null;
  } catch (error) {
    console.error("Error fetching genre data:", error);
    return null;
  }
};

export const fetchAudioUrl = (genreID: string): string => {
  // rename parameter to audioID since it can pertain to either genre or song
  const cdnUrl = "https://cdn1.suno.ai";
  return `${cdnUrl}/${genreID}.mp3`;
};

interface Clip {
  id: string;
  title: string | null;
}

const all_clips_2: Record<string, Clip[]> = all_clips_raw2 as Record<
  string,
  Clip[]
>;

// export const getClipTitlesAndIDsByGenre = (): Record<
//   string,
//   Array<[string | null, string]>
// > => {
//   const clipTitlesAndIDsByGenre: Record<
//     string,
//     Array<[string | null, string]>
//   > = {};

//   let totalClips = 0;

//   Object.entries(all_clips_2).forEach(([genre, clips]) => {
//     const filteredClips = clips.filter(
//       (clip) => clip.title !== null && clip.title !== undefined
//     );
//     clipTitlesAndIDsByGenre[genre] = filteredClips.map((clip) => [
//       clip.title,
//       clip.id,
//     ]);

//     totalClips += clipTitlesAndIDsByGenre[genre].length;
//   });

//   return clipTitlesAndIDsByGenre;
// };

export const getClipTitlesAndIDsByGenre = (): Record<
  string,
  Array<[string | null, string]>
> => {
  const clipTitlesAndIDsByGenre: Record<
    string,
    Array<[string | null, string]>
  > = {};
  let totalClips = 0;

  Object.entries(all_clips_2).forEach(([genre, clips]) => {
    // First, filter out null/undefined titles
    const filteredClips = clips.filter(
      (clip) => clip.title !== null && clip.title !== undefined
    );

    // Group clips by their base title (removing v1/v2 suffix)
    const groupedClips: { [key: string]: Clip[] } = {};
    filteredClips.forEach((clip) => {
      const baseTitle = clip.title?.replace(/ v[12]$/, "") || "";
      if (!groupedClips[baseTitle]) {
        groupedClips[baseTitle] = [];
      }
      groupedClips[baseTitle].push(clip);
    });

    // For each group, randomly select one version
    const selectedClips = Object.values(groupedClips).map((versions) => {
      const randomIndex = Math.floor(Math.random() * versions.length);
      return versions[randomIndex];
    });

    // Map to the required format
    clipTitlesAndIDsByGenre[genre] = selectedClips.map((clip) => [
      clip.title,
      clip.id,
    ]);

    totalClips += clipTitlesAndIDsByGenre[genre].length;
  });

  return clipTitlesAndIDsByGenre;
};
