#!/usr/bin/env python3
# summary: Set stereo balance, Bluetooth audio quality, and microphone noise reduction.
"""Usage: starchaser audio controls status | balance NUMBER | profile CARD PROFILE | noise on|off

Set stereo balance, Bluetooth music/call quality, and microphone noise reduction.
"""
import json
import math
import sys
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_device_io import CONFIG, read_json, run, update_json

PREFS = CONFIG / 'starchaser/audio-care.json'
FILTER = CONFIG / 'pipewire/filter-chain.conf.d/90-starchaser-noise.conf'


def balance_volumes(volume, balance):
    if not math.isfinite(balance) or not -1 <= balance <= 1 or not math.isfinite(volume) or not 0 <= volume <= 1.5:
        raise ValueError('Choose a balance between Left and Right.')
    return [volume * (1 - max(0, balance)), volume * (1 + min(0, balance))]


def cards():
    out = []
    for card in json.loads(run('pactl', '-f', 'json', 'list', 'cards')):
        if not card.get('name', '').startswith('bluez_card.'):
            continue
        profiles = card.get('profiles', {})
        if isinstance(profiles, list):
            profiles = {p['name']: p for p in profiles}
        choices = []
        for name, profile in profiles.items():
            if profile.get('available') == 'no':
                continue
            if name.startswith('a2dp'):
                choices.append(dict(id=name, name='Music quality'))
            elif name.startswith(('headset-head-unit', 'handsfree-head-unit')):
                choices.append(dict(id=name, name='Call mode'))
        out.append(dict(id=card['name'], name=card.get('properties', {}).get('device.description', 'Bluetooth headset'),
                        profiles=choices, current=card.get('active_profile', '')))
    return out


def output_balance():
    default = run('pactl', 'get-default-sink').strip()
    sink = next((row for row in json.loads(run('pactl', '-f', 'json', 'list', 'sinks')) if row['name'] == default), None)
    if not sink or len(sink.get('volume', {})) != 2:
        return None
    left, right = (channel['value'] for channel in sink['volume'].values())
    return (1 - left / right if right > left else right / left - 1) if left != right else 0


def set_balance(value):
    balance = float(value)
    default = run('pactl', 'get-default-sink').strip()
    sink = next((s for s in json.loads(run('pactl', '-f', 'json', 'list', 'sinks')) if s['name'] == default), None)
    if not sink or len(sink.get('volume', {})) != 2:
        raise ValueError('Balance needs a stereo sound output.')
    volume = max(channel['value'] / 65536 for channel in sink['volume'].values())
    values = balance_volumes(volume, balance)
    run('pactl', 'set-sink-volume', default, *(str(round(v * 65536)) for v in values))
    return dict(ok=True)


def noise(enabled):
    saved = read_json(PREFS)
    if not enabled:
        previous = saved.get('source', '')
        if previous:
            run('pactl', 'set-default-source', previous)
        run('systemctl', '--user', 'disable', '--now', 'starchaser-noise.service')
        update_json(PREFS, lambda value: value.update(noise=False))
        return dict(ok=True, message='Microphone noise reduction is off.')
    source = run('pactl', 'get-default-source').strip()
    if source == 'starchaser_clean_microphone':
        return dict(ok=True, message='Microphone noise reduction is on.')
    # JSON strings also quote the SPA configuration syntax without allowing injected config text.
    target = json.dumps(source)
    config = '''context.modules = [
    { name = libpipewire-module-filter-chain
      args = {
        node.description = "Microphone with noise reduction"
        filter.graph = {
          nodes = [ { type = ladspa name = rnnoise plugin = "/usr/lib/ladspa/librnnoise_ladspa.so" label = noise_suppressor_mono control = { "VAD Threshold (%)" = 50.0 } } ]
        }
        capture.props = { node.name = "starchaser_noise_capture" node.passive = true audio.position = [ MONO ] target.object = TARGET }
        playback.props = { node.name = "starchaser_clean_microphone" media.class = "Audio/Source" audio.position = [ MONO ] }
      }
    }
]
'''.replace('TARGET', target)
    FILTER.parent.mkdir(parents=True, exist_ok=True)
    temporary = FILTER.with_name(f'.{FILTER.name}.{__import__("os").getpid()}.tmp')
    with temporary.open('w') as stream:
        stream.write(config)
        stream.flush()
        __import__('os').fsync(stream.fileno())
    temporary.replace(FILTER)
    run('systemctl', '--user', 'enable', '--now', 'starchaser-noise.service')
    for _ in range(20):
        sources = json.loads(run('pactl', '-f', 'json', 'list', 'sources'))
        if any(s['name'] == 'starchaser_clean_microphone' for s in sources):
            run('pactl', 'set-default-source', 'starchaser_clean_microphone')
            update_json(PREFS, lambda value: value.update(noise=True, source=source))
            return dict(ok=True, message='Noise reduction is on. Choose “Microphone with noise reduction” in an open call if needed.')
        time.sleep(0.1)
    run('systemctl', '--user', 'disable', '--now', 'starchaser-noise.service')
    raise ValueError("Noise reduction didn't start. Your original microphone is still selected.")


def main(args):
    if args in (['-h'], ['--help'], ['help']):
        print(__doc__)
        return 0
    try:
        if args == ['status']:
            result = dict(ok=True, cards=cards(), noise=read_json(PREFS).get('noise', False), balance=output_balance())
        elif len(args) == 2 and args[0] == 'balance':
            result = set_balance(args[1])
        elif len(args) == 3 and args[0] == 'profile':
            if not any(card['id'] == args[1] and any(p['id'] == args[2] for p in card['profiles']) for card in cards()):
                raise ValueError('Choose a connected headset and an available sound mode.')
            run('pactl', 'set-card-profile', args[1], args[2])
            result = dict(ok=True)
        elif len(args) == 2 and args[0] == 'noise' and args[1] in ('on', 'off'):
            result = noise(args[1] == 'on')
        else:
            print(__doc__, file=sys.stderr)
            return 2
        print(json.dumps(result))
        return 0
    except (OSError, ValueError) as error:
        print(json.dumps(dict(ok=False, errors=str(error))))
        return 1


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
