package DhMakeRaku::Config;

# ABSTRACT: Manage config of DhMakeRaku

use strict;
use warnings;
use autodie qw(:all);

use Exporter qw/import/;

use Path::Tiny;
use v5.32;
use JSON;
use Git;

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

our @EXPORT_OK = qw/dh_make_raku_config/;

sub internal_config () {
    return {
        api_host          => 'salsa.debian.org',
        api_path          => '/api/v4',
        team_path         => 'perl6-team',
        team_id           => 3275,
        team_modules_path => 'perl6-team/modules',
        team_modules_id   => 3693,
    };
}

sub user_config () {
    return {
        private_token     => '',
        user              => '',
    };
}

sub dh_make_raku_config () {
    my $user_config = user_config;
    read_git_credentials($user_config);
    udpate_config_from_environment($user_config);
    my $internal_config = internal_config;

    return {
        $user_config->%*,
        $internal_config->%*
    };
}

sub read_git_credentials ($config, $file = "~/.git-credentials") {
    # try to get token from ~/.git-credentials
    my $cred = path($file);
    my $host = internal_config()->{api_host};
    if ($cred->is_file) {
        foreach my $line ($cred->lines) {
            if ($line =~ m!https://(\w+):(\w+)\@$host$!) {
                $config->{user} = $1;
                $config->{private_token} = $2;
            }
        }
    }
}

sub udpate_config_from_environment ($config) {
    ## update from environment / config file
    ## this is also exported by drt(1) from ~/.drt.conf / ~/.config/drt.conf
    ## use DRT_SALSA_FOO as $config{foo}
    foreach my $c_key ( keys $config->%* ) {
        my $KEY = 'DRT_SALSA_' . uc($c_key);
        $config->{$c_key} = $ENV{$KEY} if $ENV{$KEY};
    }
}

