import { log } from "../log.js";
import { defineSource } from "../source.js";
import { ensureArray } from "../utilities/template-helpers.js";
import { fetchWithRetry } from "../utilities/fetch.js";
import { obsidianPluginManifestJsonSource } from "./obsidian-plugin-manifest-json.js";
import { z } from "zod";
//#region src/lib/sources/obsidian-plugin-registry.ts
const communityPluginsUrl = "https://raw.githubusercontent.com/obsidianmd/obsidian-releases/master/community-plugin-stats.json";
const pluginStatsSchema = z.record(z.string(), z.record(z.string(), z.number()));
const obsidianPluginRegistrySource = defineSource({
	async discover(context) {
		if (context.options.offline) {
			log.debug("Skipping Obsidian plugin registry data source since we're in offline mode");
			return [];
		}
		let pluginIds = ensureArray(context.metadata?.obsidianPluginManifestJson).map((value) => value.data.id);
		if (pluginIds.length === 0 && !context.completedSources?.has("obsidianPluginManifestJson")) {
			log.debug(`Missing obsidianPluginManifestJson in source context metadata for ${context.options.path}, extracting it now...`);
			pluginIds = ensureArray(await obsidianPluginManifestJsonSource.extract(context)).map((value) => value.data.id);
		}
		return pluginIds;
	},
	key: "obsidianPluginRegistry",
	async parse(input) {
		log.debug("Extracting Obsidian plugin registry metadata...");
		const pluginId = input;
		const url = `https://obsidian.md/plugins?id=${encodeURIComponent(pluginId)}`;
		const response = await fetchWithRetry(communityPluginsUrl);
		if (!response.ok) return {
			data: { url },
			source: url
		};
		return {
			data: {
				downloadCount: pluginStatsSchema.parse(await response.json())[pluginId]?.downloads || void 0,
				url
			},
			source: url
		};
	},
	phase: 2
});
//#endregion
export { obsidianPluginRegistrySource };
