"""Chatixia CLI — deploy and run AI agents locally."""

from __future__ import annotations

import argparse
import sys

from chatixia import __version__


def main(argv: list[str] | None = None) -> int:
    """CLI entry point (registered as ``chatixia`` console script)."""
    parser = argparse.ArgumentParser(
        prog="chatixia",
        description="Deploy and run AI agents locally.",
    )
    parser.add_argument(
        "-V",
        "--version",
        action="version",
        version=f"chatixia {__version__}",
    )

    subparsers = parser.add_subparsers(dest="command")

    # -- chatixia run -------------------------------------------------------
    run_parser = subparsers.add_parser(
        "run",
        help="Run an agent from a manifest file",
    )
    run_parser.add_argument(
        "manifest",
        nargs="?",
        default="agent.yaml",
        help="Path to agent.yaml or agent directory (default: ./agent.yaml)",
    )
    run_parser.add_argument(
        "--daemon",
        action="store_true",
        help="Run in autonomous mode (goal-driven loop)",
    )
    run_parser.add_argument(
        "--once",
        metavar="MESSAGE",
        help="Send a single message and exit",
    )
    run_parser.add_argument(
        "--tick",
        type=int,
        default=30,
        help="Seconds between autonomous ticks (default: 30)",
    )

    # -- chatixia init ------------------------------------------------------
    init_parser = subparsers.add_parser(
        "init",
        help="Create a new agent manifest",
    )
    init_parser.add_argument(
        "name",
        nargs="?",
        default="my-agent",
        help="Agent name (default: my-agent)",
    )
    init_parser.add_argument(
        "-d",
        "--directory",
        default=".",
        help="Directory to create the manifest in (default: current)",
    )

    # -- chatixia hub -------------------------------------------------------
    hub_parser = subparsers.add_parser(
        "hub",
        help="Start the monitoring hub dashboard",
    )
    hub_parser.add_argument(
        "--host",
        default="0.0.0.0",
        help="Bind address (default: 0.0.0.0)",
    )
    hub_parser.add_argument(
        "--port",
        type=int,
        default=8002,
        help="Port (default: 8002)",
    )

    # -- chatixia validate --------------------------------------------------
    validate_parser = subparsers.add_parser(  # noqa: F841
        "validate",
        help="Validate an agent manifest",
    )
    validate_parser.add_argument(
        "manifest",
        nargs="?",
        default="agent.yaml",
        help="Path to agent.yaml (default: ./agent.yaml)",
    )

    args = parser.parse_args(argv)

    if args.command is None:
        parser.print_help()
        return 0

    if args.command == "run":
        return _cmd_run(args)
    elif args.command == "init":
        return _cmd_init(args)
    elif args.command == "hub":
        return _cmd_hub(args)
    elif args.command == "validate":
        return _cmd_validate(args)

    return 0


# ---------------------------------------------------------------------------
# Subcommand handlers
# ---------------------------------------------------------------------------


def _cmd_run(args: argparse.Namespace) -> int:
    """Execute the ``run`` subcommand."""
    from chatixia.config import load_config
    from chatixia.runner import AgentRunner

    try:
        config = load_config(args.manifest)
    except FileNotFoundError as exc:
        print(f"Error: {exc}", file=sys.stderr)
        return 1
    except Exception as exc:
        print(f"Error loading manifest: {exc}", file=sys.stderr)
        return 1

    runner = AgentRunner(config)

    try:
        if args.once:
            return runner.run_once(args.once)
        elif args.daemon:
            return runner.run_daemon(tick_interval=args.tick)
        else:
            return runner.run_interactive()
    except KeyboardInterrupt:
        print("\n👋 Goodbye!")
        return 0
    except RuntimeError as exc:
        print(f"Error: {exc}", file=sys.stderr)
        return 1


def _cmd_hub(args: argparse.Namespace) -> int:
    """Execute the ``hub`` subcommand."""
    from chatixia.hub import run_hub

    print(f"🌐 Chatixia Hub starting on http://{args.host}:{args.port}")
    run_hub(host=args.host, port=args.port)
    return 0


def _cmd_init(args: argparse.Namespace) -> int:
    """Execute the ``init`` subcommand."""
    from chatixia.scaffold import write_scaffold

    try:
        write_scaffold(args.name, args.directory)
        return 0
    except FileExistsError as exc:
        print(f"Error: {exc}", file=sys.stderr)
        return 1
    except Exception as exc:
        print(f"Error: {exc}", file=sys.stderr)
        return 1


def _cmd_validate(args: argparse.Namespace) -> int:
    """Execute the ``validate`` subcommand."""
    from chatixia.config import load_config

    try:
        config = load_config(args.manifest)
    except FileNotFoundError as exc:
        print(f"Error: {exc}", file=sys.stderr)
        return 1
    except Exception as exc:
        print(f"Error parsing manifest: {exc}", file=sys.stderr)
        return 1

    errors = config.validate()

    if errors:
        print(f"❌ {len(errors)} error(s) in {args.manifest}:")
        for err in errors:
            print(f"  • {err}")
        return 1

    # Print summary
    print(f"✅ {args.manifest} is valid")
    print(f"   Agent:    {config.name}")
    print(f"   Provider: {config.provider}")
    builtin_count = len(config.skills.builtin)
    custom_count = len(config.skills.dirs)
    print(f"   Skills:   {builtin_count} builtin, {custom_count} custom dir(s)")
    print(f"   Goals:    {len(config.goals)}")

    missing_env = config.check_env()
    if missing_env:
        print(f"\n⚠️  Missing env vars: {', '.join(missing_env)}")
        print(f"   Set them in {config.env_file} or your shell environment.")

    return 0


if __name__ == "__main__":
    sys.exit(main())
