"""AI-callable tool fonksiyonları. Obje yok, sadece string in/out."""

from .file_transport import FileTransport, DEFAULT_BASE_DIR
from .tunnel import Tunnel

_transport = FileTransport(DEFAULT_BASE_DIR)


def _get_tunnel(tunnel_id: str, agent_name: str) -> Tunnel:
    return Tunnel(tunnel_id, agent_name, _transport)


def create_tunnel(agent_name: str) -> dict:
    """Yeni tunnel oluştur.

    Args:
        agent_name: Oluşturan agent'ın adı (otomatik admin olur)

    Returns:
        {"tunnel_id": "abc123", "agent": "...", "role": "admin"}
    """
    import os
    tunnel_id = os.urandom(4).hex()
    _transport.create(tunnel_id, agent_name)
    return {"tunnel_id": tunnel_id, "agent": agent_name, "role": "admin"}


def join_tunnel(tunnel_id: str, agent_name: str) -> dict:
    """Mevcut tunnel'a katıl.

    Args:
        tunnel_id: Katılınacak tunnel
        agent_name: Katılan agent'ın adı

    Returns:
        {"tunnel_id": "...", "agent": "...", "members": [...]}
    """
    _transport.join(tunnel_id, agent_name)
    members = _transport.members(tunnel_id)
    return {"tunnel_id": tunnel_id, "agent": agent_name, "members": members}


def send_message(tunnel_id: str, agent_name: str, message: str, to: str | None = None) -> dict:
    """Tunnel'a mesaj gönder.

    Args:
        tunnel_id: Hedef tunnel
        agent_name: Gönderen agent
        message: Mesaj içeriği
        to: (opsiyonel) Belirli bir agent'a gönder. None = broadcast.

    Returns:
        {"status": "sent", "from": "...", "to": "..." or "broadcast", "message_id": "..."}
    """
    tun = _get_tunnel(tunnel_id, agent_name)
    msg = tun.send(message, to=to)
    return {
        "status": "sent",
        "from": agent_name,
        "to": to or "broadcast",
        "message_id": msg.id,
    }


def read_message(tunnel_id: str, agent_name: str, from_agent: str | None = None) -> dict:
    """Mailbox'tan bir mesaj oku (non-blocking).

    Args:
        tunnel_id: Tunnel
        agent_name: Okuyan agent
        from_agent: (opsiyonel) Sadece bu agent'tan gelen mesajları oku

    Returns:
        {"status": "message", "from": "...", "message": "...", "ts": ...}
        veya {"status": "empty"}
    """
    tun = _get_tunnel(tunnel_id, agent_name)
    msg = tun.receive(from_=from_agent)
    if msg:
        return {"status": "message", "from": msg.from_, "message": msg.payload, "ts": msg.ts}
    return {"status": "empty"}


def wait_for_message(tunnel_id: str, agent_name: str, from_agent: str | None = None, timeout: int = 30) -> dict:
    """Mesaj gelene kadar bekle (blocking).

    Args:
        tunnel_id: Tunnel
        agent_name: Bekleyen agent
        from_agent: (opsiyonel) Sadece bu agent'tan bekle
        timeout: Maksimum bekleme süresi (saniye)

    Returns:
        {"status": "message", "from": "...", "message": "...", "ts": ...}
        veya {"status": "timeout"}
    """
    import time
    tun = _get_tunnel(tunnel_id, agent_name)
    deadline = time.time() + timeout
    while time.time() < deadline:
        msg = tun.receive(from_=from_agent)
        if msg:
            return {"status": "message", "from": msg.from_, "message": msg.payload, "ts": msg.ts}
        time.sleep(0.1)
    return {"status": "timeout"}


def send_and_wait(tunnel_id: str, agent_name: str, message: str, to: str | None = None, wait_from: str | None = None, timeout: int = 30) -> dict:
    """Mesaj gönder ve cevap bekle.

    Args:
        tunnel_id: Tunnel
        agent_name: Gönderen/bekleyen agent
        message: Gönderilecek mesaj
        to: (opsiyonel) Kime gönder
        wait_from: (opsiyonel) Kimden cevap bekle (default: to ile aynı)
        timeout: Maksimum bekleme süresi (saniye)

    Returns:
        {"status": "message", "from": "...", "message": "...", "ts": ...}
        veya {"status": "timeout", "sent_message_id": "..."}
    """
    tun = _get_tunnel(tunnel_id, agent_name)
    sent = tun.send(message, to=to)
    wait_target = wait_from or to

    import time
    deadline = time.time() + timeout
    while time.time() < deadline:
        msg = tun.receive(from_=wait_target)
        if msg:
            return {"status": "message", "from": msg.from_, "message": msg.payload, "ts": msg.ts}
        time.sleep(0.1)
    return {"status": "timeout", "sent_message_id": sent.id}


def tunnel_info(tunnel_id: str) -> dict:
    """Tunnel bilgilerini getir.

    Returns:
        {"tunnel_id": "...", "members": [...], "admins": [...]}
    """
    return {
        "tunnel_id": tunnel_id,
        "members": _transport.members(tunnel_id),
        "admins": _transport.admins(tunnel_id),
    }


def list_tunnels() -> dict:
    """Tüm tunnel'ları listele.

    Returns:
        {"tunnels": [{"id": "...", "members": [...]}]}
    """
    result = []
    for tid in _transport.tunnels():
        result.append({"id": tid, "members": _transport.members(tid)})
    return {"tunnels": result}
