import typer
from rich.table import Table
from rich.console import Console
from rich import box

app = typer.Typer(help="Manage organizations.")

@app.command("list")
def list_orgs(ctx: typer.Context):
    """List orgs you have access to."""
    orgs = ctx.obj.context.get_orgs()
    active = ctx.obj.context.get_active_org()
    active_id = active["org_id"] if active else None

    if not orgs:
        typer.echo("No orgs found. Run 'acemist self' first to populate.")
        return

    table = Table(box=box.ROUNDED, padding=(0, 1))
    table.add_column("")
    table.add_column("Name", style="bold")
    table.add_column("Org ID", style="dim")

    for org in orgs:
        marker = "*" if org["org_id"] == active_id else " "
        table.add_row(marker, org["name"], org["org_id"])

    Console().print(table)

@app.command("use")
def use_org(org_id: str = typer.Argument(..., help="Org ID to activate"), ctx: typer.Context = typer.Context):
    """Set active org."""
    ctx.obj.context.set_active_org(org_id)
    typer.echo(f"Active org set to {org_id}")