"""A desert rock riff, written in Python, played by Ableton Live.

Needs: Ableton Live 11 or 12, AbletonOSC (free, github.com/ideoforms/AbletonOSC) as a Control Surface,
and `pip install python-osc`. In Live: one MIDI track (track 1) with any guitar or bass on it,
an empty first clip slot. Then: python3 riff.py

What it shows: the riff from "Cobre y Buitres". A chromatic crawl E F F# G, a jump to the octave,
a fall back down, and swing (the off-beat 8ths land a little late, like a band behind the beat).
"""
import random
import time
from pythonosc.udp_client import SimpleUDPClient

live = SimpleUDPClient("127.0.0.1", 11000)      # AbletonOSC listens here
TRACK, SLOT, BPM, SWING = 0, 0, 118, 0.08
rnd = random.Random(13)

# (MIDI note, length in beats). None = silence. E2 = 40.
R1 = [(40, .75), (40, .25), (41, .5), (42, .5), (43, .75), (None, .25), (40, .5), (52, .5)]
R2 = [(50, .5), (48, .5), (47, .75), (45, .25), (43, .5), (42, .5), (40, 1)]
R4 = [(50, .5), (48, .5), (47, .5), (46, .5), (45, .5), (44, .5), (43, .5), (42, .5)]
RIFF = R1 + R2 + R1 + R4                         # 4 bars


def swing(t):
    return t + SWING if abs(t % 1 - .5) < 1e-6 else t


notes, t = [], 0.0
for pitch, length in RIFF:
    if pitch is not None:
        start = max(0.0, swing(t) + rnd.uniform(-.014, .014))   # a human is never exactly on the grid
        vel = 104 + (8 if pitch == 40 else 0) + rnd.randint(-6, 6)
        notes += [pitch, round(start, 4), round(length * .9, 4), vel, 0]
    t += length

live.send_message("/live/song/set/tempo", float(BPM))
live.send_message("/live/clip_slot/create_clip", [TRACK, SLOT, 16.0])
time.sleep(.5)
live.send_message("/live/clip/add/notes", [TRACK, SLOT] + notes)
live.send_message("/live/clip_slot/fire", [TRACK, SLOT])
print(f"{len(notes) // 5} notes sent. Change the riff, run it again, listen.")
