import { defineTemplate } from "../metadata-types.js";
import { collectArrayField, collectField, firstOf, nonEmpty, stripUndefined } from "../utilities/template-helpers.js";
import { deduplicateDependencies, deduplicatePersonsOrOrgs, toDependencyLd, toPersonOrOrgLd, toSpdxLicenseUrl } from "../utilities/codemeta-helpers.js";
import { basename, relative } from "node:path";
import is from "@sindresorhus/is";
//#region src/lib/templates/codemeta.ts
/**
* CodeMeta 3.0 JSON-LD template.
*
* Generates a valid codemeta.json (https://codemeta.github.io/) by cascading
* data from all available metascope sources.
*
* ## Cascade strategy
*
* For **ecosystem-derived fields** (name, version, description, author,
* license, dependencies, keywords, …) the ecosystem manifest is canonical.
* This keeps the output fresh when e.g. a new dependency is added to
* package.json, and makes the round-trip stable: generate → save as
* codemeta.json → regenerate → identical output.
*
* For **codemeta-specific fields** that only exist in codemeta.json
* (developmentStatus, funding, buildInstructions, …) the existing
* codemeta.json is the source of truth.
*
* ## Software type inference
*
* Set `INFER_TARGET_PRODUCT` to `true` to enable heuristic inference of
* `targetProduct` from available signals (bin field, browser field, etc.).
*/
const codemeta = defineTemplate(({ arduinoLibraryProperties, cinderCinderblockXml, codemetaJson: codemetaRaw, codeStats, fileStats, github: githubRaw, gitStats: gitRaw, goGoMod, javaPomXml, licenseFile, metascope, nodeNpmRegistry: npmRaw, nodePackageJson, obsidianPluginManifestJson, openframeworksAddonConfigMk, openframeworksInstallXml, processingLibraryProperties, publiccodeYaml, pythonPkgInfo, pythonPypiRegistry: pypiRaw, pythonPyprojectToml, pythonSetupCfg, pythonSetupPy, readmeFile, rubyGemspec, rustCargoToml, xcodeInfoPlist }) => {
	const cm = firstOf(codemetaRaw);
	const github = firstOf(githubRaw);
	const git = firstOf(gitRaw);
	const npm = firstOf(npmRaw);
	const pypi = firstOf(pypiRaw);
	const package_ = firstOf(nodePackageJson);
	const pyproject = firstOf(pythonPyprojectToml);
	const setupPy = firstOf(pythonSetupPy);
	const setupCfg = firstOf(pythonSetupCfg);
	const pkgInfo = firstOf(pythonPkgInfo);
	const cargo = firstOf(rustCargoToml);
	const gem = firstOf(rubyGemspec);
	const pom = firstOf(javaPomXml);
	const goMod = firstOf(goGoMod);
	const arduino = firstOf(arduinoLibraryProperties);
	const processing = firstOf(processingLibraryProperties);
	const ofAddon = firstOf(openframeworksAddonConfigMk);
	const ofInstall = firstOf(openframeworksInstallXml);
	const cinder = firstOf(cinderCinderblockXml);
	const xcode = firstOf(xcodeInfoPlist);
	const obsidian = firstOf(obsidianPluginManifestJson);
	const publiccode = firstOf(publiccodeYaml);
	const loc = firstOf(codeStats);
	const readmeFileFirst = firstOf(readmeFile);
	const fileStatsFirst = firstOf(fileStats);
	const poetry = pyproject?.data.tool?.poetry;
	const name = package_?.data.name ?? pyproject?.data.project?.name ?? poetry?.name ?? setupPy?.data.name ?? setupCfg?.data.name ?? pkgInfo?.data.name ?? cargo?.data.name ?? gem?.data.name ?? pom?.data.name ?? goMod?.data.module ?? arduino?.data.name ?? processing?.data.name ?? ofAddon?.data.name ?? ofInstall?.data.name ?? cinder?.data.name ?? xcode?.data.name ?? obsidian?.data.name ?? publiccode?.data.name ?? cm?.data.name ?? readmeFileFirst?.data.name ?? fileStatsFirst?.data.folderName;
	const description = package_?.data.description ?? pyproject?.data.project?.description ?? poetry?.description ?? setupPy?.data.description ?? setupCfg?.data.description ?? pkgInfo?.data.summary ?? cargo?.data.description ?? gem?.data.summary ?? pom?.data.description ?? arduino?.data.sentence ?? processing?.data.sentence ?? ofAddon?.data.description ?? ofInstall?.data.description ?? cinder?.data.summary ?? xcode?.data.description ?? obsidian?.data.description ?? publiccode?.data.description?.shortDescription ?? cm?.data.description ?? github?.data.description;
	const version = package_?.data.version ?? pyproject?.data.project?.version ?? poetry?.version ?? setupPy?.data.version ?? setupCfg?.data.version ?? pkgInfo?.data.version ?? cargo?.data.version ?? gem?.data.version ?? pom?.data.version ?? arduino?.data.version ?? processing?.data.prettyVersion ?? ofInstall?.data.version ?? cinder?.data.version ?? xcode?.data.version ?? obsidian?.data.version ?? publiccode?.data.softwareVersion ?? cm?.data.version ?? cm?.data.softwareVersion;
	const identifier = pom?.data.identifier ?? cinder?.data.id ?? obsidian?.data.id ?? xcode?.data.identifier ?? package_?.data.name ?? cm?.data.identifier;
	const ecosystemAuthors = [
		...package_?.data.author ? [toPersonOrOrgLd({
			email: package_.data.author.email,
			name: package_.data.author.name,
			url: package_.data.author.url
		})] : [],
		...(pyproject?.data.project?.authors ?? []).map((a) => is.plainObject(a) ? toPersonOrOrgLd({
			email: a.email,
			name: a.name
		}) : toPersonOrOrgLd({ name: a })),
		...setupPy?.data.author ? [toPersonOrOrgLd({
			email: setupPy.data.author_email,
			name: setupPy.data.author
		})] : [],
		...setupCfg?.data.author ? [toPersonOrOrgLd({
			email: setupCfg.data.author_email,
			name: setupCfg.data.author
		})] : [],
		...(cargo?.data.authors ?? []).map((a) => toPersonOrOrgLd({
			email: a.email,
			name: a.name
		})),
		...gemspecAuthors(gem),
		...(pom?.data.developers ?? []).map((d) => toPersonOrOrgLd({
			affiliation: d.organization,
			email: d.email,
			name: d.name,
			url: d.url
		})),
		...(arduino?.data.authors ?? []).map((a) => toPersonOrOrgLd({
			email: a.email,
			name: a.name
		})),
		...(processing?.data.authors ?? []).map((a) => toPersonOrOrgLd({
			name: a.name,
			url: a.url
		})),
		...ofAddon?.data.author ? [toPersonOrOrgLd({ name: ofAddon.data.author })] : [],
		...ofInstall?.data.author ? [toPersonOrOrgLd({ name: ofInstall.data.author })] : [],
		...(cinder?.data.author ?? []).map((a) => toPersonOrOrgLd({ name: a })),
		...xcode?.data.author ? [toPersonOrOrgLd({
			email: xcode.data.authorEmail,
			name: xcode.data.author
		})] : [],
		...obsidian?.data.author ? [toPersonOrOrgLd({
			name: obsidian.data.author,
			url: obsidian.data.authorUrl
		})] : [],
		...(publiccode?.data.contacts ?? []).map((c) => toPersonOrOrgLd({
			affiliation: c.affiliation,
			email: c.email,
			name: c.name
		}))
	];
	const cmAuthors = cm?.data.author?.map((p) => toPersonOrOrgLd({
		affiliation: p.affiliation,
		email: p.email,
		familyName: p.familyName,
		givenName: p.givenName,
		id: p.id,
		name: p.name,
		type: p.type,
		url: p.url
	}));
	const author = resolvePersonsOrOrgs(ecosystemAuthors, cmAuthors);
	const ecosystemContributors = [...collectArrayField(nodePackageJson, (d) => d.contributors?.map((c) => is.plainObject(c) ? toPersonOrOrgLd({
		email: c.email,
		name: c.name,
		url: c.url
	}) : toPersonOrOrgLd({ name: c }))), ...(pom?.data.contributors ?? []).map((c) => toPersonOrOrgLd({
		affiliation: c.organization,
		email: c.email,
		name: c.name,
		url: c.url
	}))];
	const cmContributors = cm?.data.contributor?.map((p) => toPersonOrOrgLd({
		affiliation: p.affiliation,
		email: p.email,
		familyName: p.familyName,
		givenName: p.givenName,
		id: p.id,
		name: p.name,
		type: p.type,
		url: p.url
	}));
	const contributor = resolvePersonsOrOrgs(ecosystemContributors, cmContributors);
	const ecosystemMaintainers = [
		...collectArrayField(nodePackageJson, (d) => d.maintainers?.map((c) => is.plainObject(c) ? toPersonOrOrgLd({
			email: c.email,
			name: c.name,
			url: c.url
		}) : toPersonOrOrgLd({ name: c }))),
		...(pyproject?.data.project?.maintainers ?? []).map((m) => is.plainObject(m) ? toPersonOrOrgLd({
			email: m.email,
			name: m.name
		}) : toPersonOrOrgLd({ name: m })),
		...setupPy?.data.maintainer ? [toPersonOrOrgLd({
			email: setupPy.data.maintainer_email,
			name: setupPy.data.maintainer
		})] : [],
		...setupCfg?.data.maintainer ? [toPersonOrOrgLd({
			email: setupCfg.data.maintainer_email,
			name: setupCfg.data.maintainer
		})] : [],
		...pkgInfo?.data.maintainer ? [toPersonOrOrgLd({
			email: pkgInfo.data.maintainer_email,
			name: pkgInfo.data.maintainer
		})] : [],
		...arduino?.data.maintainer ? [toPersonOrOrgLd({
			email: arduino.data.maintainer.email,
			name: arduino.data.maintainer.name
		})] : []
	];
	const cmMaintainers = cm?.data.maintainer?.map((p) => toPersonOrOrgLd({
		affiliation: p.affiliation,
		email: p.email,
		familyName: p.familyName,
		givenName: p.givenName,
		id: p.id,
		name: p.name,
		type: p.type,
		url: p.url
	}));
	const maintainer = resolvePersonsOrOrgs(ecosystemMaintainers, cmMaintainers);
	const ecosystemCopyrightHolders = [...publiccode?.data.mainCopyrightOwner ? [toPersonOrOrgLd({ name: publiccode.data.mainCopyrightOwner })] : [], ...xcode?.data.copyrightHolder ? [toPersonOrOrgLd({ name: xcode.data.copyrightHolder })] : []];
	const cmCopyrightHolders = cm?.data.copyrightHolder?.map((p) => toPersonOrOrgLd({
		affiliation: p.affiliation,
		email: p.email,
		familyName: p.familyName,
		givenName: p.givenName,
		id: p.id,
		name: p.name,
		type: p.type,
		url: p.url
	}));
	const copyrightHolder = resolvePersonsOrOrgs(ecosystemCopyrightHolders, cmCopyrightHolders);
	const funder = resolvePersonsOrOrgs([], cm?.data.funder?.map((p) => toPersonOrOrgLd({
		affiliation: p.affiliation,
		email: p.email,
		familyName: p.familyName,
		givenName: p.givenName,
		id: p.id,
		name: p.name,
		type: p.type,
		url: p.url
	})));
	const codeRepository = github?.data.url ?? cargo?.data.repository ?? pom?.data.scmUrl ?? goMod?.data.repository_url ?? publiccode?.data.url ?? arduino?.data.repository ?? cinder?.data.git ?? cm?.data.codeRepository ?? repositoryUrlFromPackageJson(package_?.data.repository) ?? caseInsensitiveLookup(pyproject?.data.project?.urls, "repository") ?? poetry?.repository;
	const programmingLanguage = nonEmpty([...github?.data.primaryLanguage ? [github.data.primaryLanguage] : [], ...cm?.data.programmingLanguage ?? []]) ?? nonEmpty(Object.keys(github?.data.languages ?? {})) ?? loc?.data.total?.languages.slice(0, 1);
	const runtimePlatform = nonEmpty([
		...Object.keys(package_?.data.engines ?? {}),
		...goMod?.data.go_version ? [`go ${goMod.data.go_version}`] : [],
		...cargo?.data.rustVersion ? [`rust ${cargo.data.rustVersion}`] : [],
		...pyproject?.data.project?.requiresPython ? [`python ${pyproject.data.project.requiresPython}`] : [],
		...setupPy?.data.python_requires ? [`python ${setupPy.data.python_requires}`] : [],
		...gem?.data.required_ruby_version ? [`ruby ${gem.data.required_ruby_version}`] : [],
		...pom?.data.javaVersion ? [`java ${pom.data.javaVersion}`] : [],
		...cm?.data.runtimePlatform ?? []
	]);
	const operatingSystem = nonEmpty([
		...cm?.data.operatingSystem ?? [],
		...publiccode?.data.platforms ?? [],
		...ofInstall?.data.operatingSystems ?? [],
		...cinder?.data.supports ?? [],
		...xcode?.data.operatingSystems ?? []
	]);
	const applicationCategory = cm?.data.applicationCategory ?? xcode?.data.applicationCategory ?? arduino?.data.category ?? publiccode?.data.softwareType;
	const applicationSubCategory = cm?.data.applicationSubCategory;
	const runtimeDeps = collectRuntimeDeps({
		arduino,
		cargo,
		cinder,
		gem,
		goGoMod,
		javaPomXml,
		nodePackageJson,
		ofAddon,
		ofInstall,
		pkgInfo,
		publiccode,
		pyproject,
		rubyGemspec,
		setupCfg,
		setupPy
	});
	const softwareRequirements = runtimeDeps.length > 0 ? deduplicateDependencies(runtimeDeps) : cm?.data.softwareRequirements?.map((d) => toDependencyLd(d.name ?? d.identifier ?? "", d.version, d.identifier, d.runtimePlatform));
	const developmentDeps = collectDevelopmentDeps({
		cargo,
		gem,
		javaPomXml,
		nodePackageJson,
		rubyGemspec
	});
	const softwareSuggestions = developmentDeps.length > 0 ? deduplicateDependencies(developmentDeps) : cm?.data.softwareSuggestions?.map((d) => toDependencyLd(d.name ?? d.identifier ?? "", d.version, d.identifier, d.runtimePlatform));
	const dateCreated = git?.data.commitDateFirst ?? github?.data.createdAt ?? cm?.data.dateCreated;
	const dateModified = git?.data.commitDateLast ?? github?.data.pushedAt ?? cm?.data.dateModified;
	const datePublished = npm?.data.publishDateLatest ?? pypi?.data.publishDateLatest ?? publiccode?.data.releaseDate ?? github?.data.releaseDateLatest ?? git?.data.tagVersionDateLatest ?? cm?.data.datePublished;
	const copyrightYear = xcode?.data.copyrightYear ?? pom?.data.inceptionYear ?? (cm?.data.copyrightYear === void 0 ? void 0 : String(cm.data.copyrightYear));
	const rawLicense = package_?.data.license ?? cargo?.data.license ?? resolvePythonLicense(pyproject?.data.project?.license) ?? setupPy?.data.license ?? setupCfg?.data.license ?? gem?.data.license ?? firstPomLicense(pom) ?? arduino?.data.license ?? cinder?.data.license ?? publiccode?.data.license ?? github?.data.licenseSpdxId ?? collectField(licenseFile, (d) => d.spdxId)[0] ?? resolveCmLicense(cm?.data.license);
	const license = is.nonEmptyStringAndNotWhitespace(rawLicense) ? toSpdxLicenseUrl(rawLicense) : void 0;
	const isAccessibleForFree = cm?.data.isAccessibleForFree ?? (github?.data.isPrivate === false ? true : void 0);
	const keywords = nonEmpty(deduplicateStrings([
		...package_?.data.keywords ?? [],
		...pyproject?.data.project?.keywords ?? [],
		...poetry?.keywords ?? [],
		...setupPy?.data.keywords ?? [],
		...setupCfg?.data.keywords ?? [],
		...pkgInfo?.data.keywords ?? [],
		...cargo?.data.keywords ?? [],
		...ofAddon?.data.tags ?? [],
		...publiccode?.data.categories ?? [],
		...github?.data.topics ?? [],
		...cm?.data.keywords ?? []
	]));
	const url = stripReadmeFragment(package_?.data.homepage) ?? caseInsensitiveLookup(pyproject?.data.project?.urls, "homepage") ?? poetry?.homepage ?? cargo?.data.homepage ?? setupPy?.data.url ?? setupCfg?.data.url ?? pkgInfo?.data.home_page ?? gem?.data.homepage ?? pom?.data.url ?? arduino?.data.url ?? processing?.data.url ?? ofAddon?.data.url ?? ofInstall?.data.siteUrl ?? cinder?.data.url ?? xcode?.data.url ?? publiccode?.data.landingUrl ?? github?.data.homepageUrl ?? cm?.data.url ?? caseInsensitiveLookup(pyproject?.data.project?.urls, "repository") ?? poetry?.repository;
	const downloadUrl = ofInstall?.data.downloadUrl ?? processing?.data.download ?? npm?.data.url ?? pypi?.data.url ?? cm?.data.downloadUrl;
	const issueTracker = bugsUrlFromPackageJson(package_?.data.bugs) ?? pom?.data.issueManagementUrl ?? cm?.data.issueTracker ?? (github?.data.hasIssuesEnabled ? `${github.data.url}/issues` : void 0);
	const continuousIntegration = pom?.data.ciManagementUrl ?? cm?.data.continuousIntegration;
	const softwareHelp = cargo?.data.documentation ?? cm?.data.softwareHelp;
	const developmentStatus = publiccode?.data.developmentStatus ?? cm?.data.developmentStatus;
	const funding = cm?.data.funding;
	const buildInstructions = cm?.data.buildInstructions;
	const readme = readmeUrl(firstOf(readmeFile), codeRepository, github?.data.defaultBranch ?? git?.data.branchCurrent, firstOf(metascope)?.data.options.path) ?? cm?.data.readme;
	const releaseNotes = cm?.data.releaseNotes;
	const installUrl = cm?.data.installUrl;
	const relatedLink = cm?.data.relatedLink;
	const targetProduct = void 0;
	return stripUndefined({
		"@context": "https://w3id.org/codemeta/3.0",
		"@type": "SoftwareSourceCode",
		applicationCategory,
		applicationSubCategory,
		author,
		buildInstructions,
		codeRepository,
		continuousIntegration,
		contributor,
		copyrightHolder,
		copyrightYear: is.nonEmptyStringAndNotWhitespace(copyrightYear) ? Number.parseInt(copyrightYear, 10) || void 0 : void 0,
		dateCreated: toDateOnly(dateCreated),
		dateModified: toDateOnly(dateModified),
		datePublished: toDateOnly(datePublished),
		description,
		developmentStatus,
		downloadUrl,
		funder,
		funding,
		identifier,
		installUrl,
		isAccessibleForFree,
		issueTracker,
		keywords,
		license,
		maintainer,
		name,
		operatingSystem,
		programmingLanguage,
		readme,
		relatedLink,
		releaseNotes,
		runtimePlatform,
		softwareHelp,
		softwareRequirements,
		softwareSuggestions,
		targetProduct,
		url,
		version
	});
});
/**
* Extract authors from a gemspec record.
* Gemspec has `authors: string[]` and a separate `email: string | string[]`.
* We pair them by index where possible.
*/
function gemspecAuthors(gem) {
	if (gem === void 0) return [];
	const emails = gem.data.email === void 0 ? [] : Array.isArray(gem.data.email) ? gem.data.email : [gem.data.email];
	return gem.data.authors.map((authorName, index) => toPersonOrOrgLd({
		email: emails[index],
		name: authorName
	}));
}
/**
* Takes ecosystem persons (which may include undefined) and codemeta fallback persons.
* Uses ecosystem if any are present, otherwise falls back.
* Always deduplicates by name.
*/
function resolvePersonsOrOrgs(ecosystemPersons, fallbackPersons) {
	const ecosystem = ecosystemPersons.filter((p) => p !== void 0);
	if (ecosystem.length > 0) return deduplicatePersonsOrOrgs(ecosystem);
	return deduplicatePersonsOrOrgs((fallbackPersons ?? []).filter((p) => p !== void 0));
}
/**
* Collect runtime dependencies from all ecosystem sources.
*/
function collectRuntimeDeps(sources) {
	const deps = [];
	deps.push(...collectArrayField(sources.nodePackageJson, (d) => objectEntriesToDeps(d.dependencies)));
	deps.push(...(sources.pyproject?.data.project?.dependencies ?? []).map((dep) => parsePep508Dep(dep)));
	deps.push(...(sources.setupPy?.data.install_requires ?? []).map((dep) => parsePep508Dep(dep)));
	deps.push(...(sources.setupCfg?.data.install_requires ?? []).map((dep) => parsePep508Dep(dep)));
	deps.push(...(sources.pkgInfo?.data.requires_dist ?? []).map((dep) => parsePep508Dep(dep)));
	deps.push(...(sources.cargo?.data.dependencies ?? []).map((d) => toDependencyLd(d.name, d.version)));
	deps.push(...collectArrayField(sources.rubyGemspec, (d) => d.dependencies.filter((dep) => dep.type === "runtime").map((dep) => toDependencyLd(dep.name, dep.requirements.join(", ")))));
	deps.push(...collectArrayField(sources.javaPomXml, (d) => d.dependencies.map((dep) => toDependencyLd(dep.artifactId, dep.version, `${dep.groupId}:${dep.artifactId}`))));
	deps.push(...collectArrayField(sources.goGoMod, (d) => d.dependencies.map((dep) => toDependencyLd(dep.module, dep.version))));
	deps.push(...(sources.arduino?.data.depends ?? []).map((d) => toDependencyLd(d.name, d.versionConstraint)));
	deps.push(...(sources.ofAddon?.data.dependencies ?? []).map((d) => toDependencyLd(d)));
	deps.push(...(sources.ofInstall?.data.requirements ?? []).map((d) => toDependencyLd(d)));
	deps.push(...(sources.cinder?.data.requires ?? []).map((d) => toDependencyLd(d)));
	deps.push(...(sources.publiccode?.data.dependencies ?? []).map((d) => toDependencyLd(d.name, d.version)));
	return deps;
}
/**
* Collect dev dependencies from ecosystem sources.
*/
function collectDevelopmentDeps(sources) {
	const deps = [];
	deps.push(...collectArrayField(sources.nodePackageJson, (d) => objectEntriesToDeps(d.devDependencies)));
	deps.push(...(sources.cargo?.data.devDependencies ?? []).map((d) => toDependencyLd(d.name, d.version)));
	deps.push(...collectArrayField(sources.rubyGemspec, (d) => d.dependencies.filter((dep) => dep.type === "development").map((dep) => toDependencyLd(dep.name, dep.requirements.join(", ")))));
	deps.push(...collectArrayField(sources.javaPomXml, (d) => d.devDependencies.map((dep) => toDependencyLd(dep.artifactId, dep.version, `${dep.groupId}:${dep.artifactId}`))));
	return deps;
}
/**
* Convert a Record<name, version> dependency map to CodemetaDependencyLd[].
*/
function objectEntriesToDeps(deps) {
	if (deps === void 0) return void 0;
	return Object.entries(deps).map(([depName, depVersion]) => toDependencyLd(depName, depVersion));
}
/**
* Parse a PEP 508 dependency string ("package>=1.0") into a CodemetaDependencyLd.
*/
function parsePep508Dep(dep) {
	const trimmed = dep.trim();
	const nameMatch = /^[\w.-]+/.exec(trimmed);
	if (nameMatch) {
		const depVersion = trimmed.slice(nameMatch[0].length).trim();
		return toDependencyLd(nameMatch[0], depVersion.length > 0 ? depVersion : void 0);
	}
	return toDependencyLd(trimmed);
}
/**
* Extract URL from package.json repository field (string or {url}).
*/
function repositoryUrlFromPackageJson(repository) {
	if (repository === void 0) return void 0;
	if (typeof repository === "string") return repository;
	return repository.url;
}
/**
* Extract URL from package.json bugs field.
*/
function bugsUrlFromPackageJson(bugs) {
	if (bugs === void 0) return void 0;
	return bugs.url;
}
/**
* Extract the first license name from a POM record.
*/
function firstPomLicense(pom) {
	const pomLicense = pom?.data.licenses[0];
	return pomLicense?.name ?? pomLicense?.url;
}
/**
* Resolve Python pyproject.toml license field to a string.
* Can be a string (SPDX ID) or `{ spdx?: string; text?: string; file?: string }`.
*/
function resolvePythonLicense(pythonLicense) {
	if (pythonLicense === void 0) return void 0;
	if (typeof pythonLicense === "string") return pythonLicense;
	return pythonLicense.spdx ?? pythonLicense.text;
}
/**
* Resolve codemeta license field (string or string[]) to first string.
*/
function resolveCmLicense(cmLicense) {
	if (cmLicense === void 0) return void 0;
	return Array.isArray(cmLicense) ? cmLicense[0] : cmLicense;
}
/**
* Deduplicate strings case-insensitively, preserving first occurrence casing.
*/
function deduplicateStrings(strings) {
	const seen = /* @__PURE__ */ new Map();
	for (const s of strings) {
		const key = s.toLowerCase().trim();
		if (key.length > 0 && !seen.has(key)) seen.set(key, s);
	}
	return [...seen.values()];
}
/**
* Case-insensitive lookup in a string record (e.g. pyproject.toml `[project.urls]`).
*/
function caseInsensitiveLookup(record, key) {
	if (record === void 0) return void 0;
	const lowerKey = key.toLowerCase();
	for (const [k, v] of Object.entries(record)) if (k.toLowerCase() === lowerKey) return v;
}
/**
* Strip the `#readme` fragment that npm's normalize-package-data appends to
* homepage URLs derived from repository URLs.
*/
function stripReadmeFragment(url) {
	if (url === void 0) return void 0;
	return url.endsWith("#readme") ? url.slice(0, -7) : url;
}
/**
* Truncate an ISO 8601 date-time to just the date portion (YYYY-MM-DD).
* CodeMeta dates are `schema:Date`, not `schema:DateTime`.
*/
function toDateOnly(value) {
	if (value === void 0) return void 0;
	if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return value;
	const match = /^(\d{4}-\d{2}-\d{2})T/.exec(value);
	if (match) return match[1];
	return value;
}
/**
* Build a URL for the project's README.
* Prefers a web URL on the remote service (e.g. GitHub blob link) when a
* code repository URL is available, otherwise falls back to the local source path.
*/
function readmeUrl(readmeRecord, repoUrl, defaultBranch, basePath) {
	if (readmeRecord === void 0) return void 0;
	const repoRelativePath = basePath === void 0 ? basename(readmeRecord.source) : relative(basePath, readmeRecord.source).replaceAll("\\", "/");
	if (is.nonEmptyStringAndNotWhitespace(repoUrl) && repoUrl.includes("github.com")) {
		const branch = defaultBranch ?? "main";
		return `${repoUrl.replace(/\.git$/, "")}/blob/${branch}/${repoRelativePath}`;
	}
	return repoRelativePath;
}
//#endregion
export { codemeta };
