"""Entry point for the peon-goblin sales agent.

Usage::

    peon-goblin [--api-url URL] [--api-key KEY] [--model MODEL] [--poll-interval SEC] [--project-id ID]

Environment variables ``PEON_API_URL`` and ``PEON_API_KEY`` are used as
defaults for ``--api-url`` and ``--api-key`` respectively.
"""

from __future__ import annotations

import argparse
import asyncio
import logging
import os
import sys

log = logging.getLogger("peon-goblin")


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="peon-goblin",
        description="Sprocket, the sales goblin — researches leads, scores them, reports to Discord.",
    )
    parser.add_argument(
        "--api-url",
        default=os.environ.get("PEON_API_URL", "http://127.0.0.1:8420"),
        help="Peon REST API base URL (default: PEON_API_URL or http://127.0.0.1:8420)",
    )
    parser.add_argument(
        "--api-key",
        default=os.environ.get("PEON_API_KEY", ""),
        help="Peon API key for authentication (default: PEON_API_KEY env var)",
    )
    parser.add_argument(
        "--model",
        default="claude-sonnet-4-20250514",
        help="Anthropic model to use (default: claude-sonnet-4-20250514)",
    )
    parser.add_argument(
        "--poll-interval",
        type=int,
        default=600,
        help="Polling interval in seconds (default: 600 = 10 minutes)",
    )
    parser.add_argument(
        "--project-id",
        default="pyrabbit/teamroom",
        help="Project ID to fetch leads from (default: pyrabbit/teamroom)",
    )
    parser.add_argument(
        "-v", "--verbose",
        action="store_true",
        help="Enable debug logging",
    )
    return parser


def main() -> None:
    """CLI entry point for peon-goblin."""
    parser = _build_parser()
    args = parser.parse_args()

    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
    )

    if not os.environ.get("ANTHROPIC_API_KEY") and not os.environ.get("CLAUDE_CODE_OAUTH_TOKEN"):
        log.error("ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN environment variable is required")
        sys.exit(1)

    log.info("Time is money, friend!  Starting Sprocket sales goblin...")
    log.info("API URL: %s", args.api_url)
    log.info("Model: %s", args.model)
    log.info("Poll interval: %ds", args.poll_interval)
    log.info("Project: %s", args.project_id)

    from peon_mcp.goblin.agent import run_agent_loop  # noqa: E402

    try:
        asyncio.run(
            run_agent_loop(
                api_url=args.api_url,
                api_key=args.api_key,
                model=args.model,
                poll_interval=args.poll_interval,
                project_id=args.project_id,
            )
        )
    except KeyboardInterrupt:
        log.info("Sprocket closing up shop.  Catch ya later, boss!")


if __name__ == "__main__":
    main()
