"""Gợi ý bước kế tiếp + giọng trả lời thống nhất cho toàn bot.

Bot có ~50 lệnh, không ai nhớ hết. Mỗi câu trả lời nên kết thúc bằng
việc người dùng làm tiếp được gì, theo đúng một format để dễ nhận ra.
"""

import difflib

# Icon theo loại thông điệp, dùng chung để bot nói một giọng.
OK = "✅"
ERROR = "❌"
WARN = "⚠️"
INFO = "ℹ️"
DENIED = "🔒"
TIP = "💡"
NEXT = "👉"

# Luồng chính: lệnh -> các bước thường làm ngay sau đó.
# Chỉ ghi luồng có thật, đừng đoán.
SALES_FLOW = ("menu", "bg", "mua", "km", "stk")


def next_steps(*steps):
    """Khối 'Bước tiếp theo' — bỏ qua mục rỗng để call site khỏi phải if."""
    steps = [str(s).strip() for s in steps if s and str(s).strip()]
    if not steps:
        return ""
    return "\n".join(["", "", f"{NEXT} Bước tiếp theo:"] + [f"   • {s}" for s in steps])


def with_next(text, *steps):
    """Gắn khối gợi ý vào cuối câu trả lời."""
    return str(text).rstrip() + next_steps(*steps)


def denied(prefix=".", what="lệnh này", who="Quản trị viên"):
    """Từ chối quyền nhưng vẫn chỉ đường, thay vì chặn cụt."""
    return with_next(
        f"{DENIED} {who} mới dùng được {what}.",
        f"{prefix}menu — xem các lệnh bạn đang dùng được",
        f"{prefix}hotro — liên hệ hỗ trợ",
    )


def usage(prefix, command, syntax, *examples):
    """Báo sai cú pháp kèm ví dụ gõ được ngay."""
    text = f"{ERROR} Sai cú pháp.\n📝 Dùng: {prefix}{command} {syntax}".rstrip()
    return with_next(text, *[f"Ví dụ: {example}" for example in examples])


def did_you_mean(typed, available, limit=3):
    """Gợi ý lệnh gần giống khi gõ sai — stdlib lo phần so khớp."""
    if not typed:
        return []
    return difflib.get_close_matches(str(typed).casefold(), sorted(available), n=limit, cutoff=0.6)


def unknown_command(typed, available, prefix="."):
    suggestions = did_you_mean(typed, available)
    text = f"{ERROR} Không có lệnh {prefix}{typed}."
    if suggestions:
        text += "\n" + f"{TIP} Có phải bạn muốn: " + " hoặc ".join(f"{prefix}{s}" for s in suggestions) + "?"
    return with_next(
        text,
        f"{prefix}menu — xem lệnh bán hàng",
        f"{prefix}hotro — nhờ hỗ trợ",
    )


def toggled(label, enabled, prefix, command, on_word="on", off_word="off", extra=None):
    """Xác nhận bật/tắt kèm luôn cách tắt/bật lại — khỏi phải nhớ."""
    icon = OK if enabled else "🔕"
    state = "Đã bật" if enabled else "Đã tắt"
    opposite = off_word if enabled else on_word
    verb = "tắt" if enabled else "bật"
    return with_next(
        f"{icon} {state} {label} cho nhóm này.",
        f"{prefix}{command} {opposite} — {verb} lại",
        extra,
    )


if __name__ == "__main__":
    assert next_steps() == ""
    assert next_steps(None, "  ", "") == ""
    block = next_steps(".mua", ".stk")
    assert block.startswith("\n\n👉 Bước tiếp theo:") and "• .mua" in block and "• .stk" in block
    assert with_next("Xong.", ".menu").startswith("Xong.\n\n👉")
    assert with_next("Xong.") == "Xong."          # không có bước kế thì không thêm gì
    assert did_you_mean("mennu", ["menu", "mua", "stk"]) == ["menu"]
    assert did_you_mean("thongbao", ["thongbao", "lead"]) == ["thongbao"]
    assert did_you_mean("zzzzzz", ["menu", "mua"]) == []
    assert ".menu" in unknown_command("mennu", ["menu", "mua"], ".")
    assert "Có phải bạn muốn: .menu" in unknown_command("mennu", ["menu", "mua"], ".")
    assert "🔒" in denied(".") and ".hotro" in denied(".")
    on = toggled("chống link", True, ".", "antilink")
    off = toggled("chống link", False, ".", "antilink")
    assert "Đã bật" in on and ".antilink off — tắt lại" in on
    assert "Đã tắt" in off and ".antilink on — bật lại" in off
    assert "Ví dụ: .stk 100000" in usage(".", "stk", "<số tiền>", ".stk 100000")
    print("hints self-check OK")
