"""Thin CLI entry point for the zhijiang package.

This wrapper exists to fix a namespace-package shadowing issue:
When switching from non-editable to editable install, pip removes tracked files
from site-packages/zhijiang/ but leaves behind untracked files (extracted by
'sudo 7z x' in _unzip_if_necessary). The leftover directory (without __init__.py)
becomes a namespace package that shadows the editable install's _EditableFinder
(because PathFinder runs first in sys.meta_path).

By using a separate top-level module as the entry point, we can detect and clean
up the stale directory before importing from the zhijiang package.
"""

import importlib
import os
import shutil
import site
import sys


def main():
    # Clean stale zhijiang namespace package from site-packages.
    # ref: zhijiang/__init__.py _unzip_if_necessary() extracts with sudo 7z
    for sp in site.getsitepackages():
        stale = os.path.join(sp, "zhijiang")
        if os.path.isdir(stale) and not os.path.isfile(
            os.path.join(stale, "__init__.py")
        ):
            try:
                shutil.rmtree(stale)
            except PermissionError:
                os.system(f'sudo rm -rf "{stale}"')
            if not os.path.isdir(stale):
                importlib.invalidate_caches()
                sys.modules.pop("zhijiang", None)

    from zhijiang import main as _main

    _main()
