"""Python Library Packager - Download and pack Python dependencies with caching support.

This module provides functionality to:
1. Read project information from projects.json or run pyprojectparse if needed
2. Download dependencies to local .cache directory
3. Pack dependencies into a distributable format
4. Support batch processing multiple projects recursively
"""

from __future__ import annotations

import argparse
import atexit
import logging
from pathlib import Path
from typing import Final

from pytola.core.logger import get_logger

from ..components.libpacker import (
    DEFAULT_MAX_WORKERS,
    DEFAULT_MIRROR,
    PyLibPacker,
    PyLibPackerConfig,
    SelectiveExtractionStrategy,
)
from ..models.libcache import DEFAULT_CACHE_DIR

__version__ = "1.0.0"
__build__ = "20260120"
SUPPORTED_ARCHIVE_FORMATS: Final[tuple[str, ...]] = (
    "zip",
    "tar",
    "gztar",
    "bztar",
    "xztar",
)

logger = get_logger(__name__)


def parse_args() -> argparse.Namespace:
    """Parse command-line arguments."""
    parser = argparse.ArgumentParser(
        prog="pylibpack",
        description="Python library packer with caching support",
    )

    parser.add_argument(
        "directory",
        type=str,
        nargs="?",
        default=str(Path.cwd()),
        help="Base directory containing projects",
    )
    parser.add_argument(
        "--cache-dir",
        type=str,
        default=None,
        help="Custom cache directory",
    )
    parser.add_argument(
        "--python-version",
        type=str,
        default=None,
        help="Target Python version",
    )
    parser.add_argument(
        "-j",
        "--jobs",
        type=int,
        default=DEFAULT_MAX_WORKERS,
        help="Maximum concurrent downloads",
    )
    parser.add_argument(
        "--mirror",
        type=str,
        default=DEFAULT_MIRROR,
        choices=("pypi", "tsinghua", "aliyun", "ustc", "douban", "tencent"),
        help="PyPI mirror source for faster downloads in China",
    )
    parser.add_argument("--debug", "-d", action="store_true", help="Debug mode")
    parser.add_argument(
        "--no-optimize",
        "-no",
        action="store_true",
        help="Disable package optimization (extract all files)",
    )

    # Add option to show package size
    parser.add_argument(
        "--show-size",
        action="store_true",
        help="Show packed package size",
    )
    parser.add_argument(
        "--show-stats",
        action="store_true",
        help="Show detailed project statistics",
    )
    parser.add_argument(
        "--list-optimizations",
        "-lo",
        action="store_true",
        help="List all available optimization rules",
    )
    return parser.parse_args()


def main() -> None:
    """Run main entry point for pylibpack tool."""
    args = parse_args()

    # Setup logging
    if args.debug:
        logger.setLevel(logging.DEBUG)

    if args.list_optimizations:
        strategy = SelectiveExtractionStrategy()
        logging.info("Available optimization rules:")
        for lib_name in sorted(strategy.get_library_names_with_rules()):
            logging.info(f"  - {lib_name}")
        return

    # Create configuration from arguments
    config = PyLibPackerConfig(
        cache_dir=Path(args.cache_dir) if args.cache_dir else DEFAULT_CACHE_DIR,
        mirror=args.mirror,
        optimize=not args.no_optimize,
        max_workers=args.jobs,
    )

    # Register auto-save on exit
    atexit.register(config.save)

    packer = PyLibPacker(
        working_dir=Path(args.directory),
        config=config,
    )

    # Execute pack operation
    packer.run()

    if args.show_stats:
        packer.show_stats()


if __name__ == "__main__":
    main()
