# -*- coding: utf-8 -*-
"""
NUD 自定义语法库：luck 抽奖库（教程实战示例）
==============================================
教程里从零写的库。NUD 里：
    /being/
    import luck
    奖品=["宝石","金币","宝箱"]
    /luck/抽取/奖品      ← 随机抽一个输出
    /luck/数字/1/100     ← 随机 1~100 整数
"""
import random

LIB_NAME = "luck"
LIB_VERSION = "1.0.0"
LIB_DESCRIPTION = "抽奖库：/luck/抽取/列表变量 或 /luck/数字/最小/最大"

import re

_NAME = r'[一-龥A-Za-z_][一-龥A-Za-z0-9_]*'

# 语法1：/luck/抽取/列表变量名
_RE_PICK = re.compile(r'^/luck/抽取/(' + _NAME + r')$')
# 语法2：/luck/数字/最小/最大（数字或变量）
_RE_NUM = re.compile(r'^/luck/数字/(' + _NAME + r'|\d+)/(' + _NAME + r'|\d+)$')


def parse_line(content, line_num, sm_imported):
    content = content.strip()
    m = _RE_PICK.match(content)
    if m:
        return {'type': 'LUCK_PICK', 'line': line_num, 'var': m.group(1)}, None
    m = _RE_NUM.match(content)
    if m:
        return {'type': 'LUCK_NUM', 'line': line_num, 'lo': m.group(1), 'hi': m.group(2)}, None
    if content.startswith('/luck/'):
        return None, '正确写法: /luck/抽取/列表变量 或 /luck/数字/最小/最大'
    return None, None


def execute(node, env, registry, moves, output=None):
    if node.type == 'LUCK_PICK':
        var = node.var
        if var not in env:
            return f"找不到变量 '{var}'（先赋值列表）"
        items = env[var]
        if not isinstance(items, list) or not items:
            return f"变量 '{var}' 不是列表或为空"
        text = str(random.choice(items))
    else:
        def _num(v):
            if v in env:
                return int(env[v])
            return int(v)
        lo, hi = _num(node.lo), _num(node.hi)
        if lo > hi:
            lo, hi = hi, lo
        text = str(random.randint(lo, hi))
    if output is not None:
        output.append((text, None))
    cb = env.get('_print_cb')
    if callable(cb):
        try:
            cb(text, None)
        except Exception:
            pass
    return None
