package System::Introspector::Config;
use Moo;
use Config::General;

has config => (is => 'lazy');

has config_file => (is => 'ro', required => 1);

sub _build_config {
    my ($self) = @_;
    my $reader = Config::General->new($self->config_file);
    my %config = $reader->getall;
    return \%config;
}

sub sudo_user { $_[0]->config->{sudo_user} }

sub groups { keys %{ $_[0]->config->{group} || {} } }

sub has_group { exists $_[0]->config->{group}{ $_[1] } }

sub hosts {
    my ($self) = @_;
    my $host_spec = $self->config->{host};
    return ref($host_spec) ? @$host_spec : $host_spec;
}

sub user { $_[0]->config->{user} }

my $_get_inherited = sub {
    my $data = shift;
    $data ||= {};
    return
        map  { ($_ => $data->{$_}) }
        grep { exists $data->{$_} }
        qw( sudo );
};

sub config_for_group {
    my ($self, $name) = @_;
    my %common;
    my $config = $self->config;
    %common = (%common, $config->$_get_inherited);
    my $group = $config->{group}{ $name };
    %common = (%common, $group->$_get_inherited);
    return {
        introspect => {
            map {
                ($_ => {
                    %common,
                    %{ $group->{introspect}{ $_ } || {} },
                });
            } keys %{ $group->{introspect} || {} },
        },
    };
}

1;
