# pytools/cli/extract_imports.py

import argparse
from pathlib import Path
from textwrap import dedent

from pytools.core.extract_imports import extract_imports


def main():
    parser = argparse.ArgumentParser(
        prog="pytools-extract-imports",
        description=(
            "Scan Python files under PATH and print import dependencies grouped into "
            "third-party, relative (local), then stdlib (sorted)."
        ),
        epilog=dedent(
            """
            examples:
              List imports for a package directory:
                pytools-extract-imports ./src/myapp

              Ignore test folders and virtualenvs (repeat --ignore for multiple globs):
                pytools-extract-imports ./src --ignore "**/tests/**/*.py" --ignore "**/.venv/**"

              Show this help:
                pytools-extract-imports -h
            """
        ).strip(),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument(
        "path",
        type=str,
        metavar="PATH",
        help="Directory to scan recursively for *.py files",
    )
    parser.add_argument(
        "--ignore",
        action="append",
        default=[],
        metavar="GLOB",
        help="Import name/glob to exclude from main groups and track under ignored (repeatable)",
    )
    parser.add_argument(
        "--show-ignored",
        action="store_true",
        help="Print ignored imports grouped by each --ignore pattern",
    )

    args = parser.parse_args()

    extracted = extract_imports(
        Path(args.path),
        ignore_globs=args.ignore,
    )

    print("-- third-party dependencies --")
    for name in extracted.third_party:
        print(name)
    print()
    print("-- python stdlib --")
    for name in extracted.stdlib:
        print(name)
    print()
    print("-- local (relative) imports --")
    for name in extracted.local:
        print(name)
    if args.show_ignored:
        print()
        print("-- ignored --")
        for index, (pattern, names) in enumerate(extracted.ignored, start=1):
            print(f"{index}. {pattern}")
            for name in names:
                print(name)


if __name__ == "__main__":
    main()
