use JSON::PP;

# ESPN Standings Handler
# Parses JSON from ESPN's public standings API
# Usage: extractTags( espn_standings, "nhl|nba|mlb|efl" );

sub espn_standings
{
    my $json_text = shift;
    my $league = shift || 'nhl';
    my @rValue = ();

    # Debug
    # print "------------------ espn_standings ($league) --------------------\n";

    my $json;
    eval {
        $json = JSON::PP->new->decode($json_text);
    };
    if ($@) {
        print "JSON parse error: $@\n";
        return @rValue;
    }

    # Navigate to entries - structure varies slightly by league
    my $entries = [];

    if ($json->{children} && ref($json->{children}) eq 'ARRAY') {
        # Most leagues have children (conferences/divisions)
        foreach my $child (@{$json->{children}}) {
            if ($child->{standings} && $child->{standings}->{entries}) {
                push @$entries, @{$child->{standings}->{entries}};
            }
        }
    }

    # Sort by points (NHL, EFL) or win percentage (NBA, MLB) - descending
    @$entries = sort {
        my $a_pts = get_stat($a, 'points') || 0;
        my $b_pts = get_stat($b, 'points') || 0;
        my $a_pct = get_stat($a, 'winPercent') || 0;
        my $b_pct = get_stat($b, 'winPercent') || 0;

        # For NHL and EFL, sort by points; for NBA and MLB, sort by win %
        if ($a_pts > 0 || $b_pts > 0) {
            return $b_pts <=> $a_pts;  # Higher points first
        } else {
            return $b_pct <=> $a_pct;  # Higher win % first
        }
    } @$entries;

    my $count = 0;
    foreach my $entry (@$entries) {
        last if $count >= 12;  # Top 12 teams

        my $team = $entry->{team};
        next unless $team;

        my $team_name = $team->{shortDisplayName} || $team->{displayName} || 'Unknown';
        my $abbrev = $team->{abbreviation} || '';

        my %record;

        if ($league eq 'nhl') {
            my $wins = get_stat($entry, 'wins') || 0;
            my $losses = get_stat($entry, 'losses') || 0;
            my $otl = get_stat($entry, 'otLosses') || get_stat($entry, 'overtimeLosses') || 0;
            my $pts = get_stat($entry, 'points') || 0;

            %record = (
                'rank' => $count + 1,
                'team' => $team_name,
                'abbrev' => $abbrev,
                'record' => "$wins-$losses-$otl",
                'stat' => $pts,
                'stat_label' => 'PTS'
            );
        }
        elsif ($league eq 'nba') {
            my $wins = get_stat($entry, 'wins') || 0;
            my $losses = get_stat($entry, 'losses') || 0;
            my $pct = get_stat($entry, 'winPercent') || 0;
            $pct = sprintf("%.3f", $pct);
            $pct =~ s/^0//;  # .500 not 0.500

            %record = (
                'rank' => $count + 1,
                'team' => $team_name,
                'abbrev' => $abbrev,
                'record' => "$wins-$losses",
                'stat' => $pct,
                'stat_label' => 'PCT'
            );
        }
        elsif ($league eq 'mlb') {
            my $wins = get_stat($entry, 'wins') || 0;
            my $losses = get_stat($entry, 'losses') || 0;
            my $gb = get_stat_display($entry, 'gamesBehind') || '-';

            %record = (
                'rank' => $count + 1,
                'team' => $team_name,
                'abbrev' => $abbrev,
                'record' => "$wins-$losses",
                'stat' => $gb,
                'stat_label' => 'GB'
            );
        }
        elsif ($league eq 'efl') {
            my $wins = get_stat($entry, 'wins') || 0;
            my $draws = get_stat($entry, 'ties') || 0;
            my $losses = get_stat($entry, 'losses') || 0;
            my $pts = get_stat($entry, 'points') || 0;
            my $gd = get_stat_display($entry, 'pointDifferential') || '0';

            %record = (
                'rank' => $count + 1,
                'team' => $team_name,
                'abbrev' => $abbrev,
                'record' => "$wins-$draws-$losses",
                'stat' => $pts,
                'stat_label' => 'PTS',
                'gd' => $gd
            );
        }

        push @rValue, \%record if %record;
        $count++;
    }

    return @rValue;
}

# Helper to get numeric stat value
sub get_stat {
    my ($entry, $stat_name) = @_;
    return undef unless $entry->{stats};

    foreach my $stat (@{$entry->{stats}}) {
        if ($stat->{name} && $stat->{name} eq $stat_name) {
            return $stat->{value};
        }
    }
    return undef;
}

# Helper to get display value of stat
sub get_stat_display {
    my ($entry, $stat_name) = @_;
    return undef unless $entry->{stats};

    foreach my $stat (@{$entry->{stats}}) {
        if ($stat->{name} && $stat->{name} eq $stat_name) {
            return $stat->{displayValue};
        }
    }
    return undef;
}

return 1;
