#!/usr/bin/python3
"""Interactive ALSA playback setup; save only after an audible test is confirmed."""
import argparse
import os
import re
import shutil
import subprocess
import sys


def run(*args, capture=False):
    return subprocess.run(args, check=True, text=True,
                          stdout=subprocess.PIPE if capture else None,
                          env={**os.environ, "LC_ALL": "C"})


def playback_devices(output):
    devices = []
    for line in output.splitlines():
        match = re.match(r"card (\d+): (.+?), device (\d+): (.+)", line)
        if match:
            card, name, device, description = match.groups()
            devices.append((card, device, f"{name}: {description}"))
    return devices


def setup():
    devices = playback_devices(run("aplay", "-l", capture=True).stdout)
    if not devices:
        raise ValueError("No ALSA playback devices found. Check the audio driver before changing mixer settings.")
    print("Sound outputs:")
    for index, (_, _, name) in enumerate(devices, 1):
        print(f"  {index}. {name}")
    if len(devices) == 1:
        selected = 0
    else:
        choice = input("Choose an output number (Analog is usually speakers/headphones; q cancels): ").strip()
        if choice.lower() == "q":
            return 0
        if not choice.isdecimal() or not 1 <= int(choice) <= len(devices):
            raise ValueError("Invalid output number. Run sound-setup again to choose an output.")
        selected = int(choice) - 1
    card, device, name = devices[selected]
    print(f"Selected: {name}")
    controls = run("amixer", "-c", card, "scontrols", capture=True).stdout
    master = "Simple mixer control 'Master',0" in controls.splitlines()
    if master:
        print("Master will be unmuted and set to 50%. Other mixer controls are preserved.")
    else:
        print("This card has no Master control. The mixer will open for you to select")
        print("the playback channel: M unmutes, arrows change volume, Esc finishes.")
    if input("Press Enter to continue, or type q to cancel: ").strip().lower() != "":
        return 0
    if master:
        run("amixer", "-q", "-c", card, "sset", "Master", "50%", "unmute")
    else:
        run("alsamixer", "-c", card)
    print("Playing one left/right speaker test. Ctrl+C stops it.")
    run("speaker-test", "-D", f"plughw:{card},{device}", "-c", "2", "-t", "wav", "-l", "1")
    if input("Did you hear the test? Save this card's settings? [y/N]: ").strip().lower() not in ("y", "yes"):
        print("Settings were not saved by sound-setup. Current mixer changes remain active.")
        print(f"For further checks, run: amixer -c {card}")
        print("You can adjust other playback channels with alsamixer, then run sound-setup again.")
        return 1
    run("sudo", "/usr/sbin/alsactl", "store", card)
    print("Sound settings saved. Run sound-setup whenever you need to repeat this check.")
    return 0


def main():
    parser = argparse.ArgumentParser(description="Choose an ALSA output, unmute Master at 50%, test and save sound.")
    parser.parse_args()
    if os.geteuid() == 0:
        print("Run sound-setup as your desktop user, without sudo. Saving may ask for your password.", file=sys.stderr)
        return 2
    if not sys.stdin.isatty():
        print("Run sound-setup in a terminal; output selection and audible confirmation are interactive.", file=sys.stderr)
        return 2
    missing = [name for name in ("aplay", "amixer", "alsamixer", "speaker-test", "/usr/sbin/alsactl", "sudo")
               if not shutil.which(name)]
    if missing:
        print("Missing tools: " + ", ".join(missing) + ". Run desktop-setup first.", file=sys.stderr)
        return 1
    try:
        return setup()
    except (EOFError, KeyboardInterrupt):
        print("\nSound setup stopped; current mixer changes may remain active.", file=sys.stderr)
        return 130
    except (ValueError, OSError, subprocess.CalledProcessError) as error:
        print(f"Sound setup failed: {error}. No successful save is confirmed.", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
