#!/usr/bin/env python3
"""Artist networks: DERIVED co-credit links versus EXPLICIT MusicBrainz relationships (network science example).

Standard library only. Run from the edition folder:  python3 examples/collaboration_graph.py

Two different graphs, never merged:
  * co-credit graph (DERIVED): two artists are linked when they share an artist credit on an edition
    recording. A shared credit is not proof of a collaboration (a "feat." can be a label decision).
  * relationship graph (EXPLICIT): artist-artist edges entered in MusicBrainz (member of band,
    collaboration, supporting musician, ...), from data/roles_networks/artist_relationships.csv.
"""
import collections
import csv
import itertools
import os

D = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
csv.field_size_limit(1 << 30)


def rows(*parts):
    with open(os.path.join(D, *parts), encoding="utf-8", newline="") as fh:
        yield from csv.DictReader(fh)


names = {r["artist_mbid"]: r["name"] for r in rows("data", "core", "artists.csv")}
credits = collections.defaultdict(set)
for r in rows("data", "core", "recording_artists.csv"):
    credits[r["recording_mbid"]].add(r["artist_mbid"])
co = collections.Counter()
for arts in credits.values():
    for a, b in itertools.combinations(sorted(arts), 2):
        co[(a, b)] += 1
multi = sum(1 for a in credits.values() if len(a) > 1)
print(f"Co-credit graph (DERIVED): {multi:,} of {len(credits):,} recordings credit 2+ artists; {len(co):,} artist pairs")
for (a, b), n in co.most_common(5):
    print(f"   {names.get(a, a)}  --  {names.get(b, b)}   ({n} recordings)")

rel = list(rows("data", "roles_networks", "artist_relationships.csv"))
types = collections.Counter(r["relationship_type"] for r in rel)
print(f"\nRelationship graph (EXPLICIT): {len(rel):,} edges touching credited artists; top types:")
for t, n in types.most_common(6):
    print(f"   {t:32s} {n:,}")
explicit = {tuple(sorted((r["artist_mbid"], r["related_artist_mbid"]))) for r in rel}
collab = {tuple(sorted((r["artist_mbid"], r["related_artist_mbid"]))) for r in rel if r["relationship_type"] == "collaboration"}
print(f"\nOverlap: {sum(p in explicit for p in co):,} of {len(co):,} co-credit pairs also have an explicit relationship; "
      f"{sum(p in collab for p in co):,} have an explicit 'collaboration' edge.")
deg = collections.Counter()
for r in rel:
    deg[r["artist_mbid"]] += 1
    deg[r["related_artist_mbid"]] += 1
print("\nHighest explicit-relationship degree:")
for a, n in deg.most_common(5):
    print(f"   {names.get(a, a):30s} {n:,}")
