"""Meet the Nobel laureates: analyze MySafeInfo's complete Nobel Prize CSV.
Usage: python nobel-analysis.py nobelwinners.csv [--charts] [--json]
Counting uses only the standard library. Only --charts needs matplotlib. No network requests.
"""
import argparse
import csv
import json
import sys
from collections import Counter, defaultdict
from statistics import median

PRIZES = ["Physics", "Chemistry", "Physiology or Medicine", "Literature", "Peace", "Economic Sciences"]


def read_csv(path):
    with open(path, encoding="utf-8-sig", newline="") as handle:
        return list(csv.DictReader(handle))


def decade(row):
    return int(row["Year"]) // 10 * 10


def analyze(rows):
    # One row is one laureate and one prize. LaureateID is the
    # same on every prize a laureate wins, so it counts each once.
    people = [r for r in rows if r["LaureateType"] == "Person"]
    laureates = {r["LaureateID"] for r in rows}
    organizations = laureates - {r["LaureateID"] for r in people}
    decades = sorted({decade(r) for r in rows})
    by_decade = Counter((decade(r), r["AwardName"]) for r in rows)
    # Each prize category as a share of all prizes.
    by_prize = Counter(r["AwardName"] for r in rows)
    share = {prize: 100 * n / len(rows) for prize, n in by_prize.items()}
    # A laureate honored more than once has more than one row.
    prizes_of = defaultdict(list)
    for r in rows:
        prizes_of[r["LaureateID"]].append(r)
    repeat = [won for won in prizes_of.values() if len(won) > 1]
    repeat.sort(key=lambda won: won[0]["FullName"])
    # AgeAtAward is Year minus BornYear. Organizations have no age.
    ages = defaultdict(list)
    for r in people:
        ages[r["AwardName"]].append(r)
        ages["All prizes"].append(r)
    age = lambda r: int(r["AgeAtAward"])
    youngest = min(people, key=age)
    oldest = max(people, key=age)
    women = [r for r in people if r["Gender"] == "Female"]
    women_by_decade = Counter(decade(r) for r in women)
    people_by_decade = Counter(decade(r) for r in people)
    first = min(women, key=lambda r: int(r["Year"]))
    # BornCountry is the present-day country of the birthplace.
    # AffiliationCountry is where the laureate worked when honored.
    born = Counter(r["BornCountry"] for r in people if r["BornCountry"])
    moved = Counter(r["BornCountry"] for r in people
                    if r["BornCountry"] and r["AffiliationCountry"]
                    and r["BornCountry"] != r["AffiliationCountry"])
    top = sorted(born.items(), key=lambda item: (-item[1], item[0]))[:10]
    return {
        "prizes": len(rows), "laureates": len(laureates), "people": len(laureates) - len(organizations),
        "organizations": len(organizations), "women_laureates": len({r["LaureateID"] for r in women}),
        "youngest": [youngest["FullName"], age(youngest), int(youngest["Year"])],
        "oldest": [oldest["FullName"], age(oldest), int(oldest["Year"])],
        "first_woman": [first["FullName"], int(first["Year"])],
        "decades": {"columns": ["Decade"] + PRIZES, "rows": [[f"{d}s"] + [by_decade[d, p] for p in PRIZES] for d in decades]},
        "share": {"columns": ["Prize", "Prizes", "Share"],
                  "rows": [[p, n, f"{share[p]:.1f}%"] for p, n in sorted(by_prize.items(), key=lambda item: (-item[1], item[0]))]},
        "repeat": {"columns": ["Laureate", "Prizes"],
                   "rows": [[won[0]["FullName"], "; ".join(f"{r['AwardName']} {r['Year']}" for r in won)] for won in repeat]},
        "ages": {"columns": ["Prize", "Youngest", "Age", "Oldest", "Age", "Median age"],
                 "rows": [[p, min(ages[p], key=age)["FullName"], age(min(ages[p], key=age)),
                           max(ages[p], key=age)["FullName"], age(max(ages[p], key=age)),
                           f"{median(age(r) for r in ages[p]):g}"] for p in PRIZES + ["All prizes"]]},
        "women": {"columns": ["Decade", "Women", "All people"], "rows": [[f"{d}s", women_by_decade[d], people_by_decade[d]] for d in decades]},
        "born": {"columns": ["Born in", "Prizes", "Working in another country"], "rows": [[c, n, moved[c]] for c, n in top]},
    }


def charts(report):
    import matplotlib.pyplot as plt
    colors = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300"]
    fig, axes = plt.subplots(2, 2, figsize=(16, 11), layout="constrained")
    table = report["decades"]
    labels = [r[0] for r in table["rows"]]
    bottom = [0] * len(labels)
    for i, prize in enumerate(table["columns"][1:]):
        values = [r[i + 1] for r in table["rows"]]
        axes[0, 0].bar(labels, values, bottom=bottom, label=prize, color=colors[i], edgecolor="white")
        bottom = [a + b for a, b in zip(bottom, values)]
    axes[0, 0].set_title("Prizes by decade")
    axes[0, 0].tick_params(axis="x", rotation=60)
    axes[0, 0].legend(fontsize=8)
    table = report["share"]["rows"]
    axes[0, 1].pie([r[1] for r in table], labels=[f"{r[0]} ({r[1]})" for r in table], autopct="%.1f%%",
                   colors=[colors[PRIZES.index(r[0])] for r in table], wedgeprops={"width": .45, "edgecolor": "white"})
    axes[0, 1].set_title("Share of prizes")
    table = report["women"]["rows"]
    axes[1, 0].bar([r[0] for r in table], [r[2] - r[1] for r in table], label="Men", color="#c9d3dd")
    axes[1, 0].bar([r[0] for r in table], [r[1] for r in table], bottom=[r[2] - r[1] for r in table], label="Women", color=colors[4])
    axes[1, 0].set_title("Prizes to women and men by decade")
    axes[1, 0].tick_params(axis="x", rotation=60)
    axes[1, 0].legend()
    table = report["born"]["rows"][::-1]
    axes[1, 1].barh([r[0] for r in table], [r[1] for r in table], color="#c9d3dd", label="Prizes to people born there")
    axes[1, 1].barh([r[0] for r in table], [r[2] for r in table], color=colors[0], label="Working in another country")
    axes[1, 1].set_title("Where laureates were born")
    axes[1, 1].legend()
    plt.show()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("nobel_csv")
    parser.add_argument("--charts", action="store_true")
    parser.add_argument("--json", action="store_true", help="Print machine-readable tables for comparison")
    args = parser.parse_args()
    sys.stdout.reconfigure(encoding="utf-8")
    rows = read_csv(args.nobel_csv)
    result = analyze(rows)
    if args.json:
        print(json.dumps(result, ensure_ascii=False))
    else:
        print(f"{result['prizes']:,} prizes to {result['laureates']:,} laureates: {result['people']:,} people and {result['organizations']} organizations")
        print("Youngest: {} ({}, {}). Oldest: {} ({}, {}).".format(*result["youngest"], *result["oldest"]))
        print("First woman: {} ({}). {} women so far.".format(*result["first_woman"], result["women_laureates"]))
        for key in ["repeat", "decades", "share", "ages", "women", "born"]:
            print("\n" + key.upper())
            writer = csv.writer(sys.stdout, delimiter="\t", lineterminator="\n")
            writer.writerow(result[key]["columns"])
            writer.writerows(result[key]["rows"])
    if args.charts:
        charts(result)
