# Usage: python3 credit.py <tracks.tsv>   One track per line, columns separated by tabs, saved as UTF-8: title, artist, source_url, license, license_url, changes.
# A full stop at the end of the changes column is optional: the script adds one.
# A first line that starts with "title" is taken as a header and skipped. Prints one show-notes credit line per track; exits 1 if a line could not be read.
import sys
if len(sys.argv) < 2: sys.exit("usage: python3 credit.py tracks.tsv")
try:
    rows = open(sys.argv[1], encoding="utf-8-sig", newline="").read().splitlines()
except FileNotFoundError:
    sys.exit(f"missing file: {sys.argv[1]}")
except UnicodeDecodeError:
    sys.exit(f"not UTF-8: {sys.argv[1]} (save it as UTF-8 and run again)")
rows = [(n, r.rstrip("\r")) for n, r in enumerate(rows, 1) if r.strip()]
if rows and rows[0][1].split("\t")[0].strip().lower() == "title": rows = rows[1:]
if not rows: sys.exit(f"empty file: {sys.argv[1]}")
bad = 0
for n, r in rows:
    c = [x.strip() for x in r.split("\t")]
    if len(c) < 5:
        hint = " (no tabs found: separate the columns with tabs, not commas)" if "\t" not in r else ""
        print(f"line {n}: need title, artist, source_url, license, license_url{hint}", file=sys.stderr); bad += 1; continue
    title, artist, src, lic, lic_url = c[:5]; changes = c[5].rstrip(".").strip() if len(c) > 5 else ""
    if lic.upper().startswith("CC0"):
        print(f'Music: "{title}" by {artist} ({src}), {lic} ({lic_url}). No credit required; given as thanks.')
    else:
        tail = f" {changes}." if changes else ""
        print(f'Music: "{title}" by {artist} ({src}). Licensed under {lic} ({lic_url}).{tail}')
sys.exit(1 if bad else 0)
