"""albus chat -- Send a message to an agent."""

from __future__ import annotations

import asyncio

import aiohttp

from server.transport.cli._models import ChatArgs


def cmd_chat(args: ChatArgs) -> int:
    """Send a message to an agent."""
    if not args.message:
        print("Error: message required")
        return 2

    async def _chat() -> int:
        url = f"http://{args.host}:{args.port}/api/v1/agents/{args.agent}/turn"
        timeout = aiohttp.ClientTimeout(total=300)

        try:
            async with aiohttp.ClientSession(timeout=timeout) as session:
                async with session.post(url, json={"message": args.message}) as resp:
                    if resp.status != 200:
                        print(f"Error: Server returned {resp.status}")
                        return 1
                    data = await resp.json()

                    if data.get("success"):
                        print(data.get("response", ""))
                        return 0
                    print(f"Error: {data.get('error', 'Unknown error')}")
                    return 1
        except Exception:
            print(f"Error: Cannot connect to server at {args.host}:{args.port}")
            print("Start the server first: albus server")
            return 1

    return asyncio.run(_chat())
