/**
 * Funkwhale Activity Data
 * Fetches from Indiekit's endpoint-funkwhale public API
 */

import EleventyFetch from "@11ty/eleventy-fetch";
import { cacheCoverUrls, cacheFunkwhaleImage, gcFunkwhaleImages } from "../lib/cache-funkwhale-image.js";

const INDIEKIT_URL =
  process.env.INDIEKIT_URL || process.env.SITE_URL || "https://example.com";
const FUNKWHALE_INSTANCE = process.env.FUNKWHALE_INSTANCE || "";
const DEFAULT_FETCH_CACHE_DURATION = "5m";
const LISTENING_FETCH_CACHE_DURATION =
  (process.env.LISTENING_FETCH_CACHE_DURATION || "").trim() || DEFAULT_FETCH_CACHE_DURATION;
const FUNKWHALE_FETCH_CACHE_DURATION =
  (process.env.FUNKWHALE_FETCH_CACHE_DURATION || "").trim() || LISTENING_FETCH_CACHE_DURATION;

/**
 * Fetch from Indiekit's public Funkwhale API endpoint
 */
async function fetchFromIndiekit(endpoint) {
  const urls = [
    `${INDIEKIT_URL}/funkwhale/api/${endpoint}`,
    `${INDIEKIT_URL}/funkwhaleapi/api/${endpoint}`,
  ];

  for (const url of urls) {
    try {
      console.log(`[funkwhaleActivity] Fetching from Indiekit: ${url}`);
      const data = await EleventyFetch(url, {
        duration: FUNKWHALE_FETCH_CACHE_DURATION,
        type: "json",
      });
      console.log(`[funkwhaleActivity] Indiekit ${endpoint} success via ${url}`);
      return data;
    } catch (error) {
      console.log(
        `[funkwhaleActivity] Indiekit API unavailable for ${endpoint} at ${url}: ${error.message}`
      );
    }
  }

  return null;
}

/**
 * Format duration in seconds to human-readable string
 */
function formatDuration(seconds) {
  if (!seconds || seconds < 0) return "0:00";

  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);

  if (hours > 24) {
    const days = Math.floor(hours / 24);
    return `${days}d`;
  }

  if (hours > 0) {
    return `${hours}h ${minutes}m`;
  }

  return `${minutes}m`;
}

export default async function () {
  try {
    console.log("[funkwhaleActivity] Fetching Funkwhale data...");
    console.log(
      `[funkwhaleActivity] EleventyFetch cache duration: ${FUNKWHALE_FETCH_CACHE_DURATION}`
    );

    // Fetch all data from Indiekit API
    const [nowPlaying, listenings, favorites, stats] = await Promise.all([
      fetchFromIndiekit("now-playing"),
      fetchFromIndiekit("listenings"),
      fetchFromIndiekit("favorites"),
      fetchFromIndiekit("stats"),
    ]);

    // Check if we got data
    const hasData = nowPlaying || listenings?.listenings?.length || stats?.summary;

    if (!hasData) {
      console.log("[funkwhaleActivity] No data available from Indiekit");
      return {
        nowPlaying: null,
        listenings: [],
        favorites: [],
        stats: null,
        instanceUrl: FUNKWHALE_INSTANCE,
        source: "unavailable",
      };
    }

    console.log("[funkwhaleActivity] Using Indiekit API data");

    // Format stats with human-readable durations
    let formattedStats = null;
    if (stats?.summary) {
      formattedStats = {
        ...stats,
        summary: {
          all: {
            ...stats.summary.all,
            totalDurationFormatted: formatDuration(stats.summary.all?.totalDuration || 0),
          },
          month: {
            ...stats.summary.month,
            totalDurationFormatted: formatDuration(stats.summary.month?.totalDuration || 0),
          },
          week: {
            ...stats.summary.week,
            totalDurationFormatted: formatDuration(stats.summary.week?.totalDuration || 0),
          },
        },
      };
    }

    // Mark listenings that appear in favorites
    const favSet = new Set(
      (favorites?.favorites || []).map((f) => `${f.track}\0${f.artist}`)
    );
    const enrichedListenings = (listenings?.listenings || []).map((l) => ({
      ...l,
      favorite: favSet.has(`${l.track}\0${l.artist}`),
    }));

    // Cache cover images locally to avoid serving expiring presigned S3 URLs
    const [cachedNowPlaying, cachedListenings, cachedFavorites] = await Promise.all([
      nowPlaying ? { ...nowPlaying, coverUrl: await cacheFunkwhaleImage(nowPlaying.coverUrl) } : null,
      cacheCoverUrls(enrichedListenings),
      cacheCoverUrls(favorites?.favorites || []),
    ]);

    // Remove cached images that are no longer referenced by any current item
    gcFunkwhaleImages();

    return {
      nowPlaying: cachedNowPlaying,
      listenings: cachedListenings,
      favorites: cachedFavorites,
      stats: formattedStats,
      instanceUrl: FUNKWHALE_INSTANCE,
      source: "indiekit",
    };
  } catch (error) {
    console.error("[funkwhaleActivity] Error:", error.message);
    return {
      nowPlaying: null,
      listenings: [],
      favorites: [],
      stats: null,
      instanceUrl: FUNKWHALE_INSTANCE,
      source: "error",
    };
  }
}
