"""CLI commands for agentboard."""

from __future__ import annotations

import click

from agentboard.board import (
    COLUMNS,
    PRIORITIES,
    TAGS,
    find_board_root,
    init_board,
    load_board,
    board_path,
)


@click.group(invoke_without_command=True)
@click.pass_context
def cli(ctx):
    """Bidirectional kanban board for AI agents and humans."""
    if ctx.invoked_subcommand is None:
        ctx.invoke(serve)


@cli.command()
@click.option("--host", default="127.0.0.1", help="Host to bind to.")
@click.option("--port", default=5555, type=int, help="Port to bind to.")
@click.option("--no-open", is_flag=True, help="Don't open browser automatically.")
def serve(host, port, no_open):
    """Start the agentboard web UI (default command)."""
    root = find_board_root()
    if root is None:
        click.echo("No .agentboard/ found. Run 'agentboard init' first.")
        raise SystemExit(1)
    from agentboard.server import serve as run_server
    run_server(host=host, port=port, open_browser=not no_open)


@cli.command()
@click.option("--project", default="", help="Project name (defaults to directory name).")
def init(project):
    """Initialize a new agentboard in the current directory."""
    bp = init_board(project=project)
    click.echo(f"Initialized agentboard at {bp}")


@cli.command()
def status():
    """Print a summary of tasks per column."""
    root = find_board_root()
    if root is None:
        click.echo("No .agentboard/ found. Run 'agentboard init' first.")
        raise SystemExit(1)
    board = load_board(board_path(root))
    click.echo(f"Project: {board.project or '(unnamed)'}")
    click.echo(f"Updated: {board.updated_at} by {board.updated_by}")
    click.echo("")
    total = 0
    for col in board.columns:
        tasks = board.tasks_in_column(col)
        count = len(tasks)
        total += count
        label = col.replace("_", " ").title()
        click.echo(f"  {label:15s} {count}")
    click.echo(f"  {'Total':15s} {total}")


@cli.command()
@click.argument("title")
@click.option("--column", type=click.Choice(COLUMNS), default="backlog", help="Column to add task to.")
@click.option("--tag", type=click.Choice(TAGS), default=None, help="Task tag.")
@click.option("--priority", type=click.Choice(PRIORITIES), default=None, help="Task priority.")
@click.option("--assign", type=click.Choice(["human", "agent"]), default=None, help="Assign task to human or agent.")
def add(title, column, tag, priority, assign):
    """Add a task to the board."""
    root = find_board_root()
    if root is None:
        click.echo("No .agentboard/ found. Run 'agentboard init' first.")
        raise SystemExit(1)
    bp = board_path(root)
    board = load_board(bp)
    task = board.add_task(title=title, column=column, tag=tag, priority=priority, assigned_to=assign, created_by="user")
    from agentboard.board import save_board
    save_board(board, bp)
    click.echo(f"Added task {task.id}: {task.title} -> {column}")
