export const prerender = true;
---
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
import ChangelogEntries from '@components/ChangelogEntries.astro';
import { getCollection } from 'astro:content';
import { getLatestRelease } from '@lib/github';
import { sidebar } from '../../data/sidebar';

const showUnreleased = import.meta.env.DEV;

const releaseData = await getLatestRelease('gruntwork-io', 'terragrunt');
const latestVersion = (releaseData?.tag_name ?? 'v0.0.0').replace(/^v/, '');

function isReleased(version: string): boolean {
	if (!version.startsWith("v")) return false;
	const v = version.replace(/^v/, "");
	return v.localeCompare(latestVersion, undefined, { numeric: true }) <= 0;
}

const allEntries = await getCollection('changelog');

// Sort by version descending, with non-semver entries (e.g. "Unreleased") always first
allEntries.sort((a, b) => {
	const aIsVersion = a.data.version.startsWith("v");
	const bIsVersion = b.data.version.startsWith("v");
	if (!aIsVersion && bIsVersion) return -1;
	if (aIsVersion && !bIsVersion) return 1;
	return b.data.version.localeCompare(a.data.version, undefined, { numeric: true });
});

const visibleEntries = showUnreleased
	? allEntries
	: allEntries.filter((entry) => isReleased(entry.data.version));

// Build TOC headings from visible entries only
const headings: { depth: number; slug: string; text: string }[] = [];

for (const entry of visibleEntries) {
	const version = entry.data.version;
	headings.push({ depth: 2, slug: version, text: version });

	// Extract ### headings (categories) from the body
	const categoryLines = entry.body?.match(/^### .+/gm) ?? [];
	for (const line of categoryLines) {
		const text = line.replace(/^### /, '');
		const slug = text
			.toLowerCase()
			.replace(/[^\w\s-]/g, '')
			.trim()
			.replace(/\s+/g, '-');
		headings.push({ depth: 3, slug, text });
	}
}

headings.push({ depth: 2, slug: 'prior-releases', text: 'Prior Releases' });
---

<StarlightPage
	frontmatter={{
		title: 'Changelog',
		description: 'A log of notable changes to Terragrunt.',
	}}
	headings={headings}
	sidebar={sidebar}
>
	<p>This page tracks notable changes to Terragrunt. For the full list of releases and their assets, see the <a href="https://github.com/gruntwork-io/terragrunt/releases">GitHub Releases Page</a>.</p>
	<hr />
	<ChangelogEntries showUnreleased={showUnreleased} />
	<h2 id="prior-releases">Prior Releases</h2>
	<p>For all prior releases, see the <a href="https://github.com/gruntwork-io/terragrunt/releases">GitHub Releases Page</a>.</p>
</StarlightPage>
