#!/usr/bin/env python3

"""
Rebuilds the .circleci/config.yml file based on the output of ``tox --listenvs``
"""

import jinja2
import subprocess as sp

template = jinja2.Template("""\
# !!! WARNING !!!
# This file is automatically generated by ../rebuild-circleci-yaml
# !!! WARNING !!!
version: 2.1

jobs:
  {% for (tox_env, python_ver) in env_list: %}
  # !!! WARNING !!!
  # This file is automatically generated by ../rebuild-circleci-yaml
  # !!! WARNING !!!

  test-{{ tox_env }}:
    docker:
      {% if python_ver == "pypy3" -%}
      - image: pypy:3
      {%- else -%}
      - image: python:{{ python_ver }}
      {%- endif %}
    steps:
      - checkout
      - run:
          name: install tox
          command: pip install tox
      - run:
          name: run tests
          command: tox -e {{ tox_env }}
  {% endfor %}

workflows:
  main:
    jobs:
      {% for (tox_env, _) in env_list: -%}
      - test-{{ tox_env }}
      {% endfor -%}

# !!! WARNING !!!
# This file is automatically generated by ../rebuild-circleci-yaml
# !!! WARNING !!!
""")

# Maps tox python versions (ex, "py27") to CircleCI Python versions (ex, "2.7")
py_version_map = {
    "py26": "2.6",
    "py27": "2.7",
    "py35": "3.5",
    "py36": "3.6",
    "py37": "3.7",
    "py38": "3.8",
    "py39": "3.9",
    "py310": "3.10",
    "py311": "3.11",
    "pypy3": "pypy3",
}

def main():
    env_list_bytes = sp.check_output("tox --listenvs", shell=True).splitlines()
    env_list = []
    for env_bytes in env_list_bytes:
        env = env_bytes.decode("utf-8")
        if not env.strip():
            continue
        py_ver, _, _ = env.partition("-")
        env_list.append((env, py_version_map[py_ver]))

    with open(".circleci/config.yml", "w") as f:
        f.write(template.render(env_list=env_list))


if __name__ == "__main__":
    main()
