"""تست‌های «منشن ایجنت → وظیفه در Notion»."""

from __future__ import annotations

import sys
from pathlib import Path

APP = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(APP))

from services.mention_tasks import (  # noqa: E402
    MentionTaskGate,
    build_task_from_mention,
)

PASS, FAIL = 0, 0


def check(name: str, cond: bool, detail: object = "") -> None:
    global PASS, FAIL
    if cond:
        PASS += 1
        print(f"  ✅ {name}")
    else:
        FAIL += 1
        print(f"  ❌ {name} — {detail}")


def test_mode_off() -> None:
    print("\n۱) حالت خاموش (پیش‌فرض)")
    g = MentionTaskGate(mode="off")
    check("غیرفعال است", not g.enabled)
    d = g.decide("@ag01 وظیفه: چیزی انجام بده", ["AG01"])
    check("وظیفه ساخته نمی‌شود", not d.should_create, d)
    check("دلیل درست", "خاموش" in d.reason, d.reason)


def test_mode_task() -> None:
    print("\n۲) حالت task — فقط با کلمهٔ «وظیفه»")
    g = MentionTaskGate(mode="task", min_chars=10)

    cases = [
        ("@ag01 بازار هدف ما را تحلیل کن", False, "سؤال بدون کلمهٔ وظیفه"),
        ("@ag01 وظیفه: بازار هدف را تحلیل کن", True, "با «وظیفه»"),
        ("@ag03 task نوشتن ۵ پست", True, "با «task» انگلیسی"),
        ("@ag04 این را بسپار به طراحی لوگو", True, "با «بسپار»"),
        ("@ag01؟", False, "فقط علامت سؤال"),
        ("@ag01 کوتاه", False, "خیلی کوتاه"),
    ]
    for text, expected, label in cases:
        d = g.decide(text, ["AG01"])
        check(f"{label} → {expected}", d.should_create == expected, f"{d.should_create} / {d.reason}")


def test_mode_all() -> None:
    print("\n۳) حالت all — هر منشن وظیفه")
    g = MentionTaskGate(mode="all", min_chars=5)
    d = g.decide("@ag02 یک متن تبلیغاتی بنویس", ["AG02"])
    check("بدون کلمهٔ وظیفه هم می‌سازد", d.should_create, d)
    check("ایجنت درست", d.agent_ids == ("AG02",), d.agent_ids)


def test_mode_reply() -> None:
    print("\n۴) حالت reply — فقط ریپلای")
    g = MentionTaskGate(mode="reply", min_chars=5)
    check("بدون ریپلای رد می‌شود", not g.decide("@ag01 چیزی بنویس", ["AG01"]).should_create)
    check("با ریپلای قبول", g.decide("@ag01 چیزی بنویس", ["AG01"], is_reply=True).should_create)


def test_reply_effective_length() -> None:
    print("\n۵) ریپلای کوتاه روی پیام بلند")
    g = MentionTaskGate(mode="task", min_chars=12)
    long_reply = "برای لانچ محصول، لوگو و ۵ پست اینستاگرام لازم داریم. ددلاین جمعه."
    check("بدون ریپلای رد", not g.decide("@ag09 وظیفه", ["AG09"]).should_create)
    check(
        "با ریپلای قبول",
        g.decide("@ag09 وظیفه", ["AG09"], is_reply=True, reply_text=long_reply).should_create,
    )


def test_bot_messages() -> None:
    print("\n۶) پیام ربات → نادیده")
    g = MentionTaskGate(mode="all", min_chars=5)
    check("پیام ربات رد می‌شود", not g.decide("@ag01 وظیفه انجام بده", ["AG01"], from_bot=True).should_create)
    check("بدون منشن رد می‌شود", not g.decide("وظیفه انجام بده", []).should_create)


def test_rate_limit() -> None:
    print("\n۷) محدودیت نرخ")
    g = MentionTaskGate(mode="all", min_chars=5, max_per_hour=3)
    accepted = 0
    for i in range(6):
        d = g.decide(f"کار شمارهٔ {i} را انجام بده", ["AG01"])
        if d.should_create:
            g.commit()
            accepted += 1
    check("دقیقاً ۳ پذیرفته شد", accepted == 3, accepted)
    check("سقف اعمال شد", "سقف" in g.decide("کار دیگر", ["AG01"]).reason)

    g0 = MentionTaskGate(mode="all", min_chars=5, max_per_hour=0)
    ok = 0
    for _ in range(20):
        d0 = g0.decide("کار انجام بده", ["AG01"])
        if d0.should_create:
            g0.commit()
            ok += 1
    check("۰ = بی‌نهایت", ok == 20, ok)


def test_build_task() -> None:
    print("\n۸) ساخت شیء Task")
    t = build_task_from_mention(
        text="@ag04 وظیفه طراحی ۳ کانسپت لوگو",
        agent_id="AG04",
        requester="brother",
        chat_id=-100,
        message_id=42,
    )
    check("assignee", t.assignee == "AG04", t.assignee)
    check("منشن از عنوان پاک شد", "@ag04" not in t.title.lower(), t.title)
    check("عنوان شامل کار", "لوگو" in t.title, t.title)
    check("chat_id", t.chat_id == -100)
    check("requester", t.requester == "brother")
    check("وضعیت todo", t.status in {"برای انجام", "در انتظار", "todo"}, t.status)
    check("source", t.source == "telegram")

    print("\n۹) Task با ریپلای")
    t2 = build_task_from_mention(
        text="@ag09 وظیفه",
        agent_id="AG09",
        requester="brother",
        chat_id=-100,
        message_id=43,
        reply_text="برای لانچ، لوگو و محتوا لازم داریم\nددلاین جمعه",
        reply_author="me",
    )
    check("عنوان از خط اول ریپلای", t2.title.startswith("برای لانچ"), t2.title)
    check("نویسنده در توضیح", "me" in t2.description, t2.description[:60])
    check("متن کامل در توضیح", "ددلاین" in t2.description)


def main() -> int:
    print("=" * 66)
    print("  تست: منشن ایجنت → وظیفه در Notion")
    print("=" * 66)

    test_mode_off()
    test_mode_task()
    test_mode_all()
    test_mode_reply()
    test_reply_effective_length()
    test_bot_messages()
    test_rate_limit()
    test_build_task()

    print("\n" + "=" * 66)
    print(f"  نتیجه: {PASS} ✅ / {FAIL} ❌")
    print("=" * 66)
    return 0 if FAIL == 0 else 1


if __name__ == "__main__":
    raise SystemExit(main())
