#!/usr/bin/env python3
"""Start a mesh agent node.

Usage:
    python -m mesh.scripts.start_agent [--config mesh_config.yaml] [--port 8400]
"""
from __future__ import annotations

import argparse
import asyncio
import logging
import sys
from pathlib import Path

import uvicorn


def main():
    parser = argparse.ArgumentParser(description="Start mesh agent")
    parser.add_argument("--config", default="mesh/mesh_config.yaml", help="Config file")
    parser.add_argument("--port", type=int, default=None, help="Override agent port")
    parser.add_argument("--log-level", default=None, help="Log level")
    args = parser.parse_args()

    # Add project root to path
    project_root = Path(__file__).resolve().parents[2]
    sys.path.insert(0, str(project_root))

    from mesh.config import MeshConfig
    from mesh.agent.node_agent import NodeAgent
    from mesh.api.agent_api import app, wire_agent

    config = MeshConfig.from_yaml(args.config)
    if args.port:
        config.node.agent_port = args.port
    if args.log_level:
        config.log_level = args.log_level

    logging.basicConfig(
        level=getattr(logging, config.log_level.upper()),
        format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
    )
    logger = logging.getLogger("mesh.agent")
    logger.info("Starting agent on port %d", config.node.agent_port)

    # Create agent and wire into app (lifespan in agent_api.py handles start/stop)
    agent = NodeAgent(config)
    wire_agent(node_agent=agent)

    uvicorn.run(app, host=config.node.host, port=config.node.agent_port,
                log_level=config.log_level.lower())


if __name__ == "__main__":
    main()
