"""SPOQ CLI entry point.

Provides subcommands:
  spoq mcp       - Run the MCP server (stdio transport)
  spoq init      - Bootstrap SPOQ in a project directory
  spoq template  - Generate epic or map skeletons
  spoq version   - Show version
"""

import argparse
import sys

from spoq_server import __version__


def main():
    """Main CLI entry point."""
    parser = argparse.ArgumentParser(
        prog="spoq",
        description="SPOQ: Specialist Orchestrated Queuing for multi-agent AI development",
    )
    parser.add_argument(
        "--version", action="version", version=f"spoq {__version__}"
    )

    subparsers = parser.add_subparsers(dest="command", help="Available commands")

    # --- spoq mcp ---
    mcp_parser = subparsers.add_parser(
        "mcp", help="Run the SPOQ MCP server (stdio transport)"
    )
    mcp_parser.add_argument(
        "--transport", default="stdio", choices=["stdio"],
        help="Transport protocol (default: stdio)",
    )

    # --- spoq init ---
    init_parser = subparsers.add_parser(
        "init", help="Bootstrap SPOQ in a project directory"
    )
    init_parser.add_argument(
        "--target", default=".", help="Target directory (default: current directory)"
    )
    init_parser.add_argument(
        "--full", action="store_true",
        help="Include example epic and optional skills",
    )
    init_parser.add_argument(
        "--with-mcp", action="store_true",
        help="Configure .mcp.json to use the SPOQ MCP server",
    )
    init_parser.add_argument(
        "--upgrade", action="store_true",
        help="Upgrade an existing SPOQ installation",
    )

    # --- spoq template ---
    template_parser = subparsers.add_parser(
        "template", help="Generate epic or map skeletons"
    )
    template_sub = template_parser.add_subparsers(
        dest="template_type", help="Template type"
    )

    # spoq template epic <name> <task_count>
    epic_tmpl = template_sub.add_parser("epic", help="Generate an epic skeleton")
    epic_tmpl.add_argument("name", help="Epic name (converted to slug)")
    epic_tmpl.add_argument(
        "task_count", type=int, help="Number of task files (minimum 3)"
    )
    epic_tmpl.add_argument(
        "--path", default="", help="Base path (default: spoq/epics/active/)"
    )

    # spoq template map <name> <epic_count>
    map_tmpl = template_sub.add_parser("map", help="Generate a map skeleton")
    map_tmpl.add_argument("name", help="Map name (converted to slug)")
    map_tmpl.add_argument(
        "epic_count", type=int, help="Number of epic entries (minimum 2)"
    )
    map_tmpl.add_argument(
        "--path", default="", help="Base path (default: spoq/maps/active/)"
    )

    args = parser.parse_args()

    if args.command is None:
        parser.print_help()
        sys.exit(1)

    if args.command == "mcp":
        _cmd_mcp(args)
    elif args.command == "init":
        _cmd_init(args)
    elif args.command == "template":
        _cmd_template(args)


def _cmd_mcp(args):
    """Run the MCP server."""
    from spoq_server.server import main as mcp_main
    mcp_main()


def _cmd_init(args):
    """Bootstrap SPOQ in a project directory."""
    from spoq_server.init_cmd import run_init
    run_init(
        target=args.target,
        full=args.full,
        with_mcp=args.with_mcp,
        upgrade=args.upgrade,
    )


def _cmd_template(args):
    """Generate a template."""
    import json

    if args.template_type is None:
        print("Usage: spoq template {epic,map} <name> <count>")
        sys.exit(1)

    if args.template_type == "epic":
        from spoq_server.util_tools import spoq_generate_skeleton
        result = json.loads(spoq_generate_skeleton(
            name=args.name,
            task_count=args.task_count,
            path=args.path,
        ))
    elif args.template_type == "map":
        from spoq_server.map_tools import spoq_generate_map_skeleton
        result = json.loads(spoq_generate_map_skeleton(
            name=args.name,
            epic_count=args.epic_count,
            path=args.path,
        ))
    else:
        print(f"Unknown template type: {args.template_type}")
        sys.exit(1)

    if "error" in result:
        print(f"Error: {result['error']}", file=sys.stderr)
        sys.exit(1)

    path_key = "epic_path" if args.template_type == "epic" else "map_path"
    print(f"Created {args.template_type} at: {result[path_key]}")
    if "wave_distribution" in result:
        dist = result["wave_distribution"]
        print(f"  Wave 0: {dist.get('wave_0', 0)}, Wave 1: {dist.get('wave_1', 0)}, Later: {dist.get('later', 0)}")


if __name__ == "__main__":
    main()
