"""
تست‌های سبک (بدون شبکه/تلگرام واقعی):
    python -m pytest tests -q        # یا:  python tests/test_pipeline.py
"""

from __future__ import annotations

import asyncio
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path

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

import mongomock_motor  # noqa: E402

import db.mongo as mongo  # noqa: E402
from services.agents import load_registry  # noqa: E402
from services.context import (  # noqa: E402
    build_agent_context,
    format_message_line,
    human_today,
    split_for_telegram,
)
from services.notion import flatten_page, format_records_for_prompt  # noqa: E402
from services.router import RouteKind, extract_user_question, route_message, strip_mentions  # noqa: E402

registry = load_registry()


def test_registry():
    assert len(registry.agents) == 9
    assert [a.id for a in registry.enabled_agents()] == [f"AG0{i}" for i in range(1, 10)]
    assert registry.get("AG09").enabled is True
    assert "قواعد مشترک" in registry.get("AG01").full_system_prompt


def test_routing():
    assert route_message("@ag01 تحلیل بازار", registry).kind is RouteKind.SINGLE
    assert route_message("@AG03 تقویم", registry).agent_id == "AG03"
    assert route_message("/all بررسی کن", registry).kind is RouteKind.ALL
    assert route_message("/all@MyBot بررسی", registry).kind is RouteKind.ALL
    assert route_message("/daily", registry).kind is RouteKind.DAILY
    assert route_message("/help", registry).kind is RouteKind.HELP
    assert route_message("/tasks", registry).kind is RouteKind.TASKS
    assert route_message("@ag09 برنامه", registry).kind is RouteKind.SINGLE
    assert route_message("سلام بچه‌ها", registry).kind is RouteKind.IGNORE
    assert route_message("@ag09 نظرت؟", registry).kind is RouteKind.SINGLE  # AG09 حالا فعال است


def test_question_extraction():
    assert extract_user_question("@ag02 یک کپی بنویس", "@ag02") == "یک کپی بنویس"
    assert extract_user_question("/all وضعیت؟") == "وضعیت؟"
    assert extract_user_question("/daily").startswith("(بدون متن")
    assert strip_mentions("@ag01 @ag02 سلام").strip() == "سلام"


def test_context_building():
    agent = registry.get("AG01")
    history = [
        {
            "date": datetime(2025, 1, 15, 11, 0, tzinfo=timezone.utc),
            "username": "ali",
            "text": "خط اول\nخط دوم",
            "reply_to_message_id": 42,
        }
    ]
    notion = [{"Name": "رکورد تست", "Status": "فعال", "_url": "https://notion.so/x"}]
    ctx = build_agent_context(agent, notion, history, "بازار را تحلیل کن")
    assert ctx.history_count == 1
    assert "بخش ب" in ctx.user_prompt and "بخش ج" in ctx.user_prompt
    assert "[2025-01-15 14:30] @ali:" in ctx.user_prompt
    assert "رکورد تست" in ctx.user_prompt
    assert "notion.so" in ctx.evidence_hint
    # تاریخچه محدود به ۳۰ پیام
    many = [dict(history[0], text=f"m{i}") for i in range(100)]
    ctx2 = build_agent_context(agent, [], many, "تست", history_limit=30)
    assert ctx2.history_count == 30


def test_empty_notion_message():
    block = format_records_for_prompt("AG05", [])
    assert "هیچ رکورد فعالی" in block and "نه «صفر»" in block


def test_notion_flatten():
    page = {
        "id": "p1",
        "url": "https://notion.so/p1",
        "last_edited_time": "2025-01-15T10:00:00Z",
        "properties": {
            "Name": {"type": "title", "title": [{"plain_text": "عنوان"}]},
            "Status": {"type": "select", "select": {"name": "فعال"}},
            "Tags": {"type": "multi_select", "multi_select": [{"name": "a"}, {"name": "b"}]},
        },
    }
    flat = flatten_page(page)
    assert flat["Name"] == "عنوان" and flat["Status"] == "فعال" and flat["Tags"] == ["a", "b"]


def test_split_and_format():
    assert len(split_for_telegram("x" * 9000)) >= 3
    assert split_for_telegram("") == []
    line = format_message_line(
        {"date": datetime(2025, 1, 15, 11, 0, tzinfo=timezone.utc), "username": "u", "text": "سلام"}
    )
    assert line == "[2025-01-15 14:30] @u: سلام"
    assert "(" in human_today()


async def test_mongo_roundtrip():
    mongo._client = mongomock_motor.AsyncMongoMockClient()
    collection = mongo.get_history_collection("tg_agents", "chat_history")
    await collection.create_indexes(
        [__import__("pymongo").IndexModel([("chat_id", 1), ("message_id", 1)], unique=True)]
    )
    base = datetime.now(timezone.utc)
    for i in range(3):
        await mongo.save_message(
            {"message_id": i, "chat_id": -100, "username": f"u{i}", "text": f"متن {i}",
             "date": base - timedelta(minutes=10 - i)},
            "tg_agents",
        )
    await mongo.save_message(
        {"message_id": 0, "chat_id": -100, "username": "u0", "text": "تکراری", "date": base},
        "tg_agents",
    )
    rows = await mongo.get_last_messages(-100, limit=30, db_name="tg_agents")
    assert len(rows) == 3  # تکراری ذخیره نشد
    assert [r["text"] for r in rows] == ["متن 0", "متن 1", "متن 2"]  # ترتیب قدیمی → جدید


def run_all():
    sync_tests = [
        test_registry, test_routing, test_question_extraction, test_context_building,
        test_empty_notion_message, test_notion_flatten, test_split_and_format,
    ]
    for test in sync_tests:
        test()
        print(f"✅ {test.__name__}")
    asyncio.run(test_mongo_roundtrip())
    print("✅ test_mongo_roundtrip")
    print("\nهمه تست‌ها با موفقیت اجرا شدند.")


if __name__ == "__main__":
    run_all()
