#! /usr/bin/env pipenv-shebang
"""Generate C/C++ properties file for VSCode.

Uses pgenv to iterate postgres versions and generate
a C/C++ properties file for VSCode containing the
include paths for the postgres headers.

Usage:
  generate_c_cpp_properties-json.py <target_path>
  generate_c_cpp_properties-json.py (-h | --help)
  generate_c_cpp_properties-json.py --version

Options:
  -h --help     Show this screen.
  --version     Show version.

"""
import json
import subprocess

from docopt import docopt


def main(args):
    target_path = args['<target_path>']

    output = subprocess.check_output(['pgenv', 'versions'])
    # typical output is:
    #      14.8      pgsql-14.8
    #  *   15.3      pgsql-15.3
    #      16beta2    pgsql-16beta2
    # where the line marked with a * is the currently active version
    #
    # we are only interested in the first word of each line, which is the version number
    # thus we strip the whitespace and the * from the line and split it into words
    # and take the first word
    versions = [line.strip('* ').split()[0] for line in output.decode('utf-8').splitlines()]

    # create the list of configurations per version
    configurations = []
    for version in versions:
        configurations.append(generate_configuration(version))

    # create the json file
    c_cpp_properties = {
        "configurations": configurations,
        "version": 4
    }

    # write the c_cpp_properties.json file
    with open(target_path, 'w') as f:
        json.dump(c_cpp_properties, f, indent=4)


def generate_configuration(version):
    """Returns a configuration for the given postgres version.

    >>> generate_configuration('14.8')
    {
        "name": "Citus Development Configuration - Postgres 14.8",
        "includePath": [
            "/usr/local/include",
            "/home/citus/.pgenv/src/postgresql-14.8/src/**",
            "${workspaceFolder}/**",
            "${workspaceFolder}/src/include/",
        ],
        "configurationProvider": "ms-vscode.makefile-tools"
    }
    """
    return {
        "name": f"Citus Development Configuration - Postgres {version}",
        "includePath": [
            "/usr/local/include",
            f"/home/citus/.pgenv/src/postgresql-{version}/src/**",
            "${workspaceFolder}/**",
            "${workspaceFolder}/src/include/",
        ],
        "configurationProvider": "ms-vscode.makefile-tools"
    }


if __name__ == '__main__':
    arguments = docopt(__doc__, version='0.1.0')
    main(arguments)
