"""تست: تاپیک‌های گروه + متن کامل پیام + منشن واقعی Notion."""

from __future__ import annotations

import sys
from pathlib import Path

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

from config.settings import settings  # noqa: E402
from services.notion_mention import (  # noqa: E402
    agent_mention_rich,
    build_assignee_rich,
    describe_mapping,
    has_real_mention,
    mention_line,
    normalize_uuid,
    parse_agent_users,
)
from services.threads import (  # noqa: E402
    ThreadCache,
    extract_thread,
    format_source_block,
    reply_kwargs,
    thread_link,
)

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}")


# --------------------------------------------------------------------------- #
class Chat:
    def __init__(self, cid: int = -100123, title: str = "گروه تست", ctype: str = "supergroup"):
        self.id = cid
        self.title = title
        self.type = ctype


class Msg:
    def __init__(self, text="", thread_id=None, is_topic=False, chat=None,
                 reply_to=None, created_name=""):
        self.text = text
        self.message_thread_id = thread_id
        self.is_topic_message = is_topic
        self.chat = chat or Chat()
        self.reply_to_message = reply_to
        self.forum_topic_created = (lambda: None)()
        if created_name:
            class C:
                name = created_name
            self.forum_topic_created = C()


def test_extract_thread() -> None:
    print("\n۱) استخراج تاپیک از پیام")
    m = Msg("سلام", thread_id=77, is_topic=True)
    info = extract_thread(m)
    check("thread_id", info.thread_id == 77)
    check("is_topic", info.is_topic)
    check("label بدون نام", info.label == "تاپیک 77", info.label)

    m2 = Msg("سلام", thread_id=88, is_topic=True, created_name="طراحی")
    check("نام از forum_topic_created", extract_thread(m2).name == "طراحی")

    m3 = Msg("عادی")   # بدون تاپیک
    info3 = extract_thread(m3)
    check("بدون تاپیک", info3.thread_id is None and not info3.is_topic)
    check("label خالی", info3.label == "")

    m4 = Msg("سلام", thread_id=1, is_topic=True)
    check("تاپیک General", extract_thread(m4).label == "عمومی")

    check("پیام None امن", extract_thread(None).thread_id is None)


def test_thread_cache() -> None:
    print("\n۲) کش نام تاپیک")
    c = ThreadCache()
    c.set_name(-100, 5, "تولید محتوا")
    check("بازیابی", c.get_name(-100, 5) == "تولید محتوا")
    check("ناموجود", c.get_name(-100, 9) == "")

    # پیام بدون نام → از کش جهانی استفاده می‌کند
    from services.threads import thread_cache

    thread_cache.set_name(-100, 5, "تولید محتوا")
    m = Msg("x", thread_id=5, is_topic=True, chat=Chat(-100))
    check("کش استفاده شد", extract_thread(m).name == "تولید محتوا", extract_thread(m).name)


def test_thread_link() -> None:
    print("\n۳) لینک تاپیک")
    link = thread_link(-1001234567890, 77, 900)
    check("فرمت t.me/c", link.startswith("https://t.me/c/"), link)
    check("بدون -100", "-100" not in link, link)
    check("شامل تاپیک و پیام", "/77/900" in link, link)
    check("بدون message_id", thread_link(-100123, 5) == "https://t.me/c/123/5")
    check("بدون chat", thread_link(None, 5) == "")
    check("بدون thread", thread_link(-100123, None) == "")


def test_reply_kwargs() -> None:
    print("\n۴) آرگومان پاسخ در تاپیک")
    check("با تاپیک", reply_kwargs(Msg(thread_id=7, is_topic=True)) == {"message_thread_id": 7})
    check("بدون تاپیک", reply_kwargs(Msg()) == {})


def test_source_block() -> None:
    print("\n۵) بلوک منبع")
    b = format_source_block(
        chat_title="گروه", topic="تولید محتوا", author="employer",
        permalink="https://t.me/c/1/2/3", thread_id=2,
    )
    check("عنوان بلوک", "─── منبع ───" in b)
    check("گروه", "گروه: گروه" in b)
    check("تاپیک", "تاپیک: تولید محتوا" in b)
    check("فرستنده", "فرستنده: employer" in b)
    check("لینک", "https://t.me/c/1/2/3" in b)
    check("خالی امن", format_source_block() == "─── منبع ───")


def test_agent_users() -> None:
    print("\n۶) نگاشت ایجنت → Notion")
    u1 = "b1e8f2a4-1111-2222-3333-444455556666"
    u2 = "7c3d9f11-aaaa-bbbb-cccc-ddddeeeeffff"

    parsed = parse_agent_users(f"AG03={u1},AG04=page:{u2}")
    check("دو ایجنت", len(parsed) == 2, parsed)
    check("AG03 نوع user", parsed["AG03"]["type"] == "user")
    check("AG04 نوع page", parsed["AG04"]["type"] == "page")
    check("page id درست", parsed["AG04"]["id"] == u2)
    check("خالی → dict خالی", parse_agent_users("") == {})

    # UUID بدون خط تیره
    parsed2 = parse_agent_users("AG05=b1e8f2a4111122223333444455556666")
    check("UUID ۳۲ کاراکتری پذیرفته شد", "AG05" in parsed2, parsed2)

    check("normalize", normalize_uuid("b1e8f2a4111122223333444455556666") == u1)


def test_mention_rich() -> None:
    print("\n۷) ساخت منشن واقعی")
    u = "b1e8f2a4-1111-2222-3333-444455556666"
    users = {"AG03": {"type": "user", "id": u}}

    rich = agent_mention_rich("AG03", users)
    check("نوع mention", rich["type"] == "mention")
    check("mention type=user", rich["mention"]["type"] == "user")
    check("UUID درست", rich["mention"]["user"]["id"] == u)

    page_rich = agent_mention_rich("AG04", {"AG04": {"type": "page", "id": u}})
    check("mention type=page", page_rich["mention"]["type"] == "page")

    fallback = agent_mention_rich("AG07", {})
    check("fallback متن", fallback["type"] == "text")
    check("fallback @AG07", fallback["text"]["content"] == "@AG07")

    check("has_real_mention True", has_real_mention([rich]))
    check("has_real_mention False", not has_real_mention([fallback]))

    arr = build_assignee_rich("AG03", users)
    check("build_assignee_rich", len(arr) == 1 and arr[0]["type"] == "mention")

    check("mention_line", mention_line("ag03", "محتوای جدید") == "@AG03 محتوای جدید")

    d = describe_mapping("AG03=" + u)
    check("describe_mapping", "AG03" in d)
    check("describe خالی", "خالی است" in describe_mapping(""))


def test_settings_props() -> None:
    print("\n۸) ستون‌های تاپیک در تنظیمات")
    props = settings.notion_task_props
    check("topic", props.get("topic") == "Topic", props.get("topic"))
    check("link", props.get("link") == "Link", props.get("link"))


def test_task_fields() -> None:
    print("\n۹) فیلدهای تاپیک روی Task")
    from services.tasks import Task

    t = Task(
        title="کمپین محتوا", assignee="AG03",
        thread_id=77, topic="تولید محتوا",
        chat_title="گروه", permalink="https://t.me/c/1/2/3",
    )
    d = t.to_dict()
    check("thread_id", d["thread_id"] == 77)
    check("topic", d["topic"] == "تولید محتوا")
    check("chat_title", d["chat_title"] == "گروه")
    check("permalink", d["permalink"].startswith("https://t.me/c/"))


def test_access_group() -> None:
    print("\n۱۰) امنیت: /task در گروه")
    from services.access import can_create_tasks

    old_owner = settings.telegram_owner_ids
    old_allowed = settings.telegram_allowed_user_ids
    old_strict = settings.task_creators_strict

    try:
        # bootstrap: هیچ‌کس تنظیم نشده
        settings.telegram_owner_ids = ""
        settings.telegram_allowed_user_ids = ""
        check("گروه: bootstrap رد می‌شود", not can_create_tasks(999, "employer", in_group=True))
        check("پیوی: bootstrap مجاز", can_create_tasks(999, "employer", in_group=False))

        # مالک تنظیم شد
        settings.telegram_owner_ids = "111"
        settings.telegram_allowed_user_ids = "111,222"
        check("مالک مجاز", can_create_tasks(111, "brother", in_group=True))
        check("کارفرما رد", not can_create_tasks(999, "employer", in_group=True))
        check("شناسه ناشناخته رد", not can_create_tasks(333, "x", in_group=True))
    finally:
        settings.telegram_owner_ids = old_owner
        settings.telegram_allowed_user_ids = old_allowed
        settings.task_creators_strict = old_strict


def main() -> int:
    print("=" * 68)
    print("  تست: تاپیک‌ها + متن کامل + منشن Notion + امنیت")
    print("=" * 68)
    test_extract_thread()
    test_thread_cache()
    test_thread_link()
    test_reply_kwargs()
    test_source_block()
    test_agent_users()
    test_mention_rich()
    test_settings_props()
    test_task_fields()
    test_access_group()
    print("\n" + "=" * 68)
    print(f"  نتیجه: {PASS} ✅ / {FAIL} ❌")
    print("=" * 68)
    return 0 if FAIL == 0 else 1


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