from typing import List

from pygeai.core.utils.console import Console
from pygeai.skills.models import Agent, Skill


def display_skills_table(skills: List[Skill], show_category: bool = True):
    """Display skills in a formatted table."""
    if not skills:
        Console.write_stdout("No skills found.")
        return

    Console.write_stdout("\nAvailable Skills:\n")

    if show_category:
        by_category = {}
        for skill in skills:
            cat = skill.category
            if cat not in by_category:
                by_category[cat] = []
            by_category[cat].append(skill)

        for category in sorted(by_category.keys()):
            Console.write_stdout(f"\n{category.upper()} Skills:")
            for skill in by_category[category]:
                Console.write_stdout(f"  {skill.name:<30} {skill.description}")
    else:
        for skill in skills:
            Console.write_stdout(f"  {skill.name:<30} {skill.description}")

    Console.write_stdout("")


def display_skill_details(skill: Skill):
    """Display detailed skill information."""
    Console.write_stdout(f"\nSkill: {skill.name}")
    Console.write_stdout(f"Description: {skill.description}")
    Console.write_stdout(f"Category: {skill.category}")
    Console.write_stdout(f"Version: {skill.version}")
    Console.write_stdout(f"Author: {skill.author}")

    if skill.license:
        Console.write_stdout(f"License: {skill.license}")

    if skill.compatibility:
        Console.write_stdout(f"Compatibility: {skill.compatibility}")

    if skill.allowed_tools:
        Console.write_stdout(f"Allowed Tools: {', '.join(skill.allowed_tools)}")

    Console.write_stdout("\nInstructions:")
    Console.write_stdout(skill.instructions[:500])
    if len(skill.instructions) > 500:
        Console.write_stdout("...\n(Use 'geai skills info <name>' for full instructions)")

    Console.write_stdout("")


def prompt_yes_no(question: str, default: bool = True) -> bool:
    """Prompt for yes/no confirmation."""
    default_str = "Y/n" if default else "y/N"
    response = input(f"{question} ({default_str}): ").strip().lower()

    if not response:
        return default

    return response in ["y", "yes"]


def prompt_selection(options: List[str], prompt: str, allow_all: bool = True) -> List[int]:
    """
    Prompt user to select from numbered options.

    Returns list of selected indices (0-based).
    """
    for i, option in enumerate(options, 1):
        Console.write_stdout(f"  {i}. {option}")

    all_text = " or 'all'" if allow_all else ""
    selection = input(f"\n{prompt} (comma-separated numbers{all_text}): ").strip()

    if allow_all and selection.lower() == "all":
        return list(range(len(options)))

    try:
        indices = [int(x.strip()) - 1 for x in selection.split(",")]
        valid_indices = [i for i in indices if 0 <= i < len(options)]
        return valid_indices
    except (ValueError, IndexError):
        Console.write_error("Invalid selection")
        return []
