# Copyright (c) Metis. All rights reserved.

"""mantis-agent CLI — runs a LitAgent inside a platform container.

This eliminates the need for hand-written entrypoint.py files in agent
containers. The orchestrator sets ``MANTIS_STORE_URL`` and
``MANTIS_RUN_ID``; this command handles everything else.

Usage::

    # In Dockerfile:
    CMD ["mantis-agent", "--agent", "crm_agent:crm_agent"]

    # Or manually:
    MANTIS_STORE_URL=http://host:9876 MANTIS_RUN_ID=run-abc \
        mantis-agent --agent my_module:my_agent
"""

from __future__ import annotations

import asyncio
import importlib
import logging
import sys
from typing import Optional


def _resolve_agent(agent_ref: str):
    """Resolve 'module:attribute' to a LitAgent instance.

    Args:
        agent_ref: Reference like 'crm_agent:crm_agent' (module:attr).

    Returns:
        The resolved LitAgent instance.

    Raises:
        ValueError: If the reference format is invalid.
        ImportError: If the module can't be imported.
        AttributeError: If the attribute doesn't exist in the module.
    """
    if ":" not in agent_ref:
        raise ValueError(f"Agent reference must be in 'module:attribute' format, got: '{agent_ref}'")

    module_path, attr_name = agent_ref.rsplit(":", 1)
    module = importlib.import_module(module_path)
    agent = getattr(module, attr_name)
    return agent


async def _run_agent(agent_ref: str, worker_id: int = 0) -> None:
    """Initialize store, tracer, runner, and execute rollouts.

    Args:
        agent_ref: Module:attribute reference to the LitAgent.
        worker_id: Worker ID for this runner instance.
    """
    logger = logging.getLogger(__name__)

    # 1. Resolve agent
    logger.info(f"Resolving agent: {agent_ref}")
    agent = _resolve_agent(agent_ref)
    logger.info(f"Agent resolved: {type(agent).__name__}")

    # 2. Create store client (connects to worker's StoreServer via HTTP)
    from mantisdk.store.insight import create_platform_store_client_from_env

    store = create_platform_store_client_from_env()
    logger.info(f"Store client created")

    # 3. Create tracer
    from mantisdk.tracer.otel import OtelTracer

    tracer = OtelTracer()

    # 4. Create and initialize runner
    from mantisdk.runner import LitAgentRunner

    runner = LitAgentRunner(tracer=tracer)
    runner.init(agent)
    runner.init_worker(worker_id=worker_id, store=store)
    logger.info(f"Runner initialized (worker_id={worker_id})")

    # 5. Poll and execute rollouts
    await runner.iter()


def main() -> None:
    """CLI entry point for ``mantis-agent``."""
    try:
        import typer
    except ImportError:
        print(
            "typer is required for mantis-agent. " "Install with: pip install mantisdk[agent]",
            file=sys.stderr,
        )
        sys.exit(1)

    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s %(levelname)-8s [%(name)s] %(message)s",
    )

    app = typer.Typer(
        name="mantis-agent",
        help="Mantis agent runner — executes rollouts inside a platform container.",
        no_args_is_help=True,
    )

    @app.command()
    def run(
        agent: str = typer.Option(
            ...,
            "--agent",
            "-a",
            help="Agent reference in module:attribute format (e.g., crm_agent:crm_agent).",
        ),
        worker_id: int = typer.Option(
            0,
            "--worker-id",
            "-w",
            help="Worker ID for this runner instance.",
        ),
    ) -> None:
        """Start the agent runner, polling for rollouts from the store server."""
        asyncio.run(_run_agent(agent, worker_id=worker_id))

    app()


if __name__ == "__main__":
    main()
