import subprocess
import os

def run_command_live(cmd):
    process = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True,
        bufsize=1
    )

    os.makedirs("downloads", exist_ok=True)
    # Read stdout line by line as it appears
    i = 0
    for line in process.stdout:
        print(line, end="")  # end="" keeps original line breaks
        if line.strip().endswith("Downloaded."):
            name = line.split("Downloaded.")[0].strip()
            os.rename(name, f"downloads/{i:04d}-{name}")
            i += 1
            print(f"DOWNLOADED AND RENAMED TRACK {i}")

    process.stdout.close()
    returncode = process.wait()
    return returncode


if __name__ == "__main__":
    # Example: replace with your own command
    command = ['scdl', '-l', 'hugo-a-943641374', '-f', '--no-original', '--no-playlist', '-n', '500']
    run_command_live(command)
