#!/usr/bin/env python3
import os.path
import shutil
import subprocess
import sys
import tempfile
import zipfile


def main() -> int:
    with zipfile.ZipFile(
            'out.zip', 'w',
            compression=zipfile.ZIP_DEFLATED,
            compresslevel=9,
    ) as zipf:
        with tempfile.TemporaryDirectory() as tmpdir:
            subprocess.check_call((
                sys.executable, '-mpip', 'install', '--target', tmpdir,
                '-r', 'requirements.txt',
            ))

            # remove the bin directory, it is not useful in lambda
            shutil.rmtree(os.path.join(tmpdir, 'bin'))

            for root, _, filenames in os.walk(tmpdir):
                for filename in filenames:
                    if filename.endswith('.pyc'):
                        continue
                    abspath = os.path.join(root, filename)
                    arcname = os.path.relpath(abspath, tmpdir)
                    zipf.write(abspath, arcname=arcname)
            zipf.write('sample_app.py')
    return 0


if __name__ == '__main__':
    exit(main())
