#!/usr/bin/env python3
"""notion_agent.py — اتوماسیون Notion، بدون تلگرام.

هر بار که در Notion ایجنتی منشن شود، آن ایجنت پاسخ می‌دهد.

استفاده:
    python notion_agent.py --once              # یک دور اسکن
    python notion_agent.py --once --dry-run    # فقط نشان بده، ننویس
    python notion_agent.py --watch             # حلقهٔ دائمی
    python notion_agent.py --test-prompt "@AG04 لوگو بساز"
    python notion_agent.py --check             # بررسی اتصال و تنظیمات

سه منبع:
    --inbox <database_id>    دیتابیسی که هر ردیف یک درخواست است
    --tasks <database_id>    دیتابیس Tasks (Assignee + Result)
    --pages <id1,id2>        صفحه‌هایی که کامنت‌هایشان رصد شود
    --recent N               N صفحهٔ اخیراً ویرایش‌شده (پیش‌فرض ۲۵)
"""

from __future__ import annotations

import argparse
import logging
import sys
import time
from pathlib import Path

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

from config.settings import settings  # noqa: E402
from services.notion_native import (  # noqa: E402
    NotionClient,
    NotionNativeAutomation,
    build_prompt,
    extract_agent_ids,
)

G, R, Y, B, N = "\033[32m", "\033[31m", "\033[33m", "\033[34m", "\033[0m"
if not sys.stdout.isatty():
    G = R = Y = B = N = ""

OK, BAD, WARN, INFO = f"{G}✓{N}", f"{R}✗{N}", f"{Y}!{N}", f"{B}•{N}"


def setup_logging(verbose: bool) -> None:
    logging.basicConfig(
        level=logging.DEBUG if verbose else logging.INFO,
        format="%(asctime)s | %(levelname)-7s | %(name)s | %(message)s",
        datefmt="%H:%M:%S",
    )


# --------------------------------------------------------------------------- #
def cmd_check() -> int:
    print("═" * 62)
    print("  بررسی اتصال Notion")
    print("═" * 62)

    ok = True

    # کلید
    if not settings.notion_api_key:
        print(f"{BAD} NOTION_API_KEY خالی است")
        print("    → ./wiring.sh --notion-key secret_...")
        return 1
    print(f"{OK} کلید Notion (…{settings.notion_api_key[-4:]})")

    client = NotionClient()
    if not client.available:
        print(f"{BAD} کلاینت ساخته نشد — notion-client نصب است؟")
        return 1

    # تست اتصال
    pages, err = client.search_recently_edited(3)
    if err:
        print(f"{BAD} اتصال: {err}")
        ok = False
    else:
        print(f"{OK} اتصال برقرار — {len(pages)} صفحه یافت شد")

    # منابع
    print()
    if settings.notion_inbox_db:
        rows, e = client.query_database(settings.notion_inbox_db, page_size=1)
        print(f"{OK if not e else BAD} Inbox: {settings.notion_inbox_db[:8]}… {e or f'{len(rows)} ردیف'}")
        ok = ok and not e
    else:
        print(f"{INFO} Inbox تنظیم نشده")

    if settings.notion_tasks_db:
        rows, e = client.query_database(settings.notion_tasks_db, page_size=1)
        print(f"{OK if not e else BAD} Tasks: {settings.notion_tasks_db[:8]}… {e or f'{len(rows)} ردیف'}")
        ok = ok and not e
    else:
        print(f"{INFO} Tasks تنظیم نشده")

    if settings.notion_watch_pages:
        ids = [x.strip() for x in settings.notion_watch_pages.split(",") if x.strip()]
        print(f"{OK} صفحه‌های رصد: {len(ids)}")
    elif settings.notion_watch_recent:
        print(f"{OK} صفحه‌های اخیر: {settings.notion_watch_recent}")
    else:
        print(f"{WARN} هیچ صفحه‌ای رصد نمی‌شود")

    # پاسخ‌دهنده
    print()
    provider = (settings.llm_provider or "openai").lower()
    if provider == "offline":
        print(f"{OK} پاسخ‌دهنده: offline (قاعده‌محور، بدون کلید)")
    elif provider == "ollama":
        print(f"{OK} پاسخ‌دهنده: ollama ({settings.llm_base_url or 'localhost:11434'})")
    elif settings.active_llm_key:
        print(f"{OK} پاسخ‌دهنده: {provider} / {settings.openai_model}")
    else:
        print(f"{BAD} پاسخ‌دهنده: کلید {provider} خالی است")
        ok = False

    # نگاشت کاربران
    if settings.notion_user_agent_map:
        print(f"{OK} نگاشت کاربر→ایجنت: {settings.notion_user_agent_map}")
    else:
        print(f"{INFO} نگاشت کاربر تنظیم نشده (منشن متنی @AG04 کافی است)")

    print()
    print(f"{OK} آماده است" if ok else f"{BAD} مشکلات بالا را رفع کنید")
    return 0 if ok else 1


def cmd_test_prompt(text: str) -> int:
    """ساخت پرامپت از متن دلخواه و اجرای پاسخ‌دهنده."""
    agents = extract_agent_ids(text)
    if not agents:
        print(f"{BAD} هیچ ایجنتی در متن نیست. مثال: \"@AG04 لوگو بساز\"")
        return 1

    print(f"{INFO} ایجنت‌های شناسایی‌شده: {', '.join(agents)}\n")

    auto = NotionNativeAutomation()
    for agent_id in agents:
        prompt = build_prompt(agent_id=agent_id, mention_text=text, page_title="(تست)")
        print(f"{B}── پرامپت {agent_id} ──{N}")
        print(prompt[:900])
        print(f"\n{B}── پاسخ ──{N}")
        try:
            answer = auto._answer_sync(prompt)  # noqa: SLF001
        except Exception as exc:  # noqa: BLE001
            print(f"{BAD} خطا: {exc}")
            continue
        print(answer)
        print()

    return 0


def cmd_run(once: bool, dry_run: bool, interval: int) -> int:
    auto = NotionNativeAutomation()
    if not auto.client.available:
        print(f"{BAD} کلید Notion خالی است → ./wiring.sh --notion-key secret_...")
        return 1

    post = not dry_run
    cycle = 0

    def one_pass() -> int:
        nonlocal cycle
        cycle += 1
        before = dict(auto.stats)
        results = auto.tick(post=post)
        delta = {k: auto.stats[k] - before.get(k, 0) for k in auto.stats}

        stamp = time.strftime("%H:%M:%S")
        print(
            f"{INFO} [{stamp}] دور {cycle} — اسکن {delta['scanned']} | "
            f"منشن {delta['matched']} | پاسخ {delta['answered']} | "
            f"نوشته {delta['posted']} | خطا {delta['errors']}"
        )
        for r in results:
            icon = "✅" if r.posted else ("❌" if r.error else "•")
            print(f"   {icon} {r.agent_id} [{r.source}] {r.answer[:70]!r}")
            if r.error:
                print(f"      خطا: {r.error}")
        if dry_run and results:
            print(f"   {Y}(dry-run: هیچ‌چیز در Notion نوشته نشد){N}")
        return len(results)

    if once:
        one_pass()
        auto.close()
        return 0

    print(f"{OK} حالت رصد فعال — هر {interval} ثانیه (Ctrl+C برای توقف)")
    if dry_run:
        print(f"{Y}⚠️ dry-run: پاسخ‌ها فقط نمایش داده می‌شوند{N}")
    try:
        while True:
            try:
                one_pass()
            except KeyboardInterrupt:
                raise
            except Exception as exc:  # noqa: BLE001
                print(f"{BAD} خطا در دور {cycle}: {exc}")
            time.sleep(interval)
    except KeyboardInterrupt:
        print(f"\n{INFO} توقف. مجموع: {auto.stats}")
    finally:
        auto.close()
    return 0


# --------------------------------------------------------------------------- #
def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser(
        description="اتوماسیون Notion: منشن ایجنت → پاسخ ایجنت (بدون تلگرام)"
    )
    ap.add_argument("--once", action="store_true", help="یک دور اسکن و خروج")
    ap.add_argument("--watch", action="store_true", help="حلقهٔ دائمی")
    ap.add_argument("--dry-run", action="store_true", help="ننویس، فقط نشان بده")
    ap.add_argument("--check", action="store_true", help="بررسی اتصال و تنظیمات")
    ap.add_argument("--test-prompt", metavar="TEXT", default="", help="تست پرامپت از متن")
    ap.add_argument("--interval", type=int, default=0, help="بازهٔ اسکن (ثانیه)")
    ap.add_argument("--inbox", default="", help="شناسهٔ دیتابیس Inbox")
    ap.add_argument("--tasks", default="", help="شناسهٔ دیتابیس Tasks")
    ap.add_argument("--pages", default="", help="شناسهٔ صفحه‌ها با کاما")
    ap.add_argument("--recent", type=int, default=-1, help="تعداد صفحهٔ اخیر")
    ap.add_argument("-v", "--verbose", action="store_true")
    args = ap.parse_args(argv)

    setup_logging(args.verbose)

    # override تنظیمات با آرگومان‌ها
    if args.inbox:
        settings.notion_inbox_db = args.inbox
    if args.tasks:
        settings.notion_tasks_db = args.tasks
    if args.pages:
        settings.notion_watch_pages = args.pages
    if args.recent >= 0:
        settings.notion_watch_recent = args.recent
    interval = args.interval or settings.notion_native_interval

    if args.check:
        return cmd_check()
    if args.test_prompt:
        return cmd_test_prompt(args.test_prompt)
    if args.once or args.watch:
        return cmd_run(once=args.once, dry_run=args.dry_run, interval=interval)

    ap.print_help()
    print(f"\n{INFO} مثال‌ها:")
    print("  python notion_agent.py --check")
    print("  python notion_agent.py --test-prompt '@AG04 برای لانچ لوگو طراحی کن'")
    print("  python notion_agent.py --once --dry-run --pages <page-id>")
    print("  python notion_agent.py --watch --inbox <db-id>")
    return 0


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