from __future__ import annotations

import asyncio
import re

_SAFE_PATTERN = re.compile(r"[^a-zA-Z0-9:\-_. ]")
_MAX_DISPLAY_LEN = 64
_MAX_GROUP_LEN = 64


def _sanitize(value: str, max_len: int) -> str:
    return _SAFE_PATTERN.sub("", value)[:max_len]


class TmuxInjector:
    def __init__(self, target_pane: str) -> None:
        self.target_pane = target_pane

    async def inject(self, text: str) -> bool:
        type_proc = await asyncio.create_subprocess_exec(
            "tmux", "send-keys", "-t", self.target_pane, "-l", text,
            stdout=asyncio.subprocess.DEVNULL,
            stderr=asyncio.subprocess.DEVNULL,
        )
        if await type_proc.wait() != 0:
            return False
        submit_proc = await asyncio.create_subprocess_exec(
            "tmux", "send-keys", "-t", self.target_pane, "Enter",
            stdout=asyncio.subprocess.DEVNULL,
            stderr=asyncio.subprocess.DEVNULL,
        )
        return await submit_proc.wait() == 0

    async def inject_notification(
        self,
        from_display: str,
        group_id: str,
    ) -> bool:
        safe_from = _sanitize(from_display, _MAX_DISPLAY_LEN)
        safe_group = _sanitize(group_id, _MAX_GROUP_LEN)
        text = (
            f"[ALSO NOTF] New message in group '{safe_group}' from {safe_from}. "
            f"Call the read_new_messages tool to read it."
        )
        return await self.inject(text)
