// Fanart.tv client for artist images.
// API: https://fanart.tv/2015/03/api/
// Requires API key (free tier available).

import { requestJson } from './http.js';

interface FanartArtistResponse {
  artistbackground?: Array<{ url: string }>;
  artistthumb?: Array<{ url: string }>;
  hdartistclearart?: Array<{ url: string }>;
  artistlogo?: Array<{ url: string }>;
  musicbanner?: Array<{ url: string }>;
}

export class FanartClient {
  private readonly baseUrl = 'https://webservice.fanart.tv/v3/music';
  private readonly apiKey: string;
  private readonly userAgent = 'muzick/0.1';

  constructor(apiKey?: string) {
    this.apiKey = apiKey || process.env.FANART_API_KEY || '';
  }

  private get enabled(): boolean {
    return this.apiKey.trim() !== '';
  }

  async getArtistImages(mbid: string): Promise<{
    background?: string;
    thumb?: string;
    clearart?: string;
    logo?: string;
    banner?: string;
  } | null> {
    if (!this.enabled) return null;
    if (!mbid) return null;

    const url = `${this.baseUrl}/${encodeURIComponent(mbid)}?api_key=${encodeURIComponent(this.apiKey)}`;

    try {
      const data = await requestJson<FanartArtistResponse>(url, {
        userAgent: this.userAgent,
        minIntervalMs: 1000, // Be respectful
      });

      return {
        background: data.artistbackground?.[0]?.url,
        thumb: data.artistthumb?.[0]?.url,
        clearart: data.hdartistclearart?.[0]?.url,
        logo: data.artistlogo?.[0]?.url,
        banner: data.musicbanner?.[0]?.url,
      };
    } catch (err) {
      console.warn('[Fanart.tv] getArtistImages failed:', (err as Error).message);
    }
    return null;
  }

  /**
   * Get the best available artist image.
   * Priority: thumb > clearart > logo > background > banner
   */
  async getBestArtistImage(mbid: string): Promise<string | null> {
    const images = await this.getArtistImages(mbid);
    if (!images) return null;
    
    return images.thumb ?? images.clearart ?? images.logo ?? images.background ?? images.banner ?? null;
  }
}