#!/usr/bin/env perl
use 5.024;
use warnings;
use utf8;

use Data::Dump qw( pp );
use LWP::Authen::OAuth2;
use JSON qw( decode_json encode_json );

my $profileid = 2138280;
my $ladderid = 213977;

my $bliz = LWP::Authen::OAuth2->new(
	client_id               => '7f0f95ac9529474f854ee8d68a12c3e0',
	client_secret           => 'Kfa8n98UAaDo4brOeqxe9C2kJE9pqpSd',
	token_endpoint          => 'https://us.battle.net/oauth/token',
	request_required_params => [qw( client_id client_secret grant_type scope )],
);
$bliz->request_tokens(
	scope => 'account.public',
	grant_type => 'client_credentials',
);

sub blizget {
	my $args = join('/', @_);
	my $res = $bliz->get("https://us.api.blizzard.com/sc2/$args");
	$res->is_success or die $res->status_line;
	my $json = $res->decoded_content;
	return decode_json($json);
}

my $ladder = blizget(profile => 2 => 1 => $profileid => ladder => $ladderid);
my $team = $ladder->{ladderTeams}->[ $ladder->{ranksAndPools}->[0]->{rank} - 1 ];

say encode_json({
	league   => $ladder->{currentLadderMembership}->{localizedGameMode},
	division => $ladder->{localizedDivision},
	mmr      => $team->{mmr},
	members  => $team->{teamMembers},
	members_ => [map { blizget(metadata => profile => 2 => 1 => $_->{id}) } $team->{teamMembers}->@*],
});
