import re

LIB_NAME = "move"
LIB_VERSION = "1.0.0"
LIB_DESCRIPTION = "按钮移动语法库，支持瞬移和平滑滑动"

_MOVE_RE = re.compile(
    r'^/m/([a-zA-Z][a-zA-Z0-9]*)/x\s*=\s*(-?\d+)\s*/\s*y\s*=\s*(-?\d+)\s*$'
)

_SM_MOVE_RE = re.compile(
    r'^sm:/m/([a-zA-Z][a-zA-Z0-9]*)/x\s*=\s*(-?\d+)\s*/\s*y\s*=\s*(-?\d+)\s*$'
)

X_MIN, X_MAX = -240, 240
Y_MIN, Y_MAX = -180, 180

MOVE = 'MOVE'

_parser = None
_executor = None


def _clamp(v: int, lo: int, hi: int) -> int:
    return max(lo, min(hi, v))


def parse_line(content: str, line_num: int, sm_imported: bool):
    if content.startswith('sm:/m/'):
        m = _SM_MOVE_RE.match(content)
        if m:
            if not sm_imported:
                return None, f'sm 滑动语法需要先 import sm（在第 {line_num} 行之前加一行 import sm）'
            x = _clamp(int(m.group(2)), X_MIN, X_MAX)
            y = _clamp(int(m.group(3)), Y_MIN, Y_MAX)
            return {
                'type': MOVE,
                'line': line_num,
                'name': m.group(1),
                'x': x,
                'y': y,
                'smooth': True,
            }, None
        return None, f'滑动语法写错了: {content}（正确写法: sm:/m/名字/x=N/y=M）'

    if content.startswith('/m/'):
        m = _MOVE_RE.match(content)
        if m:
            x = _clamp(int(m.group(2)), X_MIN, X_MAX)
            y = _clamp(int(m.group(3)), Y_MIN, Y_MAX)
            return {
                'type': MOVE,
                'line': line_num,
                'name': m.group(1),
                'x': x,
                'y': y,
                'smooth': False,
            }, None
        return None, f'移动语法写错了: {content}（正确写法: /m/名字/x=N/y=M）'

    return None, None


def execute(node, env, registry, moves, output=None):
    name = getattr(node, 'name', node.get('name', '')) if isinstance(node, dict) else node.name
    x = getattr(node, 'x', node.get('x', 0)) if isinstance(node, dict) else node.x
    y = getattr(node, 'y', node.get('y', 0)) if isinstance(node, dict) else node.y
    smooth = getattr(node, 'smooth', node.get('smooth', False)) if isinstance(node, dict) else node.smooth
    duration = getattr(node, 'duration', node.get('duration', None)) if isinstance(node, dict) else getattr(node, 'duration', None)

    for b in registry:
        if b.get('name') == name:
            if not smooth:
                b['x'] = x
                b['y'] = y
            else:
                moves.append({'name': name, 'x': x, 'y': y, 'smooth': True,
                              'duration': duration})
            return None

    return f"找不到名为 '{name}' 的按钮，无法移动"


def register(parser_func, executor_func):
    global _parser, _executor
    _parser = parser_func
    _executor = executor_func


def get_parser():
    return _parser or parse_line


def get_executor():
    return _executor or execute
