"""
orbits - Visualize dependency sizes as systems of planets

Reads dependency declarations from a project's config files (pyproject.toml,
setup.cfg, requirements.txt) and looks up each package in the currently active
Python environment to get version and disk size.

Run this script with the Python interpreter whose environment you want to
measure (e.g. activate your venv first).

Usage:
    orbits [PROJECT_DIR] [OPTIONS]

Options:
    --python            Explicit Python interpreter to measure (overrides $VIRTUAL_ENV)
    -h, --help          Show help
"""

import argparse
from pathlib import Path
import sys

from dep_orbits.parse import NoDependenciesException, calculate_tree
from dep_orbits.server import start_server

RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
CYAN = "\033[36m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
RED = "\033[31m"


def c(text, *codes):
    return "".join(codes) + str(text) + RESET


def main() -> None:
    try:
        parser = argparse.ArgumentParser(
            prog="deptree",
            description=(
                "Show the full dependency tree with disk sizes for a Python project.\n\n"
                "Package sizes are read from the CURRENTLY ACTIVE Python environment.\n"
                "Activate your venv (or use `uv run`) before running this script."
            ),
            formatter_class=argparse.RawDescriptionHelpFormatter,
        )
        parser.add_argument(
            "project_dir",
            nargs="?",
            default=".",
            help="Path to project directory (default: current dir)",
        )
        parser.add_argument(
            "--python",
            default=None,
            metavar="PATH",
            help="Explicit Python interpreter to measure (overrides $VIRTUAL_ENV)",
        )
        args = parser.parse_args()

        project_dir = Path(args.project_dir).resolve()
        if not project_dir.is_dir():
            print(f"Error: '{project_dir}' is not a directory.", file=sys.stderr)
            sys.exit(1)

        try:
            tree = calculate_tree(project_dir, Path(args.python) if args.python else None)
        except NoDependenciesException:
            print(
                c(
                    "No dependencies found. Ensure the project has a pyproject.toml, "
                    "setup.cfg, or requirements.txt.",
                    YELLOW,
                ),
                file=sys.stderr,
            )
            sys.exit(0)

        thread = start_server(tree)

        thread.join()
    except KeyboardInterrupt:
        return
