"""Brain — sends tasks to OpenClaw for execution via sessions_spawn-like webhook."""

import logging
import httpx

from config import OPENCLAW_URL, OPENCLAW_TOKEN

logger = logging.getLogger("agent.brain")


async def think(task_title: str, task_description: str | None, project_name: str) -> str:
    """Send a task to OpenClaw and get the result."""
    prompt = f"""Ты — агент-кодер в проекте "{project_name}".

Задача: {task_title}
"""
    if task_description:
        prompt += f"\nОписание:\n{task_description}\n"

    prompt += """
Выполни задачу и верни результат. Если нужно написать код — напиши его.
Если нужно проанализировать — проанализируй. Ответь кратко и по делу.
"""

    logger.info("Sending task to OpenClaw: %s", task_title)

    try:
        async with httpx.AsyncClient(timeout=300) as client:
            resp = await client.post(
                f"{OPENCLAW_URL}/hooks/agent",
                headers={
                    "Authorization": f"Bearer {OPENCLAW_TOKEN}",
                    "Content-Type": "application/json",
                },
                json={
                    "task": prompt,
                    "model": "anthropic/claude-sonnet-4",
                    "label": f"agent-coder-task",
                },
            )
            resp.raise_for_status()
            data = resp.json()
            result = data.get("result", data.get("message", str(data)))
            logger.info("OpenClaw responded: %s chars", len(result))
            return result
    except Exception as e:
        logger.error("OpenClaw error: %s", e)
        return f"Ошибка при выполнении: {e}"
