<?php

$sections = json_decode(file_get_contents("docs.json"), true);

$output = "";

function replaceDocs($comment, $section) {
	return preg_replace_callback('/@docs\s+(.+)/mu', function ($matches) use ($section) {
		$tokens = array_map('trim', explode(',', $matches[1]));


		$functions = array_column($section['values'], 'comment', 'name');
		$functionTypes = array_column($section['values'], 'type', 'name');

		$aliases = array_column($section['aliases'], 'comment', 'name');
		$aliasTypes = array_column($section['aliases'], 'type', 'name');

		$types = array_column($section['types'], 'comment', 'name');
		$typeDefinitions = array_column($section['types'], 'cases', 'name');
		$output = "";

		foreach ($tokens as $token) {
			if (isset($aliases[$token])) {
				$type = $aliasTypes[$token];
				$comment = trim($aliases[$token]);
				$output .= "```elm\ntype alias $token = \n";
				$output .= "  $type\n```\n\n$comment";
			}

			if (isset($functions[$token])) {
				$type = formatSignature($functionTypes[$token]);
				$comment = trim($functions[$token]);
				$output .= "```elm\n$token : $type\n```\n\n$comment";
			}

			if (isset($types[$token])) {
				$output .= formatType($token, $types[$token], $typeDefinitions[$token]);
			}

			$output .= "\n\n---\n";
		}


		return $output;
	}, $comment);
}

function formatSignature($signature) {
	$parts = array_map('trim', explode("->", $signature));
	if (count($parts) > 3 || strlen($signature) > 110) {
		$signature = array_map(function ($p) {
			if ($p[0] === "(") {
				return $p . " -> ";
			}
			return $p . "\n    -> ";
		}, $parts);
		$signature = implode("", $signature);
		$signature = trim($signature, "\n ->");
	}

	return $signature;
}

function formatType($name, $comment, $cases) {
	$output = "";
	$output .= "```elm\ntype $name\n";
	$output .= "    = ";

	$firstCase = $cases[0] ?? $name;
	$cases = array_slice($cases, 1);

	$output .= $name;
	foreach ($cases as $case) {
		$case = $case[0] . " " . ($case[1][0] ?? "");
		$output .= "\n    | $case";
	}

	$output .= "\n```\n\n";
	$output .= trim($comment);
	return $output;
}

foreach ($sections as $section) {
	$output .= "#" . $section['name'] . "\n\n";
	$output .= replaceDocs($section['comment'], $section);
	$output .= "\n\n---\n\n";
}

echo $output;
