"""
Modules CLI commands for managing published remote modules.
"""

import click

from ..client import APIClient, APIError
from .utils import console, error_console, verbose_option


@click.group()
def modules():
    """Manage published modules on the platform"""
    pass


@modules.command(name="list")
@click.option("--category", help="Filter by data category")
@click.option("--limit", default=100, help="Maximum number of modules to list")
@verbose_option
def list_cmd(category, limit):
    """List available published modules"""
    client = APIClient()
    try:
        results = client.modules.list(category=category, limit=limit)
        data = [r if isinstance(r, dict) else (r.model_dump() if hasattr(r, "model_dump") else {}) for r in results]

        # Nicer table output
        from rich.table import Table

        table = Table(title="Published Modules")
        table.add_column("ID", style="cyan")
        table.add_column("Name", style="green")
        table.add_column("Version", style="blue")
        table.add_column("Status", style="magenta")

        for m in data:
            table.add_row(
                m.get("id", ""),
                m.get("display_name") or m.get("name", ""),
                m.get("version", ""),
                m.get("state", "unknown"),
            )
        console.print(table)
    except APIError as e:
        error_console.print(f"[red]Error:[/red] {e}")
        raise click.Abort() from e


@modules.command()
@click.argument("module_id")
@click.option("--version", required=True, help="Specific version to suspend")
@verbose_option
def suspend(module_id, version):
    """Suspend a specific version of a module"""
    client = APIClient()
    try:
        client.modules.suspend_version(module_id, version)
        console.print(f"[green]Successfully suspended version {version} of module {module_id}[/green]")
    except APIError as e:
        error_console.print(f"[red]Error:[/red] {e}")
        raise click.Abort() from e


@modules.command()
@click.argument("module_id")
@click.option("--reason", help="Optional reason for deletion")
@verbose_option
def delete(module_id, reason):
    """Delete a module"""
    client = APIClient()
    try:
        client.modules.delete(module_id, reason=reason)
        console.print(f"[green]Successfully deleted module {module_id}[/green]")
    except APIError as e:
        error_console.print(f"[red]Error:[/red] {e}")
        raise click.Abort() from e
