import typer
from typing import Optional
from acemist.mist.mist import Mist, Region
from acemist.rest.rest import RestClient

app = typer.Typer(help="Context management. Configure API url etc.")

@app.command()
def add(
    name: str = typer.Option(..., "--name", "-n"),
    region: Region = typer.Option(..., "--region", "-r"),
    api_token: Optional[str] = typer.Option(None, "--token", "-t"),
    org_id: Optional[str] = typer.Option(None, "--org-id", "-o"),
    site_id:str = typer.Option(..., "--site-id", "-s"),
    ctx: typer.Context = typer.Context
):
    """Set or update a context."""
    cm = ctx.obj.context

    if api_token is None:
        api_token = typer.prompt("API token", hide_input=True)

    cm.set_context(name, region, api_token, org_id=org_id, site_id=site_id)

    # Auto-populate org from /self if org_id not provided
    if not org_id:
        try:
            mist = ctx.obj.mist
            mist._poplulate_self()
            data = mist.user_data
            orgs = [p for p in data.get("privileges", []) if p.get("scope") == "org"]
            if len(orgs) == 1:
                cm.update_org(orgs[0]["org_id"], orgs[0]["name"])
                typer.echo(f"Org auto-set to '{orgs[0]['name']}'")
            elif len(orgs) > 1:
                typer.echo("Multiple orgs found. Set one with: acemist context set-org --org-id <id>")
                for o in orgs:
                    typer.echo(f"  {o['org_id']}  {o['name']}")
        except Exception as e:
            typer.echo(f"Could not auto-detect org: {e}", err=True)

    typer.echo(f"Context '{name}' set and activated!")

@app.command()
def list(ctx: typer.Context):
    """List all saved contexts."""
    cm = ctx.obj.context
    contexts = cm.data.get('contexts', {})

    active = cm.data.get("active_context")
    if not contexts:
        typer.echo("No contexts saved.")
        return
    for name, data in contexts.items():
        marker = "*" if name == active else " "

        region = data.get("region", "")
        apiurl = data.get("apiurl", "")
        site_id= data.get("site_id","")
        typer.echo(f"{marker} {name}@{region} ({apiurl}) ({site_id})")

@app.command()
def use(name: str, ctx: typer.Context):
    """Set active context by name."""
    ctx.obj.set_active(name)
    typer.echo(f"Active context set to '{name}'")
