#!/usr/bin/perl
# Expand the @data classes of lm-coursier as upstream's dataclass-scalafix
# rule (GenerateDataClass 0.3.0, Apache-2.0) does, for Scala 3: upstream
# runs that rule through sbt-scalafix, which Debian does not have.
# Usage: dataclass-gen <out-dir> <file.scala>...
# Each output file keeps the input's path below "scala/".
# Copyright 2026 Juan Manuel Mendez Rey <juan.mendezr@proton.me>
# License: Apache-2.0
use strict;
use warnings;
use File::Basename qw(dirname);
use File::Path qw(make_path);

my $out = shift or die "usage: $0 <out-dir> <file.scala>...\n";

# Split $s on commas at nesting depth 0.
sub split_top {
	my ($s) = @_;
	my (@parts, $cur, $depth, $q);
	($cur, $depth, $q) = ('', 0, '');
	for my $c (split //, $s) {
		if ($q) { $q = '' if $c eq $q; $cur .= $c; next }
		if ($c eq '"' || $c eq '`') { $q = $c; $cur .= $c; next }
		$depth++ if $c =~ /[(\[{]/;
		$depth-- if $c =~ /[)\]}]/;
		if ($c eq ',' && $depth == 0) { push @parts, $cur; $cur = ''; next }
		$cur .= $c;
	}
	push @parts, $cur if $cur =~ /\S/;
	return @parts;
}

# Index of the bracket closing the one opening at $i.
sub closing {
	my ($s, $i) = @_;
	my ($depth, $q) = (0, '');
	for (my $j = $i; $j < length $s; $j++) {
		my $c = substr($s, $j, 1);
		if ($q) { $q = '' if $c eq $q; next }
		if ($c eq '"') { $q = $c; next }
		$depth++ if $c =~ /[(\[{]/;
		$depth-- if $c =~ /[)\]}]/;
		return $j if $depth == 0;
	}
	die "unbalanced brackets\n";
}

sub trim { my ($s) = @_; $s =~ s/^\s+|\s+$//g; return $s }

sub gen_class {
	my ($name, $params, $ext, $body) = @_;
	my @p;
	$params =~ s{//[^\n]*}{}g;
	for my $raw (split_top($params)) {
		my $t = trim($raw);
		my $since = '';
		$since = $1 while $t =~ s/^(\@since(?:\("[^"]*"\))?)\s*//;
		$t =~ /^(`[^`]+`|\w+)\s*:\s*(.*)$/s or die "cannot parse parameter '$t'\n";
		my ($n, $rest) = ($1, $2);
		my ($type, $def) = ($rest, undef);
		my @td = split_eq($rest);
		($type, $def) = @td if @td == 2;
		push @p, { name => $n, type => trim($type), default => defined $def ? trim($def) : undef, since => $since };
	}
	my @f = map { $_->{name} } @p;
	my $plain = sub { my $x = $_[0]; $x =~ s/`//g; $x };
	my $ctor = join(', ', map { "val $_->{name}: $_->{type}" } @p);
	my $c = "final class $name private ($ctor) extends "
	  . join(' with ', grep { length } ($ext, 'Product', 'Serializable')) . " {\n\n";
	my %existing = map { $_ => 1 } ($body =~ /\bdef\s+(\w+)/g);
	$c .= "override def equals(obj: Any): Boolean = obj match {\n  case c: $name =>\n    "
	  . join(' && ', map { "this.$_ == c.$_" } @f) . "\n  case _ =>\n    false\n}\n";
	$c .= "override lazy val hashCode: Int = {\n  val state = Seq(" . join(', ', @f)
	  . ")\n  state.foldLeft(0)((a, b) => 31 * a.hashCode() + b.hashCode())\n}\n";
	$c .= "private def copy(" . join(', ', map { "$_->{name}: $_->{type} = this.$_->{name}" } @p)
	  . "): $name = new $name(" . join(', ', @f) . ")\n";
	$c .= "override def canEqual(obj: Any): Boolean = obj match {\n  case c: $name => true\n  case _ => false\n}\n";
	$c .= "override def productArity = " . scalar(@f) . "\n";
	my $i = 0;
	$c .= "override def productElement(n: Int) = n match {\n"
	  . join('', map { "  case " . $i++ . " =>\n    $_\n" } @f)
	  . "  case _ =>\n    throw new IndexOutOfBoundsException()\n}\n";
	$i = 0;
	$c .= "override def productElementName(n: Int) = n match {\n"
	  . join('', map { "  case " . $i++ . " =>\n    \"" . $plain->($_) . "\"\n" } @f)
	  . "  case _ =>\n    throw new IndexOutOfBoundsException()\n}\n";
	$c .= "override def productElementNames = {\n  Iterator(" . join(', ', map { '"' . $plain->($_) . '"' } @f) . ")\n}\n";
	$c .= "override def productIterator = {\n  Iterator(" . join(', ', @f) . ")\n}\n";
	$c .= "override def productPrefix = \"$name\"\n";
	for my $q (@p) {
		my $pn = $plain->($q->{name});
		$c .= "def with\u$pn($q->{name}: $q->{type}): $name = copy($q->{name} = $q->{name})\n";
	}
	$c .= "override def toString = {\n  val sb = new StringBuilder(\"$name\")\n"
	  . "  sb.append(productElementNames.zip(productIterator).map {\n    case (name, value) =>\n"
	  . "      s\"\$name=\$value\"\n  }.mkString(\"(\", \",\", \")\"))\n  sb.toString\n}\n"
	  unless $existing{toString};
	$c .= "\n$body\n}\n";

	# Companion: the full apply, one per @since prefix, one without defaults.
	my @sinces = do { my %s; grep { !$s{$_}++ } sort map { $_->{since} } @p };
	my @sets;
	if (@sinces > 1) {
		for my $k (0 .. $#sinces) {
			my %sub = map { $_ => 1 } @sinces[0 .. $k];
			push @sets, [grep { $_->{since} eq '' || $sub{ $_->{since} } } @p];
		}
	}
	push @sets, [grep { !defined $_->{default} } @p] if grep { defined $_->{default} } @p;
	my (%seen, @rest);
	for my $s (@sets) {
		my $key = join(',', map { $_->{name} } @$s);
		next if $seen{$key}++ || @$s == @p;
		push @rest, $s;
	}
	my $o = "object $name {\n";
	$o .= "def apply(" . join(', ', map { "$_->{name}: $_->{type}" } @p) . "): $name = new $name(" . join(', ', @f) . ")\n";
	for my $s (@rest) {
		my %in = map { $_->{name} => 1 } @$s;
		my @args = map {
			$in{ $_->{name} } ? $_->{name}
			  : (defined $_->{default} ? $_->{default} : die "default value missing for $_->{name}\n")
		} @p;
		$o .= "def apply(" . join(', ', map { "$_->{name}: $_->{type}" } @$s) . "): $name = new $name(" . join(', ', @args) . ")\n";
	}
	$o .= "}\n";
	return "$c$o";
}

# Split "Type = default" at the first top-level '='.
sub split_eq {
	my ($s) = @_;
	my ($depth, $q) = (0, '');
	for (my $j = 0; $j < length $s; $j++) {
		my $c = substr($s, $j, 1);
		if ($q) { $q = '' if $c eq $q; next }
		if ($c eq '"') { $q = $c; next }
		$depth++ if $c =~ /[(\[{]/;
		$depth-- if $c =~ /[)\]}]/;
		if ($c eq '=' && $depth == 0 && substr($s, $j + 1, 1) ne '>' && substr($s, $j - 1, 1) !~ /[=<>!]/) {
			return (substr($s, 0, $j), substr($s, $j + 1));
		}
	}
	return ($s);
}

for my $file (@ARGV) {
	open(my $fh, '<', $file) or die "$file: $!\n";
	my $src = do { local $/; <$fh> };
	close $fh;
	$src =~ s/^import dataclass\b.*\n//mg;
	$src =~ s/^(import [\w.]+\.)\{\s*data\s*,\s*since\s*\}\n//mg;
	my $res = '';
	while ($src =~ /\@data\s+class\s+(\w+)\s*\(/g) {
		my ($name, $start, $open) = ($1, $-[0], $+[0] - 1);
		my $close = closing($src, $open);
		my $params = substr($src, $open + 1, $close - $open - 1);
		my $tail = substr($src, $close + 1);
		my ($ext, $body, $end) = ('', '', $close + 1);
		if ($tail =~ /^\s*extends\s+([\w.\[\], ]+?)\s*(\{|\n)/) {
			$ext = $1;
			$end = $close + 1 + $+[1];
			$tail = substr($src, $end);
		}
		if ($tail =~ /^\s*\{/) {
			my $bo = $end + $-[0] + index(substr($tail, $-[0]), '{');
			my $bc = closing($src, $bo);
			$body = substr($src, $bo + 1, $bc - $bo - 1);
			$end = $bc + 1;
		}
		$res .= substr($src, 0, $start) . gen_class($name, $params, $ext, $body);
		$src = substr($src, $end);
		pos($src) = 0;
	}
	$res .= $src;
	(my $rel = $file) =~ s{^.*?/scala/}{};
	my $dest = "$out/$rel";
	make_path(dirname($dest));
	open(my $oh, '>', $dest) or die "$dest: $!\n";
	print $oh $res;
	close $oh;
}
