package DhMakeRaku::RakudoStar;

# ABSTRACT: add dependency in raku for Rakudo Star modules

use v5.20;
use strict;
use warnings;
use autodie qw(:all);

use Exporter qw/import/;

use Path::Tiny;
use HTTP::Tiny;
use Config::Model qw/cme/;

use feature qw/signatures/;
no warnings qw/experimental::signatures/;

our @EXPORT_OK = qw/is_star_module star_module_version add_dep_in_raku_pkg/;

my $rk_star_list_url = "https://github.com/rakudo/star/raw/master/etc/modules.txt";
my $http = HTTP::Tiny->new();

sub get_rk_star_file () {
    my $resp = $http->get($rk_star_list_url);
    if ($resp->{success}) {
        return $resp->{content};
    }
    else {
        die "Request to $rk_star_list_url failed ($resp->{status}) with response:\n$resp->{reason}\n";
    }
}

# content is used for test
sub get_rk_star_data ($content = '') {
    state $data;

    return $data if $data;

    my $file = $content || get_rk_star_file;

    # remove comments
    $file =~ s/#.*//g;

    # remove empty lines
    $file =~ s/\n+/\n/g;

    # remove first empty line
    $file =~ s/^\n//;

    foreach my $line (split /\n+/,$file) {
        my ($name, $protocol, $url, $version) = split /\s+/, $line;
        # remove non debian part from version number
        $version =~ s/^v//;
        # tweak $name to match Debian conventions
        $data->{"raku-".lc($name)} = $version;
    }
    return $data;
}

sub is_star_module($name) {
    return  get_rk_star_data()->{$name} ? 1 : 0;
}

sub star_module_version($name) {
    return  get_rk_star_data()->{$name};
}

sub add_dep_in_raku_pkg ($name, $version, $path = '../../raku') {
    my $dep = $version =~ /master|main/ ? '' : " (>= $version)";

    my $path_o = path($path);
    if ($path_o->exists) {
        my $instance = cme (
            application => 'dpkg-control',
            name => 'raku',
            root_dir => $path
        );

        say "Checking raku control file for dependency '$name$dep' (may trigger a warning)...";
        # add the dependency in control file with a version constraint
        # that may not be required
        $instance->load(qq!binary:raku Depends:.ensure("$name$dep")!);

        say "fix potential version constraint in raku dependencies...";
        $instance->apply_fixes;

        say "writing back raku's control file...";
        $instance->write_back;
    }
    else {
        say "Could not find raku package file. Skipping dependency check..."
    }
}

1;
