/**
 * Modrinth API client — search packs, list versions, download mod files.
 * Task #101 — Modpack Server Installer
 *
 * Modrinth API v2: https://docs.modrinth.com/
 * No API key required for public endpoints.
 */

const axios = require('axios');

const BASE = 'https://api.modrinth.com/v2';
const UA = 'FirefrostGaming/Arbiter (contact@firefrostgaming.com)';

function headers() {
  return { 'User-Agent': UA, 'Accept': 'application/json' };
}

/**
 * Search modpacks.
 */
async function searchPacks(query, options = {}) {
  const facets = [['project_type:modpack']];
  if (options.gameVersion) facets.push([`versions:${options.gameVersion}`]);
  if (options.modLoader) facets.push([`categories:${options.modLoader.toLowerCase()}`]);

  const params = {
    query,
    facets: JSON.stringify(facets),
    limit: options.pageSize || 20,
    offset: options.offset || 0,
    index: 'downloads'
  };

  const resp = await axios.get(`${BASE}/search`, { headers: headers(), params, timeout: 15000 });
  const packs = (resp.data.hits || []).map(p => ({
    id: p.project_id,
    name: p.title,
    summary: p.description,
    thumbnail: p.icon_url || null,
    downloadCount: p.downloads,
    modLoader: (p.categories || []).find(c => /forge|fabric|neoforge|quilt/i.test(c)) || 'unknown',
    mcVersions: p.versions || [],
    provider: 'modrinth'
  }));
  return { packs, total: resp.data.total_hits || packs.length };
}

/**
 * Get pack details by project ID or slug.
 */
async function getPackDetails(projectId) {
  const resp = await axios.get(`${BASE}/project/${projectId}`, { headers: headers(), timeout: 10000 });
  const p = resp.data;
  return {
    id: p.id,
    name: p.title,
    summary: p.description,
    description: p.body || p.description,
    thumbnail: p.icon_url || null,
    screenshots: (p.gallery || []).map(g => g.url),
    downloadCount: p.downloads,
    categories: p.categories || [],
    provider: 'modrinth'
  };
}

/**
 * List versions for a project.
 */
async function listVersions(projectId) {
  const resp = await axios.get(`${BASE}/project/${projectId}/version`, {
    headers: headers(), timeout: 10000
  });
  return (resp.data || []).map(v => ({
    versionId: v.id,
    displayName: v.name,
    versionNumber: v.version_number,
    gameVersions: v.game_versions || [],
    loaders: v.loaders || [],
    files: (v.files || []).map(f => ({
      url: f.url,
      filename: f.filename,
      size: f.size,
      primary: f.primary
    })),
    datePublished: v.date_published
  }));
}

/**
 * Get the primary download URL for a specific version.
 */
async function getDownloadUrl(projectId, versionId) {
  const versions = await listVersions(projectId);
  const v = versions.find(ver => ver.versionId === versionId);
  if (!v || !v.files.length) return null;
  const primary = v.files.find(f => f.primary) || v.files[0];
  return primary.url;
}

module.exports = { searchPacks, getPackDetails, listVersions, getDownloadUrl };
