import { parseFile } from "music-metadata";
import type { ItemMetadata } from "./types";

export type AudioTagMetadata = {
  title?: string;
  artist?: string;
  album?: string;
  genre?: string;
  year?: string;
};

export async function readAudioTags(filePath: string): Promise<AudioTagMetadata | null> {
  try {
    const { common } = await parseFile(filePath);
    if (!common.title && !common.artist && !common.album && !common.genre?.length) {
      return null;
    }

    return {
      title: common.title,
      artist: common.artist,
      album: common.album,
      genre: common.genre?.join(", "),
      year: common.year?.toString(),
    };
  } catch {
    return null;
  }
}

export function audioTagsToMetadata(
  tags: AudioTagMetadata,
  fallbackTitle: string,
): Pick<ItemMetadata, "title" | "description" | "tags" | "artist" | "songTitle"> {
  const songTitle = tags.title || fallbackTitle;
  const videoTitle =
    tags.artist && tags.title
      ? `${tags.artist} - ${tags.title}`
      : tags.title || fallbackTitle;

  const description = [tags.artist, tags.album, tags.year].filter(Boolean).join(" · ");
  const tagParts = [tags.genre, tags.artist].filter(Boolean);

  return {
    title: videoTitle,
    songTitle,
    description,
    tags: tagParts.join(", "),
    artist: tags.artist || null,
  };
}
