#!/bin/bash

ENDPOINT="http://192.168.1.117:9529/ZidooMusicControl/v2/getState"

data=$(curl -s --max-time 3 "$ENDPOINT") || data="{}"

# Averiguamos si Roon está activo
roon_active=$(echo "$data" | jq -e '
  .everSoloPlayInfo.everSoloPlayAudioInfo.songName? != null and
  .everSoloPlayInfo.everSoloPlayAudioInfo.songName != ""
' 2>/dev/null)

if [[ "$roon_active" == "true" ]]; then
  # Para Roon, usamos esta ruta…
  COVER_CACHE="/tmp/roon_album_cover.jpg"

  output=$(echo "$data" | jq -e "{
    title: (.everSoloPlayInfo.everSoloPlayAudioInfo.songName // \"Desconocido\"),
    artist: (.everSoloPlayInfo.everSoloPlayAudioInfo.artistName // \"\"),
    cover_url: (.everSoloPlayInfo.everSoloPlayAudioInfo.albumUrl // \"\"),
    album: (.everSoloPlayInfo.everSoloPlayAudioInfo.albumName // \"\"),
    quality: (.everSoloPlayOutputInfo.outPutDecodec // \"PCM\"),
    bits: (
      if (.everSoloPlayInfo.everSoloPlayAudioInfo.audioBitsPerSample? // 0) > 0
      then (.everSoloPlayInfo.everSoloPlayAudioInfo.audioBitsPerSample | tostring + \"-bit\")
      else \"\"
      end
    ),
    samplerate: (
      if (.everSoloPlayInfo.everSoloPlayAudioInfo.audioSampleRate? // 0) > 0
      then ((.everSoloPlayInfo.everSoloPlayAudioInfo.audioSampleRate / 1000 | floor | tostring) + \" kHz\")
      else \"\"
      end
    ),
    mqa: (.everSoloPlayOutputInfo.outPutMqaType? != 0)
  }")
else
  # Para “playingMusic”, usamos la caché normal
  COVER_CACHE="$HOME/.cache/eww/dmp_cover.jpg"

  output=$(echo "$data" | jq -e "{
    title: (.playingMusic.title // \"Desconocido\"),
    artist: (.playingMusic.artist // \"\"),
    cover_url: (.playingMusic.albumArt // \"\"),
    album: (.playingMusic.album // \"\"),
    quality: (.playingMusic.audioQuality // \"\"),
    bits: (.playingMusic.bits // \"\"),
    samplerate: (.playingMusic.sampleRate // \"\"),
    mqa: false
  }")
fi

# Construimos el info_string como antes…
info_string=$(echo "$output" | jq -r '[
  .quality,
  .bits,
  .samplerate
] | map(select(. != "")) | join(" – ")')

# Descargamos portada en la ruta que elegimos arriba
cover_url=$(echo "$output" | jq -r .cover_url)
if [[ "$cover_url" =~ ^http ]]; then
  curl -s "$cover_url" -o "$COVER_CACHE"
fi

if command -v convert &>/dev/null; then
  convert "$COVER_CACHE" -resize 230x230^ -gravity center -extent 230x230 "$COVER_CACHE"
elif command -v ffmpeg &>/dev/null; then
  ffmpeg -y -loglevel quiet -i "$COVER_CACHE" -vf "scale=230:230:force_original_aspect_ratio=increase,crop=230:230" "$COVER_CACHE"
fi

# Emitimos el JSON final
echo "$output" | jq --arg cover "$COVER_CACHE" --arg info "$info_string" \
  '. + {cover: $cover, info: $info}'

