# -*- coding: utf-8 -*-
"""
NUD 自定义语法库：datetime 日期时间库
=====================================
放 lib/ 目录，NUD 里：
    /being/
    import datetime
    /datetime/时间      ← 输出当前时间 19:26:11
    /datetime/日期      ← 输出当前日期 2026-08-05
    /datetime/全部      ← 输出 2026-08-05 19:26:11
"""
import re
from datetime import datetime as _dt

LIB_NAME = "datetime"
LIB_VERSION = "1.0.0"
LIB_DESCRIPTION = "日期时间库：/datetime/时间 /datetime/日期 /datetime/全部"

_RE = re.compile(r'^/datetime/([一-龥A-Za-z_][一-龥A-Za-z0-9_]*)$')


def parse_line(content, line_num, sm_imported):
    m = _RE.match(content)
    if not m:
        return None, None
    what = m.group(1)
    if what not in ('时间', '日期', '全部'):
        return None, f'不知道要显示什么: {what}（可用: 时间 / 日期 / 全部）'
    return {'type': 'DATETIME_PRINT', 'line': line_num, 'what': what}, None


def execute(node, env, registry, moves, output=None):
    what = getattr(node, 'what', '全部')
    now = _dt.now()
    text = {
        '时间': now.strftime('%H:%M:%S'),
        '日期': now.strftime('%Y-%m-%d'),
        '全部': now.strftime('%Y-%m-%d %H:%M:%S'),
    }[what]
    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
