#!/usr/bin/env bash

declare -A matches_played wins draws losses points

print_table_row() {
    printf '%-30s | %2s | %2s | %2s | %2s | %2s\n' "$@"
}

print_table_row "Team" "MP" "W" "D" "L" "P"

initialize_teams_stats() {
	local team
	for team in "$@"; do
		: "${matches_played[$team]:=0}"
		: "${wins[$team]:=0}"
		: "${draws[$team]:=0}"
		: "${losses[$team]:=0}"
		: "${points[$team]:=0}"
	done
}

initialize_teams_stats "$team1" "$team2"

while IFS= read -r -t1 line; do
    # Break loop if an empty line is encountered
    [ -z "$line" ] && break

    # Parse the input line
    IFS=';' read -r team1 team2 outcome <<<"$line"

    ((matches_played[$team1]++))
    ((matches_played[$team2]++))

    case "$outcome" in
        "win")
            ((wins[$team1]++))
            ((losses[$team2]++))
            ((points[$team1] += 3))
            ;;
        "draw")
            ((draws[$team1]++))
            ((draws[$team2]++))
            ((points[$team1]++))
            ((points[$team2]++))
            ;;
        "loss")
            ((losses[$team1]++))
            ((wins[$team2]++))
            ((points[$team2] += 3))
            ;;
    esac
# Read input from a file or standard input (stdin)
done <"${1:-/dev/stdin}"

# Iterate over teams and print their statistics, sorted by points
for team in "${!matches_played[@]}"; do
    print_table_row "$team" "${matches_played[$team]}" "${wins[$team]}" "${draws[$team]}" "${losses[$team]}" "${points[$team]}"
# Sort the table by points in descending order, then alphabetically by team name
done | sort -t'|' -k6nr,6 -k1,1