from __future__ import annotations

import argparse
import textwrap

from pdm import termui
from pdm._types import SearchResults
from pdm.cli.commands.base import BaseCommand
from pdm.cli.options import verbose_option
from pdm.models.working_set import WorkingSet
from pdm.project import Project
from pdm.utils import normalize_name


def print_results(
    ui: termui.UI,
    hits: SearchResults,
    working_set: WorkingSet,
    terminal_width: int | None = None,
) -> None:
    if not hits:
        return
    name_column_width = max(len(hit.name) + len(hit.version or "") for hit in hits) + 4

    for hit in hits:
        name = hit.name
        summary = hit.summary or ""
        if terminal_width is not None:
            target_width = terminal_width - name_column_width - 5
            if target_width > 10:
                # wrap and indent summary to fit terminal
                summary = ("\n" + " " * (name_column_width + 2)).join(textwrap.wrap(summary, target_width))
        current_width = len(name) + 1
        spaces = " " * (name_column_width - current_width)
        line = f"[req]{name}[/]{spaces} - {summary}"
        try:
            ui.echo(line)
            if normalize_name(name) in working_set:
                dist = working_set[normalize_name(name)]
                ui.echo(f"  INSTALLED: {dist.version}")
        except UnicodeEncodeError:
            pass


class Command(BaseCommand):
    """[DEPRECATED] Search for PyPI packages"""

    arguments = (verbose_option,)

    def add_arguments(self, parser: argparse.ArgumentParser) -> None:
        parser.add_argument("query", help="Query string to search")

    def handle(self, project: Project, options: argparse.Namespace) -> None:
        project.core.ui.warn(
            "Since pypi.org no longer supports search API, this command is deprecated and will be removed in future versions. "
            "Please visit `https://pypi.org` in the browser to search for packages.",
        )
        return
