export type SoftwareFamily =
  | 'VANILLA'
  | 'PAPER'
  | 'PURPUR'
  | 'FABRIC'
  | 'FORGE'
  | 'NEOFORGE'
  | 'QUILT'
  | 'BEDROCK_DEDICATED';

export type ModrinthProjectType = 'mod' | 'plugin' | 'modpack' | 'resourcepack' | 'shader';

export interface ModrinthProject {
  project_id: string;
  slug: string;
  title: string;
  description: string;
  project_type: ModrinthProjectType;
  downloads: number;
  icon_url?: string;
}

export interface ModrinthSearchResponse {
  hits: ModrinthProject[];
  offset: number;
  limit: number;
  total_hits: number;
}

export interface ModrinthVersionFile {
  hashes: Record<string, string>;
  url: string;
  filename: string;
  primary: boolean;
  size: number;
}

export interface ModrinthVersion {
  id: string;
  project_id: string;
  name: string;
  version_number: string;
  game_versions: string[];
  loaders: string[];
  files: ModrinthVersionFile[];
  date_published: string;
}

const MODRINTH_API = 'https://api.modrinth.com/v2';

export async function searchModrinthProjects(input: {
  query: string;
  projectType: ModrinthProjectType;
  gameVersion: string;
  loader?: string;
  limit?: number;
}): Promise<ModrinthSearchResponse> {
  const facets: string[][] = [
    [`project_type:${input.projectType}`],
    [`versions:${input.gameVersion}`],
  ];

  if (input.loader) {
    facets.push([`categories:${input.loader}`]);
  }

  const params = new URLSearchParams({
    query: input.query,
    limit: String(input.limit ?? 20),
    index: 'relevance',
    facets: JSON.stringify(facets),
  });

  const response = await fetch(`${MODRINTH_API}/search?${params.toString()}`, {
    headers: {
      'User-Agent': 'HexaHost-GameCloud/1.0 (catalog-sync)',
    },
  });

  if (!response.ok) {
    throw new Error(`Modrinth search failed: ${response.status}`);
  }

  return response.json() as Promise<ModrinthSearchResponse>;
}

export async function getModrinthProjectVersions(
  projectId: string,
): Promise<ModrinthVersion[]> {
  const response = await fetch(
    `${MODRINTH_API}/project/${encodeURIComponent(projectId)}/version`,
    {
      headers: {
        'User-Agent': 'HexaHost-GameCloud/1.0 (catalog-sync)',
      },
    },
  );

  if (!response.ok) {
    throw new Error(`Modrinth versions failed: ${response.status}`);
  }

  return response.json() as Promise<ModrinthVersion[]>;
}

export interface ModrinthProjectDetails {
  id: string;
  slug: string;
  title: string;
  description: string;
  project_type: ModrinthProjectType;
  downloads: number;
  icon_url?: string;
}

export async function getModrinthProject(projectId: string): Promise<ModrinthProjectDetails> {
  const response = await fetch(
    `${MODRINTH_API}/project/${encodeURIComponent(projectId)}`,
    {
      headers: {
        'User-Agent': 'HexaHost-GameCloud/1.0 (catalog-sync)',
      },
    },
  );

  if (!response.ok) {
    throw new Error(`Modrinth project failed: ${response.status}`);
  }

  return response.json() as Promise<ModrinthProjectDetails>;
}

export async function getModrinthVersion(versionId: string): Promise<ModrinthVersion> {
  const response = await fetch(
    `${MODRINTH_API}/version/${encodeURIComponent(versionId)}`,
    {
      headers: {
        'User-Agent': 'HexaHost-GameCloud/1.0 (catalog-sync)',
      },
    },
  );

  if (!response.ok) {
    throw new Error(`Modrinth version failed: ${response.status}`);
  }

  return response.json() as Promise<ModrinthVersion>;
}
