# -*- coding: utf-8 -*-
"""
Slash Commands 模块
支持从 .md 文件加载用户自定义斜杠命令，文件名即命令名，内容为 Prompt 模板。
模板支持 {{var}} 变量替换和 $USER_INPUT 占位符（用户在命令后追加的输入）。
"""
import re
from pathlib import Path
from typing import Dict, List, Optional


class SlashCommand:
    """单个 slash 命令：名称 + Prompt 模板，支持变量展开。"""

    def __init__(self, name: str, template: str):
        self.name = name
        self.template = template

    def expand(self, variables: Dict[str, str]) -> str:
        """展开模板变量。
        - {{var}} 替换为 variables[var]，缺失保留原占位符
        - $VAR 替换为 variables[VAR]，缺失保留原占位符
        """
        result = self.template
        for key, value in variables.items():
            result = result.replace("{{" + key + "}}", value)
            result = result.replace("$" + key, value)
        return result


class SlashCommandRegistry:
    """从指定目录加载 .md 文件作为 slash 命令的注册表。"""

    def __init__(self, commands_dir: Optional[Path] = None):
        self._commands: Dict[str, SlashCommand] = {}
        if commands_dir is not None:
            self._load_from_dir(commands_dir)

    def _load_from_dir(self, commands_dir: Path) -> None:
        """从目录加载所有顶层 .md 文件作为命令"""
        if not commands_dir.exists() or not commands_dir.is_dir():
            return
        for md_file in commands_dir.iterdir():
            if not md_file.is_file() or md_file.suffix != ".md":
                continue
            name = md_file.stem
            try:
                template = md_file.read_text(encoding="utf-8")
            except Exception:
                continue
            self._commands[name] = SlashCommand(name, template)

    def get(self, name: str) -> Optional[SlashCommand]:
        """按名获取命令，未定义返回 None"""
        return self._commands.get(name)

    def list_names(self) -> List[str]:
        """返回所有已加载命令名"""
        return list(self._commands.keys())

    def expand_command(self, name: str, variables: Dict[str, str]) -> Optional[str]:
        """获取并展开指定命令，未定义返回 None"""
        cmd = self.get(name)
        if cmd is None:
            return None
        return cmd.expand(variables)


def create_default_registry() -> SlashCommandRegistry:
    """创建指向 ~/.abyss/commands/ 的默认注册表"""
    commands_dir = Path.home() / ".abyss" / "commands"
    return SlashCommandRegistry(commands_dir=commands_dir)
