<?php

require 'vendor/autoload.php';
$ffmpeg = FFMpeg\FFMpeg::create();
  
function normalize_string($str) {
  $out = str_replace(' ', '_', preg_replace('/[\'\"\(\)\.,\[\]]+/', '', strtolower(str_replace('Ke$ha', 'kesha', $str))));
  return $out;
}

$file = trim(file_get_contents($argv[1]));
$items = array_map(function ($l) {
  return explode("\t", $l);
}, explode("\n", $file));
$header = array_slice($items, 0, 1)[0];
$items = array_map(function ($l) use ($argv) {
  return [
    'title' => $l['Name'],
    'artist' => $l['Artist'],
    'album' => $l['Album'],
    'mime' => 'audio/mp3',
    'file' => str_replace("Macintosh HD", "", $l['Location']),
    'note' => ''
  ];
}, array_map(function ($l) use ($header) {
  print_r($header);
  print_r($l);
  return array_combine($header, $l);
}, array_slice($items, 1)));

foreach ($items as $k => $item) {
  $out = $argv[2].'/'.normalize_string($item['artist']).'-'.normalize_string($item['title']).'.mp3';
  if (!file_exists($out) && file_exists($item['file'])) {
    $audio = $ffmpeg->open($item['file']);
    $audio->save(new FFMpeg\Format\Audio\MP3(), $out);
  }
  $items[$k]['file'] = $out;
}

$json = [
  'title' => '',
  'description' => '',
  'cover' => '',
  'tags' => [],
  'pubDate' => '',
  'tracklist' => $items
];

file_put_contents(preg_replace('/\.[a-zA-Z0-9]$/', '', $argv[1]).'.json', json_encode($json, JSON_PRETTY_PRINT));