"""Step 1: install LibreTranslate into this app's Python environment.

DirectAdmin > Setup Python App > Execute python script:  lt_install.py  > Run Script
It returns at once and keeps installing in the background (10-30 minutes).
Follow it in File Manager: open lt_install.log in this folder. It ends with "DONE".
"""
import os
import subprocess
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
LOG = os.path.join(HERE, 'lt_install.log')
# The CPU-only build of PyTorch: about 200 MB instead of several GB (the server has no graphics card).
STEPS = [
    [sys.executable, '-m', 'pip', 'install', '--upgrade', 'pip'],
    [sys.executable, '-m', 'pip', 'install', '--extra-index-url', 'https://download.pytorch.org/whl/cpu', 'libretranslate'],
]

if '--run' in sys.argv:
    with open(LOG, 'a', buffering=1) as log:
        for cmd in STEPS:
            log.write('\n$ pip ' + ' '.join(cmd[3:]) + '\n')
            code = subprocess.call(cmd, cwd=HERE, stdout=log, stderr=subprocess.STDOUT)
            if code != 0:
                log.write('\nFAILED (exit code %d). Run lt_install.py again; finished downloads are reused.\n' % code)
                sys.exit(code)
        log.write('\nDONE: LibreTranslate is installed. Next step: run lt_models.py\n')
else:
    with open(LOG, 'w') as log:
        log.write('Installing LibreTranslate with ' + sys.executable + '\n')
    subprocess.Popen([sys.executable, os.path.abspath(__file__), '--run'], cwd=HERE, stdin=subprocess.DEVNULL,
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
    print('Started. Installing in the background: open lt_install.log in File Manager to follow it (10-30 minutes).')
