#!/usr/bin/env python3.12
# Released under the MIT License. See LICENSE for details.
#
"""Command line wrapper for the spinoff system."""

from __future__ import annotations

import os
import sys
import subprocess

if __name__ == '__main__':

    # The initial invocation of this script actually just sets the stage
    # for the *real* invocation of this script, which always happens
    # from the fully-inited virtual env of the source project. This way
    # all modules used by the spinoff system are in place and there's no
    # abiguity where we could be loading Python stuff from the dst
    # project while we're in the process of modifying it.
    if 'BA_SPINOFF_SRC_ROOT' not in os.environ:

        # Calc absolute paths for our source (and possibly dst)
        # projects. If we are getting invoked via a symlink, what it
        # points to is src and we are dst. Otherwise we are src and
        # there is no dst.
        dst_proj_root: str | None
        if os.path.islink(sys.argv[0]):
            src_spinoff_path = os.path.realpath(sys.argv[0])
            dst_proj_root = os.path.abspath(
                os.path.join(os.path.dirname(sys.argv[0]), '..')
            )

        else:
            src_spinoff_path = sys.argv[0]
            dst_proj_root = None  # pylint: disable=invalid-name

        src_proj_root = os.path.abspath(
            os.path.join(os.path.dirname(src_spinoff_path), '..')
        )
        src_proj_python = os.path.join(src_proj_root, '.venv/bin/python3.12')

        cmd = [src_proj_python, 'tools/spinoff'] + sys.argv[1:]

        env = dict(os.environ, BA_SPINOFF_SRC_ROOT=src_proj_root)
        if dst_proj_root is not None:
            env['BA_SPINOFF_DST_ROOT'] = dst_proj_root

        # Make sure the src project is properly bootstrapped.
        subprocess.run(['make', 'env'], check=True, cwd=src_proj_root)

        # Finally, run for realz (from src proj dir).
        result = subprocess.run(cmd, check=False, env=env, cwd=src_proj_root)
        sys.exit(result.returncode)

    else:
        from batools.spinoff import spinoff_main

        # Ok; we're a real invocation. Do our thing.
        spinoff_main()
