from curses.ascii import isdigit
from pathlib import Path

import nonebot
import nonebot.adapters
import nonebot.adapters.discord
import nonebot.rule
from nonebot import on_command
from nonebot_plugin_alconna import Alconna, Args, UniMessage, on_alconna

from konabot.common.nb.is_admin import is_admin
from konabot.common.path import DOCS_PATH_MAN1, DOCS_PATH_MAN3, DOCS_PATH_MAN7, DOCS_PATH_MAN8

def search_man(section: int) -> dict[tuple[int, str], Path]:
    base_path = {
        1: DOCS_PATH_MAN1,
        3: DOCS_PATH_MAN3,
        7: DOCS_PATH_MAN7,
        8: DOCS_PATH_MAN8,
    }.get(section, DOCS_PATH_MAN1)

    res: dict[tuple[int, str], Path] = {}
    for fp in base_path.iterdir():
        if fp.suffix != '.txt':
            continue
        name = fp.name.lower().removesuffix('.txt')
        res[(section, name)] = fp
    return res


man = on_alconna(Alconna(
    'man',
    Args['section', int | None],
    Args['doc', str | None],
))

@man.handle()
async def _(
    section: int | None,
    doc: str | None,
    event: nonebot.adapters.Event,
):
    if doc is not None and section is None and all(isdigit(c) for c in doc):
        section = int(doc)
        doc = None

    if section is not None and section not in {1, 3, 7, 8}:
        await man.send(
            UniMessage().text(f"你所指定的文档类型 {section} 不在可用范围内")
        )
        return

    if doc is None:
        # 检索模式
        if section is None:
            section_set = {1}
        else:
            section_set = {section}
        if 1 in section_set and is_admin(event):
            section_set.add(8)
        mans: list[str] = []
        for section in section_set:
            mans += [f"{n}({s})" for s, n in search_man(section).keys()]
        mans.sort()
        
        await man.send(UniMessage().text(
            (
                "★此方 BOT 使用帮助★\n"
                "使用 man <指令名> 查询某个指令的名字\n\n"
                "可供查询的指令清单："
            )
            + ", ".join(mans)
            + "\n\n例如，使用 man man 来查询 man 指令的使用方法"
        ))
    else:
        # 查阅模式
        if section is None:
            section_set = {1}
        else:
            section_set = {section}
        if 1 in section_set and is_admin(event):
            section_set.add(8)
        if 8 in section_set and not is_admin(event):
            await man.send(UniMessage().text("你没有查看该指令类型的权限"))
            return
        mans_dict: dict[tuple[int, str], Path] = {}
        for section in section_set:
            mans_dict: dict[tuple[int, str], Path] = {**mans_dict, **search_man(section)}
        mans_dict_2 = {key[1]: val for key, val in mans_dict.items()}
        mans_fp = mans_dict_2.get(doc.lower())
        if mans_fp is None:
            await man.send(UniMessage().text("你所检索的指令不存在"))
            return
        mans_msg = mans_fp.read_text('utf-8', 'replace')
        if isinstance(event, nonebot.adapters.discord.event.MessageEvent):
            mans_msg = f'```\n{mans_msg}\n```'
        await man.send(UniMessage().text(mans_msg))


help_deprecated = on_command('help', rule=nonebot.rule.to_me())

@help_deprecated.handle()
async def _():
    await help_deprecated.send('你可以使用 man 指令来查询此方 BOT 的帮助')
