"""keryx — WhatsApp messaging via wacli.

Tools:
  keryx_read_messages — read a conversation
  keryx_draft_send    — draft a message (NEVER sends directly)
  keryx_list_chats    — list recent chats
  keryx_sync_status   — check the wacli daemon
"""

from vivesca.base import run_cli
from vivesca.schemas import StatusOutput, ToolOutput

from fastmcp.tools import tool
from mcp.types import ToolAnnotations

BINARY = "~/bin/keryx"


class MessagesResult(ToolOutput):
    """WhatsApp conversation messages."""
    messages: str


class DraftResult(ToolOutput):
    """Draft message shell block for manual execution."""
    draft: str


class ChatsResult(ToolOutput):
    """Recent WhatsApp chats listing."""
    chats: str


@tool(
    name="keryx_read_messages",
    description="Read a WhatsApp conversation. Merges phone + LID JID threads.",
    annotations=ToolAnnotations(readOnlyHint=True, destructiveHint=False),
)
def keryx_read_messages(name: str, limit: int = 20) -> MessagesResult:
    """Read WhatsApp conversation with a contact."""
    result = run_cli(BINARY, ["read", name, "--limit", str(limit)])
    return MessagesResult(messages=result)


@tool(
    name="keryx_draft_send",
    description="Draft a WhatsApp message. NEVER sends — returns shell block for manual execution.",
    annotations=ToolAnnotations(readOnlyHint=True, destructiveHint=False),
)
def keryx_draft_send(name: str, message: str) -> DraftResult:
    """Draft a WhatsApp message (does not send)."""
    result = run_cli(BINARY, ["send", name, message, "--copy"])
    return DraftResult(draft=result)


@tool(
    name="keryx_list_chats",
    description="List recent WhatsApp chats.",
    annotations=ToolAnnotations(readOnlyHint=True, destructiveHint=False),
)
def keryx_list_chats(limit: int = 20) -> ChatsResult:
    """List recent WhatsApp chats."""
    result = run_cli(BINARY, ["chats", "--limit", str(limit)])
    return ChatsResult(chats=result)


@tool(
    name="keryx_sync_status",
    description="Check the wacli sync daemon status.",
    annotations=ToolAnnotations(readOnlyHint=True, destructiveHint=False),
)
def keryx_sync_status() -> StatusOutput:
    """Check the wacli sync daemon status."""
    result = run_cli(BINARY, ["sync", "status"])
    return StatusOutput(status="ok", message=result)
