#!/usr/bin/python3
"""Install private AI, speech, or both through fixed package operations."""
import os
import subprocess
import sys
from pathlib import Path

# Exit codes the setup (bin/starchaser-private-ai) turns into advice: the packages, then the service.
INSTALL_FAILED = 1
START_FAILED = 3

# Discrete Radeon RX 6000 series and newer (and the workstation cards built on them): the cards the AMD compute
# libraries in ollama-rocm run on. Older and built-in AMD graphics get the plain package, which still works.
AMD_COMPUTE_DEVICES = range(0x73a0, 0x7600)


def graphics_package(sysfs=Path('/sys'), nvidia_tool=Path('/usr/bin/nvidia-smi')):
    """The add-on that lets private AI use this computer's graphics card, or None to use the processor.

    Read from the hardware itself, never from an argument: the caller chooses only ai, voice or ai-voice.
    """
    found = set()
    for device in sorted((sysfs / 'bus/pci/devices').glob('*')):
        try:
            if not (device / 'class').read_text().strip().startswith('0x03'):   # display controllers only
                continue
            vendor = (device / 'vendor').read_text().strip().lower()
            model = int((device / 'device').read_text().strip(), 16)
        except (OSError, ValueError):
            continue
        try: driver = os.path.basename(os.readlink(device / 'driver'))
        except OSError: driver = ''
        # An NVIDIA card counts with NVIDIA's own driver: running it now, or installed and waiting for a restart.
        if vendor == '0x10de' and (driver == 'nvidia' or (driver != 'nouveau' and nvidia_tool.exists())):
            found.add('ollama-cuda')
        elif vendor == '0x1002' and driver == 'amdgpu' and model in AMD_COMPUTE_DEVICES:
            found.add('ollama-rocm')
    return next((name for name in ('ollama-cuda', 'ollama-rocm') if name in found), None)


def main(argv, graphics=graphics_package):
    if argv not in (["ai"], ["voice"], ["ai-voice"]) or os.geteuid() != 0:
        return 'Run private AI setup from Settings.'
    if argv == ['voice']:
        return subprocess.run(['/usr/bin/pacman','-S','--needed','--noconfirm','whisper-cpp']).returncode
    # The package manager takes its usual lock and refuses concurrent software changes.
    # Each add-on needs the plain package and adds to it, and --needed skips what is installed: a second run
    # changes nothing, and a run after the graphics driver arrives adds only the add-on.
    addon = graphics()
    packages = ['ollama'] + ([addon] if addon else []) + (['whisper-cpp'] if argv == ['ai-voice'] else [])
    if subprocess.run(['/usr/bin/pacman','-S','--needed','--noconfirm', *packages]).returncode:
        return INSTALL_FAILED
    # With an add-on, start the service again: one that was already running looked for graphics support before
    # the add-on was there. Without one, a running service is left alone.
    steps = [['enable'], ['restart']] if addon else [['enable', '--now']]
    for step in steps:
        if subprocess.run(['/usr/bin/systemctl', *step, 'ollama.service']).returncode:
            return START_FAILED
    return 0


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