import re

from konabot.plugins.handle_text.base import (
    TextHandleResult,
    TextHandler,
    TextHandlerEnvironment,
)


def _get_text(istream: str | None, args: list[str]) -> str | None:
    """从 istream 或 args 中获取待处理文本"""
    if istream is not None:
        return istream
    if args:
        return " ".join(args)
    return None


class THTrim(TextHandler):
    name = "trim"
    keywords = ["strip", "去空格"]

    async def handle(
        self, env: TextHandlerEnvironment, istream: str | None, args: list[str]
    ) -> TextHandleResult:
        text = _get_text(istream, args)
        if text is None:
            return TextHandleResult(1, "trim 使用方法：trim [文本]\n去除首尾空白字符")
        return TextHandleResult(0, text.strip())


class THLTrim(TextHandler):
    name = "ltrim"
    keywords = ["lstrip"]

    async def handle(
        self, env: TextHandlerEnvironment, istream: str | None, args: list[str]
    ) -> TextHandleResult:
        text = _get_text(istream, args)
        if text is None:
            return TextHandleResult(1, "ltrim 使用方法：ltrim [文本]\n去除左侧空白字符")
        return TextHandleResult(0, text.lstrip())


class THRTrim(TextHandler):
    name = "rtrim"
    keywords = ["rstrip"]

    async def handle(
        self, env: TextHandlerEnvironment, istream: str | None, args: list[str]
    ) -> TextHandleResult:
        text = _get_text(istream, args)
        if text is None:
            return TextHandleResult(1, "rtrim 使用方法：rtrim [文本]\n去除右侧空白字符")
        return TextHandleResult(0, text.rstrip())


class THSqueeze(TextHandler):
    name = "squeeze"
    keywords = ["压缩空白"]

    async def handle(
        self, env: TextHandlerEnvironment, istream: str | None, args: list[str]
    ) -> TextHandleResult:
        text = _get_text(istream, args)
        if text is None:
            return TextHandleResult(
                1, "squeeze 使用方法：squeeze [文本]\n将连续空白字符压缩为单个空格"
            )
        return TextHandleResult(0, re.sub(r"[ \t]+", " ", text))


class THLines(TextHandler):
    name = "lines"
    keywords = ["行处理"]

    async def handle(
        self, env: TextHandlerEnvironment, istream: str | None, args: list[str]
    ) -> TextHandleResult:
        # lines <子命令> [文本]
        # 子命令: trim | empty | squeeze
        if len(args) < 1:
            return TextHandleResult(
                1,
                "lines 使用方法：lines <子命令> [文本]\n"
                "子命令：\n"
                "  trim    - 去除每行首尾空白\n"
                "  empty   - 去除所有空行\n"
                "  squeeze - 将连续空行压缩为一行",
            )

        subcmd = args[0]
        text = (
            istream
            if istream is not None
            else (" ".join(args[1:]) if len(args) > 1 else None)
        )
        if text is None:
            return TextHandleResult(1, "请提供需要处理的文本（通过管道或参数）")

        raw_lines = text.split("\n")

        match subcmd:
            case "trim":
                result = "\n".join(line.strip() for line in raw_lines)
            case "empty":
                result = "\n".join(line for line in raw_lines if line.strip())
            case "squeeze":
                squeezed: list[str] = []
                prev_empty = False
                for line in raw_lines:
                    is_empty = not line.strip()
                    if is_empty:
                        if not prev_empty:
                            squeezed.append("")
                        prev_empty = True
                    else:
                        squeezed.append(line)
                        prev_empty = False
                result = "\n".join(squeezed)
            case _:
                return TextHandleResult(
                    1, f"未知子命令：{subcmd}\n可用：trim, empty, squeeze"
                )

        return TextHandleResult(0, result)
