#!/usr/bin/env perl
# Converts the documentation of lib/Games/TF2/Demo.pm into docs/api.md and
# that of lib/Games/TF2/Server.pm into docs/server-api.md.
#
#     perl tools/pod2markdown        (or: make readme)
#
# Pod::Markdown with one change: each verbatim block loses the
# indentation its lines share and is fenced. A block whose second line is
# a rule of dashes (a table of the pod) is fenced without a language,
# every other block as perl.
#
# Copyright (C) 2026 davenonymous.
#
# This program is free software; you can redistribute it and/or modify
# it under the same terms as Perl itself.
use v5.26;
use warnings;
use feature qw(signatures);
no warnings qw(experimental::signatures);

# Each pod file with the Markdown file it becomes.
use constant MARKDOWN_OF_POD => (
	[ 'lib/Games/TF2/Demo.pm'   => 'docs/api.md' ],
	[ 'lib/Games/TF2/Server.pm' => 'docs/server-api.md' ],
);

package My::Pod::Markdown {
	use parent 'Pod::Markdown';
	use feature qw(signatures);
	no warnings qw(experimental::signatures);

	die "Pod::Markdown has no _indent_verbatim(); this script needs an update\n"
		unless Pod::Markdown->can('_indent_verbatim');

	# A fenced block without the indentation its lines share.
	sub _indent_verbatim ( $self, $paragraph ) {
		my @lines    = split /\n/, $paragraph;
		my ($indent) = sort { $a <=> $b } map { /\A( *)/; length $1 } grep { /\S/ } @lines;
		$indent //= 0;
		my @code     = map { length > $indent ? substr( $_, $indent ) : '' } @lines;
		my $language = _is_table(@code) ? '' : 'perl';
		return "```$language\n" . join( "\n", @code ) . "\n```";
	}

	# Whether a block is a table: its second line is a rule of dashes,
	# with spaces between the columns.
	sub _is_table (@lines) {
		return @lines > 1 && $lines[1] =~ /\A-+(?: +-+)*\z/;
	}
}

sub convert ( $podFile, $markdownFile ) {
	my $markdown;
	my $parser = My::Pod::Markdown->new( output_encoding => 'UTF-8' );
	$parser->output_string( \$markdown );
	$parser->parse_file($podFile);
	open my $handle, '>:raw', $markdownFile or die "pod2markdown: cannot write $markdownFile: $!\n";
	print {$handle} $markdown or die "pod2markdown: cannot write $markdownFile: $!\n";
	close $handle or die "pod2markdown: cannot write $markdownFile: $!\n";
	return;
}

convert( $_->@* ) foreach MARKDOWN_OF_POD;
