import { logger } from "../../../logger/index.js";
import { parseSingleYaml } from "../../../util/yaml.js";
import { getHttpUrl } from "../../../util/git/url.js";
import { getDep } from "../dockerfile/extract.js";
import { HelmDatasource } from "../../datasource/helm/index.js";
import { isOCIRegistry, removeOCIPrefix } from "../helmv3/oci.js";
import { GithubReleasesDatasource } from "../../datasource/github-releases/index.js";
import { GitRefsDatasource } from "../../datasource/git-refs/index.js";
import { Vendir } from "./schema.js";

//#region lib/modules/manager/vendir/extract.ts
function extractHelmChart(helmChart, aliases) {
	if (isOCIRegistry(helmChart.repository.url)) return {
		...getDep(`${removeOCIPrefix(helmChart.repository.url)}/${helmChart.name}:${helmChart.version}`, false, aliases),
		depName: helmChart.name,
		depType: "HelmChart",
		pinDigests: false
	};
	return {
		depName: helmChart.name,
		currentValue: helmChart.version,
		depType: "HelmChart",
		registryUrls: [helmChart.repository.url],
		datasource: HelmDatasource.id
	};
}
function extractGitSource(gitSource) {
	return {
		depName: getHttpUrl(gitSource.url),
		depType: "GitSource",
		currentValue: gitSource.ref,
		datasource: GitRefsDatasource.id
	};
}
function extractGithubReleaseSource(githubRelease) {
	return {
		depName: githubRelease.slug,
		packageName: githubRelease.slug,
		depType: "GithubRelease",
		currentValue: githubRelease.tag,
		datasource: GithubReleasesDatasource.id
	};
}
function parseVendir(content, packageFile) {
	try {
		return parseSingleYaml(content, {
			customSchema: Vendir,
			removeTemplates: true
		});
	} catch {
		logger.debug({ packageFile }, "Error parsing vendir.yml file");
		return null;
	}
}
function extractPackageFile(content, packageFile, config) {
	logger.trace(`vendir.extractPackageFile(${packageFile})`);
	const deps = [];
	const pkg = parseVendir(content, packageFile);
	if (!pkg) return null;
	const contents = pkg.directories.flatMap((directory) => directory.contents);
	for (const content of contents) if ("helmChart" in content && content.helmChart) {
		const dep = extractHelmChart(content.helmChart, config.registryAliases);
		if (dep) deps.push(dep);
	} else if ("git" in content && content.git) {
		const dep = extractGitSource(content.git);
		if (dep) deps.push(dep);
	} else if ("githubRelease" in content && content.githubRelease) {
		const dep = extractGithubReleaseSource(content.githubRelease);
		if (dep) deps.push(dep);
	}
	if (!deps.length) return null;
	return { deps };
}

//#endregion
export { extractPackageFile };
//# sourceMappingURL=extract.js.map