"""تست: گیرندگان وظیفه — ۹ ایجنت (A01..A09) + ۳ انسان (H01..H03).

نسخهٔ ۱.۰.۲ بتا
پوشش: نرمال‌سازی کد، بازه‌ها، گروه‌ها، تجزیهٔ /task، حلقهٔ اجرا، پولر، روتینگ.
"""

from __future__ import annotations

import asyncio
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.agents import load_registry  # noqa: E402
from services.assignees import (  # noqa: E402
    GROUP_TOKENS,
    Human,
    AssigneeRegistry,
    agent_id as agent_from_code,
    build_default_registry,
    get_registry,
    human_id,
    is_agent,
    is_human,
    normalize_code,
    parse_assignees,
    split_runnable,
    storage_code,
)
from services.router import RouteKind, route_message, strip_mentions  # noqa: E402
from services.tasks import Task, parse_task_message  # noqa: E402

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}" + (f" — {detail}" if detail != "" else ""))


# --------------------------------------------------------------------------- #
print("\n=== ۱) نرمال‌سازی کد گیرنده ===")
check("A03 → A03", normalize_code("A03") == "A03")
check("A3 → A03", normalize_code("A3") == "A03")
check("a3 → A03", normalize_code("a3") == "A03")
check("@A03 → A03", normalize_code("@A03") == "A03")
check("AG03 → A03", normalize_code("AG03") == "A03")
check("@ag3 → A03", normalize_code("@ag3") == "A03")
check("H02 → H02", normalize_code("H02") == "H02")
check("H2 → H02", normalize_code("H2") == "H02")
check("@h2 → H02", normalize_code("@h2") == "H02")
check("۹ → A09 (سازگاری)", normalize_code("9") == "A09")
check("رقم دو رقمی 03 → A03", normalize_code("03") == "A03")
check("نامعتبر → None", normalize_code("X1") is None)
check("خالی → None", normalize_code("") is None)
check("None → None", normalize_code(None) is None)

check("is_human(H02)", is_human("H02") is True)
check("is_human(A03) غلط", is_human("A03") is False)
check("is_agent(A03)", is_agent("A03") is True)
check("is_agent(H02) غلط", is_agent("H02") is False)
check("A03 → AG03", agent_from_code("A03") == "AG03")
check("H02 → None (ایجنت نیست)", agent_from_code("H02") is None)
check("H02 → H02", human_id("H02") == "H02")

print("\n=== ۲) کد ذخیره‌سازی (سازگاری با نسخهٔ قبل) ===")
check("A03 → AG03", storage_code("A03") == "AG03", storage_code("A03"))
check("A09 → AG09", storage_code("A09") == "AG09")
check("H02 → H02", storage_code("H02") == "H02")
check("ag3 → AG03", storage_code("ag3") == "AG03")

print("\n=== ۳) بازه‌ها ===")
q = parse_assignees("A01-A09")
check("A01-A09 → ۹ کد", len(q.codes) == 9, q.codes)
check("A01-A09 شروع", q.codes[0] == "A01")
check("A01-A09 پایان", q.codes[-1] == "A09")
check("A01-A09 هجده؟ نه", "A18" not in q.codes)

q = parse_assignees("H01-H03")
check("H01-H03 → ۳ کد", q.codes == ["H01", "H02", "H03"], q.codes)

q = parse_assignees("A1-A3")
check("A1-A3 کوتاه", q.codes == ["A01", "A02", "A03"], q.codes)
q = parse_assignees("A1..A4")
check("A1..A4 با نقطه", q.codes == ["A01", "A02", "A03", "A04"], q.codes)
q = parse_assignees("H1 تا H3")
check("H1 تا H3 فارسی", q.codes == ["H01", "H02", "H03"], q.codes)
q = parse_assignees("A01-H03")
check("بازهٔ مختلط رد می‌شود", q.codes == [], q.codes)
q = parse_assignees("A09-A01")
check("بازهٔ معکوس رد می‌شود", q.codes == [], q.codes)

print("\n=== ۴) فهرست و گروه ===")
check("A01,A02,A03", parse_assignees("A01,A02,A03").codes == ["A01", "A02", "A03"])
check("A01،A02 (کامای فارسی)", parse_assignees("A01،A02").codes == ["A01", "A02"])
check("A03,H02 (مختلط)", parse_assignees("A03,H02").codes == ["A03", "H02"])
check("@agents → ۹ ایجنت", len(parse_assignees("@agents").codes) == 9)
check("@humans → ۳ انسان", parse_assignees("@humans").codes == ["H01", "H02", "H03"])
check("@all → ۱۲ گیرنده", len(parse_assignees("@all").codes) == 12)
check("GROUP_TOKENS سه گروه", len(GROUP_TOKENS) == 3)
check("@agent مفرد هم کار می‌کند", len(parse_assignees("@agent").codes) == 9)

print("\n=== ۵) تجزیهٔ /task با همهٔ فرم‌ها ===")
cases = [
    ("/task @A03 عنوان وظیفه", ["A03"], "عنوان وظیفه"),
    ("/task @AG03 عنوان", ["A03"], "عنوان"),
    ("/task @H02 متن را بازنویسی کن", ["H02"], "متن را بازنویسی کن"),
    ("/task @A01-A09 کمپین نوروز", [f"A0{i}" for i in range(1, 10)], "کمپین نوروز"),
    ("/task @H01-H03 امضای قرارداد", ["H01", "H02", "H03"], "امضای قرارداد"),
    ("/task @A03,@H02 بازبینی متن", ["A03", "H02"], "بازبینی متن"),
    ("/task @agents گزارش هفتگی", None, "گزارش هفتگی"),
    ("/task @humans تأیید نهایی", ["H01", "H02", "H03"], "تأیید نهایی"),
    ("/task 9 سئو", ["A09"], "سئو"),
    ("/task a3 عنوان", ["A03"], "عنوان"),
    ("/task @H1 عنوان", ["H01"], "عنوان"),
]
for text, expected, title in cases:
    r = parse_task_message(text)
    ok_codes = True if expected is None else (r is not None and r.targets == expected)
    check(f"{text[:34]:36} گیرنده", ok_codes, r.targets if r else None)
    check(f"{text[:34]:36} عنوان", r is not None and r.title == title, r.title if r else None)

check("بدون اسلش کار نمی‌کند", parse_task_message("سلام خوبی") is None)
check("/help دستور وظیفه نیست", parse_task_message("/help") is None)
check("/task خالی → bare", parse_task_message("/task").bare is True)
check("/task خالی → بدون گیرنده", parse_task_message("/task").targets == [])

r = parse_task_message("/task @A03 عنوان\nخط دوم توضیح\nخط سوم")
check("عنوان = خط اول", r.title == "عنوان", r.title)
check("توضیح = خطوط بعدی", "خط دوم" in r.description and "خط سوم" in r.description, r.description)

r = parse_task_message("@A03 وظیفه: عنوان تست")
check("@A03 وظیفه: فرم دوم", r is not None and r.targets == ["A03"] and r.title == "عنوان تست", r)
r = parse_task_message("@H02 کار: بازنویسی")
check("@H02 کار: فرم دوم", r is not None and r.targets == ["H02"], r)

r = parse_task_message("/task @A03,@H02 کار")
check("agent_id سازگار = AG03", r.agent_id == "AG03", r.agent_id)
check("is_multi درست", r.is_multi is True)
check("تک‌گیرنده is_multi غلط", parse_task_message("/task @A03 کار").is_multi is False)

print("\n=== ۶) دستورهای جایگزین ===")
for alias in ["/وظیفه", "/کار", "/ta", "/assign"]:
    r = parse_task_message(f"{alias} @A05 تست")
    check(f"{alias} @A05 پذیرفته شد", r is not None and r.targets == ["A05"], r)
check("دستورها از تنظیمات", "task" in settings.task_command_list)

print("\n=== ۷) تقسیم ایجنت / انسان ===")
agents, humans = split_runnable(["A03", "H02", "A09", "H01"])
check("ایجنت‌ها جدا", agents == ["A03", "A09"], agents)
check("انسان‌ها جدا", humans == ["H02", "H01"], humans)
check("فقط ایجنت", split_runnable(["A01"]) == (["A01"], []))
check("فقط انسان", split_runnable(["H03"]) == ([], ["H03"]))
check("کد نامعتبر نادیده", split_runnable(["X9"]) == ([], []))

print("\n=== ۸) مدل Task و حلقهٔ اجرا ===")
t_agent = Task(title="تست", assignee="AG03", assignee_code="A03")
check("ایجنت runnable", t_agent.is_runnable is True)
check("ایجنت human نیست", t_agent.is_human is False)
check("کد ایجنت در to_dict", t_agent.to_dict()["assignee_code"] == "A03")

t_human = Task(title="تست", assignee="H02", assignee_code="H02")
check("🔴 انسان runnable نیست", t_human.is_runnable is False)
check("انسان human است", t_human.is_human is True)
check("وظیفهٔ انسانی از پولر رد می‌شود", t_human.is_runnable is False)

t_h_bare = Task(title="تست", assignee="H03")
check("تشخیص انسان از assignee خالی", t_h_bare.is_human is True)
t_a_bare = Task(title="تست", assignee="AG07")
check("تشخیص ایجنت از assignee خالی", t_a_bare.is_human is False)

print("\n=== ۹) رجیستری گیرندگان ===")
registry = build_default_registry()
check("۹ ایجنت ثبت شد", len(registry.agent_codes) == 9, registry.agent_codes)
check("۳ انسان ثبت شد", len(registry.humans) == 3, list(registry.humans))
check("۱۲ کد کل", len(registry.all_codes()) == 12)
check("H02 پیدا می‌شود", registry.get("H02") is not None)
check("A03 پیدا می‌شود", registry.get("A03") is not None)
check("AG03 هم پیدا می‌شود", registry.get("AG03") is not None)
check("H09 وجود ندارد", registry.get("H09") is None)
check("A10 وجود ندارد", registry.get("A10") is None)

a = registry.get("A03")
check("نوع ایجنت", a.kind == "agent" and a.is_agent)
check("نام ایجنت از agents.yaml", "کارگردان" in a.name or "محتوا" in a.name, a.name)
h = registry.get("H02")
check("نوع انسان", h.kind == "human" and h.is_human)
check("نوع انسانی human پر است", h.human is not None)
check("label شامل «انسان»", "انسان" in h.label(), h.label())
check("directory دو دسته دارد", any("ایجنت" in line for line in registry.directory_lines())
      and any("انسان" in line for line in registry.directory_lines()))

custom = AssigneeRegistry(humans=[Human("H01", "سارا", "مدیر")])
custom.add_agent("A05", "وب", "سایت")
check("رجیستری سفارشی", custom.get("H01").name == "سارا" and custom.get("A05").name == "وب")
check("رجیستری سراسری پایدار", get_registry() is get_registry())

print("\n=== ۱۰) روتینگ منشن ===")
reg = load_registry()
r = route_message("@ag03 سلام", reg)
check("@ag03 → SINGLE AG03", r.kind is RouteKind.SINGLE and r.agent_id == "AG03")
r = route_message("@a03 سلام", reg)
check("@a03 (کوتاه) → SINGLE", r.kind is RouteKind.SINGLE and r.agent_id == "AG03")
r = route_message("@A3 سلام", reg)
check("@A3 (تک‌رقمی) → SINGLE", r.kind is RouteKind.SINGLE and r.agent_id == "AG03")
r = route_message("@h02 لطفا بررسی کن", reg)
check("@h02 → HUMAN H02", r.kind is RouteKind.HUMAN and r.agent_id == "H02", r)
r = route_message("@H2 ببین", reg)
check("@H2 → HUMAN", r.kind is RouteKind.HUMAN and r.agent_id == "H02")
r = route_message("@h09 ناموجود", reg)
check("@h09 → IGNORE", r.kind is RouteKind.IGNORE, r.kind)
r = route_message("سلام", reg)
check("بدون منشن → IGNORE", r.kind is RouteKind.IGNORE)
r = route_message("/all سوال", reg)
check("/all → ALL", r.kind is RouteKind.ALL)
check("HUMAN در should_reply", route_message("@h01 x", reg).should_reply is True)
check("strip_mentions انسان را هم بردارد",
      strip_mentions("@ag03 سلام @h02 خوبی") == "سلام خوبی",
      strip_mentions("@ag03 سلام @h02 خوبی"))

print("\n=== ۱۱) تنظیمات انسان‌ها ===")
check("HUMAN_NAMES خوانده می‌شود", isinstance(settings.human_names, str))
check("human_ids روی H01 کار می‌کند", isinstance(settings.human_ids("H01"), set))
check("human_ids روی کد ناموجود", settings.human_ids("H99") == set())
check("TASK_MULTI_SPLIT پیش‌فرض True", settings.task_multi_split is True)
check("HUMAN_TASK_STATUS پیش‌فرض todo", settings.human_task_status == "todo")

settings.human_h02_ids = "111,222"
h02 = get_registry(reload=True).get_human_by_telegram(111, None)
check("تطبیق انسان با شناسهٔ تلگرام", h02 is not None and h02.id == "H02", h02)
h02b = get_registry().get_human_by_telegram(None, "someoneelse")
check("شناسهٔ ناشناس → None", h02b is None)
settings.human_h02_ids = ""

print("\n=== ۱۲) سناریوی کامل: ساخت وظیفه برای ۳ انسان + ۲ ایجنت ===")


class FakeUser:
    def __init__(self, uid=424242, username="owner", full_name="مالک"):
        self.id = uid
        self.username = username
        self.full_name = full_name
        self.is_bot = False


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


class FakeMessage:
    def __init__(self, text, reply_to=None):
        self.text = text
        self.caption = None
        self.message_id = 900
        self.chat_id = -100123
        self.chat = FakeChat()
        self.from_user = FakeUser()
        self.message_thread_id = 77
        self.reply_to_message = reply_to
        self.replies = []
        self.is_topic_message = True
        self.forum_topic_created = None
        self.forum_topic_closed = None
        self.forum_topic_reopened = None
        self.forum_topic_edited = None

    async def reply_text(self, text, **kwargs):
        self.replies.append(text)
        return self


class FakeIndex:
    def __init__(self):
        self.items = []

    def add(self, task):
        self.items.append(task)

    def all(self):
        return list(self.items)


async def scenario() -> None:
    from services.automation import AutomationService

    # مالک را ست می‌کنیم — در حالت bootstrap گروه عمداً رد می‌شود (رفع باگ امنیتی)
    settings.telegram_owner_ids = "424242"
    settings.telegram_allowed_user_ids = "424242"

    created: list[Task] = []

    class Store:
        available = False
        props = {}
        async def create(self, task):
            created.append(task)
            return task
        async def update(self, task, patch):
            return task
        async def query(self, **kw):
            return []

    class FakeNotion:
        available = False
        async def fetch_active_records(self, db, limit=10):
            return []

    auto = AutomationService(
        registry=load_registry(),
        notion_service=FakeNotion(),
        llm_service=None,
        mongo_module=None,
        get_send_fn=lambda: None,
    )
    auto.task_store = Store()
    auto.index = FakeIndex()

    ran: list[str] = []

    async def fake_run_now(task):
        ran.append(task.assignee_code or task.assignee)

    auto._run_now = fake_run_now          # type: ignore[method-assign]
    notified: list[str] = []

    async def fake_notify_human(task):
        notified.append(task.assignee_code or task.assignee)

    auto._notify_human = fake_notify_human   # type: ignore[method-assign]

    # --- ۱) یک ایجنت ---
    msg = FakeMessage("/task @A03 تولید محتوای لوگو\nسه پست برای هفتهٔ اول")
    handled = await auto.handle_task_message(msg)
    await asyncio.sleep(0)
    check("۱) دستور شناخته شد", handled is True)
    check("۱) یک وظیفه ساخته شد", len(created) == 1, len(created))
    check("۱) ذخیره به شکل AG03", created[0].assignee == "AG03", created[0].assignee)
    check("۱) کد جدید A03", created[0].assignee_code == "A03")
    check("۱) ایجنت اجرا شد", ran == ["A03"], ran)
    check("۱) انسان اعلان نگرفت", notified == [], notified)
    check("۱) رسید شامل نام ایجنت",
          "کارگردان" in msg.replies[0] or "محتوا" in msg.replies[0], msg.replies)

    # --- ۲) یک انسان ---
    created.clear(); ran.clear(); notified.clear()
    msg2 = FakeMessage("/task @H02 قرارداد را امضا کن")
    await auto.handle_task_message(msg2)
    await asyncio.sleep(0)
    check("۲) یک وظیفه ساخته شد", len(created) == 1)
    check("۲) ذخیره H02", created[0].assignee == "H02")
    check("۲) 🔴 ایجنت اجرا نشد", ran == [], ran)
    check("۲) اعلان انسانی رفت", notified == ["H02"], notified)
    check("۲) رسید می‌گوید انسان است",
          "انسان" in msg2.replies[0], msg2.replies[0])
    check("۲) وظیفهٔ انسانی runnable نیست", created[0].is_runnable is False)

    # --- ۳) مختلط: ۲ ایجنت + ۳ انسان ---
    created.clear(); ran.clear(); notified.clear()
    msg3 = FakeMessage("/task @A01,@A05,@H01-H03 لانچ کمپین\nهمه هماهنگ شوند")
    await auto.handle_task_message(msg3)
    await asyncio.sleep(0)
    check("۳) ۵ وظیفه ساخته شد", len(created) == 5, [c.assignee for c in created])
    check("۳) ایجنت‌ها اجرا شدند", sorted(ran) == ["A01", "A05"], ran)
    check("۳) انسان‌ها اعلان گرفتند", sorted(notified) == ["H01", "H02", "H03"], notified)
    check("۳) عنوان مشترک", all(c.title == "لانچ کمپین" for c in created))
    check("۳) رسید شمارش دارد", "5 وظیفه" in msg3.replies[0], msg3.replies[0])
    check("۳) رسید تفکیک دارد", "2 ایجنت" in msg3.replies[0] or "۲ ایجنت" in msg3.replies[0])

    # --- ۴) ۹ ایجنت یک‌جا ---
    created.clear(); ran.clear(); notified.clear()
    msg4 = FakeMessage("/task @A01-A09 گزارش هفتگی")
    await auto.handle_task_message(msg4)
    await asyncio.sleep(0)
    check("۴) ۹ وظیفه", len(created) == 9, len(created))
    check("۴) ۹ ایجنت اجرا", len(ran) == 9, ran)
    check("۴) هیچ انسانی", notified == [])

    # --- ۵) گیرندهٔ ناشناخته ---
    created.clear(); ran.clear()
    msg5 = FakeMessage("/task @H09 کاری")
    await auto.handle_task_message(msg5)
    check("۵) هیچ وظیفه‌ای ساخته نشد", created == [])
    check("۵) پیام راهنما فرستاده شد", len(msg5.replies) == 1)
    check("۵) راهنما فهرست کدها را دارد",
          "H01" in msg5.replies[0] and "A01" in msg5.replies[0], msg5.replies[0])

    # --- ۶) بدون گیرنده ---
    msg6 = FakeMessage("/task یک کار")
    await auto.handle_task_message(msg6)
    check("۶) راهنمای کامل", "فرم‌های پذیرفته‌شده" in msg6.replies[0] or "/task @A03" in msg6.replies[0])

    # --- ۷) ریپلای بدون عنوان ---
    created.clear(); ran.clear(); notified.clear()
    parent = FakeMessage("متن کامل درخواست کارفرما برای بازنویسی")
    parent.from_user = FakeUser(999, "employer", "کارفرما")
    msg7 = FakeMessage("/task @H02", reply_to=parent)
    await auto.handle_task_message(msg7)
    await asyncio.sleep(0)
    check("۷) عنوان از پیام ریپلای", created and "بازنویسی" in created[0].title, created[0].title if created else None)
    check("۷) منبع در توضیح", created and "─── منبع ───" in created[0].description)
    check("۷) تاپیک ثبت شد", created and created[0].thread_id == 77)

    # --- ۸) دسترسی: کاربر غیرمجاز ---
    created.clear()
    settings.telegram_owner_ids = "555"
    settings.telegram_task_creator_ids = "555"
    msg8 = FakeMessage("/task @A03 کار")
    msg8.from_user = FakeUser(999, "stranger", "غریبه")
    await auto.handle_task_message(msg8)
    check("۸) 🔴 غیرمجاز رد شد", created == [])
    check("۸) پیام رد شدن", "مجاز نیست" in msg8.replies[0], msg8.replies)
    settings.telegram_owner_ids = "424242"
    settings.telegram_task_creator_ids = ""


def test_assignees_pipeline() -> None:
    """نقطهٔ ورود pytest — همان سناریو."""
    asyncio.run(scenario())


if __name__ == "__main__" and not any("pytest" in m for m in sys.modules):
    asyncio.run(scenario())

# --------------------------------------------------------------------------- #
print("\n" + "=" * 62)
print(f"نتیجه: {PASS} ✅ / {FAIL} ❌")
if FAIL:
    raise SystemExit(1)
print("همهٔ تست‌های گیرندگان وظیفه پاس شد.")
