#!/usr/bin/env python3
"""check_wiring.py — بررسی اینکه دیتابیس‌های Notion و ربات درست به هم وصل شده‌اند.

این اسکریپت بدون تغییر چیزی، فقط **می‌سنجد**:
  ۱) NOTION_API_KEY معتبر است؟
  ۲) هر ۸ دیتابیس ایجنت وجود دارد و integration به آن دسترسی دارد؟
  ۳) دیتابیس Tasks ساخته شده و پراپرتی‌های لازم را دارد؟
     (مهم: Status باید نوع `status` باشد با گزینه‌های فارسی درست)
  ۴) دیتابیس daily_log
  ۵) توکن تلگرام معتبر است؟ (getMe)
  ۶) MongoDB و OpenAI

اجرا:
    python tools/check_wiring.py
    python tools/check_wiring.py --test-task      # یک وظیفهٔ آزمایشی در Notion بساز
    python tools/check_wiring.py --env .env
"""

from __future__ import annotations

import argparse
import asyncio
import json
import os
import sys
import urllib.error
import urllib.request
from pathlib import Path

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

OK = "\033[92m✓\033[0m"
NO = "\033[91m✗\033[0m"
WARN = "\033[93m!\033[0m"

required_status = ["بک‌لاگ", "برای انجام", "در حال انجام", "منتظر بازبینی", "انجام شد", "مسدود", "رد شد"]
required_task_props = {
    "Name": "title",
    "Assignee": "select",
    "Status": "status",
    "Description": "rich_text",
    "Result": "rich_text",
    "ParentTask": "rich_text",
    "TraceID": "rich_text",
    "ChatID": "number",
}


def load_env(path: Path) -> dict[str, str]:
    """خواندن .env بدون وابستگی به کتابخانه."""
    env: dict[str, str] = {}
    if not path.exists():
        return env
    for raw in path.read_text(encoding="utf-8").splitlines():
        line = raw.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        k, _, v = line.partition("=")
        env[k.strip()] = v.strip().strip('"').strip("'")
    return env


def clean_notion_id(value: str) -> str:
    """پذیرش URL یا UUID خام و تبدیل به شناسهٔ خالص."""
    if not value:
        return ""
    v = value.strip()
    if "/" in v:  # URL: https://notion.so/Title-<32hex>
        tail = v.rstrip("/").split("/")[-1]
        v = tail.split("-")[-1] if len(tail.split("-")[-1]) == 32 else tail
    v = v.replace("-", "")
    import re

    m = re.search(r"[0-9a-fA-F]{32}", v)
    return m.group(0) if m else v


def http_json(url: str, headers: dict, method: str = "GET", body: dict | None = None) -> dict:
    data = json.dumps(body).encode() if body else None
    req = urllib.request.Request(url, data=data, headers=headers, method=method)
    if data:
        req.add_header("Content-Type", "application/json")
    try:
        with urllib.request.urlopen(req, timeout=25) as r:
            return json.loads(r.read())
    except urllib.error.HTTPError as e:
        try:
            return json.loads(e.read())
        except Exception:  # noqa: BLE001
            return {"error": f"HTTP {e.code}", "message": str(e)}
    except Exception as e:  # noqa: BLE001
        return {"error": str(e)}


class Checker:
    def __init__(self, env: dict[str, str]) -> None:
        self.env = env
        self.key = env.get("NOTION_API_KEY", "").strip()
        self.problems: list[str] = []
        self.warnings: list[str] = []

    def _nv(self, key: str) -> str:
        return self.env.get(key, "").strip()

    # ------------------------------------------------------------------ #
    def check_telegram(self) -> None:
        token = self._nv("TELEGRAM_BOT_TOKEN")
        if not token or ":" not in token:
            print(f"  {NO} TELEGRAM_BOT_TOKEN خالی یا نامعتبر")
            self.problems.append("TELEGRAM_BOT_TOKEN را با ./run.sh set TELEGRAM_BOT_TOKEN ... بگذارید")
            return
        data = http_json(f"https://api.telegram.org/bot{token}/getMe", {})
        if data.get("ok"):
            me = data["result"]
            print(f"  {OK} تلگرام: @{me.get('username')} ({me.get('first_name')})")
        else:
            print(f"  {NO} تلگرام: {data.get('description') or data.get('error')}")
            self.problems.append("توکن تلگرام نامعتبر است — از BotFather توکن جدید بگیرید")

    # ------------------------------------------------------------------ #
    def check_notion_key(self) -> bool:
        if not self.key:
            print(f"  {NO} NOTION_API_KEY خالی")
            self.problems.append("NOTION_API_KEY را از notion.so/my-integrations بگیرید")
            return False
        data = http_json(
            "https://api.notion.com/v1/users/me",
            {"Authorization": f"Bearer {self.key}", "Notion-Version": "2022-06-28"},
        )
        if data.get("object") == "user" or data.get("bot"):
            name = (data.get("bot") or {}).get("owner", {})
            print(f"  {OK} کلید Notion معتبر ({data.get('name') or 'integration'})")
            return True
        print(f"  {NO} کلید Notion: {data.get('message') or data.get('error')}")
        self.problems.append("NOTION_API_KEY نامعتبر است")
        return False

    # ------------------------------------------------------------------ #
    def get_db(self, db_id: str) -> dict:
        return http_json(
            f"https://api.notion.com/v1/databases/{db_id}",
            {"Authorization": f"Bearer {self.key}", "Notion-Version": "2022-06-28"},
        )

    def check_agent_dbs(self) -> None:
        mapping = {
            "AG01": "NOTION_DB_MARKET", "AG02": "NOTION_DB_COPY",
            "AG03": "NOTION_DB_CONTENT", "AG04": "NOTION_DB_DESIGN",
            "AG05": "NOTION_DB_WEB", "AG06": "NOTION_DB_SEO",
            "AG07": "NOTION_DB_DATA", "AG08": "NOTION_DB_CAMPAIGN",
        }
        print("\n  ۸ دیتابیس ایجنت:")
        for agent, key in mapping.items():
            raw = self._nv(key)
            if not raw:
                print(f"    {WARN} {agent}: {key} خالی (اختیاری — بخش Notion آن ایجنت خالی می‌ماند)")
                self.warnings.append(f"{key} خالی است → {agent} بدون دادهٔ Notion کار می‌کند")
                continue
            db = self.get_db(clean_notion_id(raw))
            if db.get("object") == "database":
                title = "".join(t.get("plain_text", "") for t in db.get("title", []))
                print(f"    {OK} {agent}: {title or '(بدون عنوان)'}")
            else:
                print(f"    {NO} {agent}: {db.get('message') or db.get('error')}")
                self.problems.append(
                    f"{key} در دسترس نیست — integration را به آن دیتابیس Share کنید "
                    f"(در Notion: دیتابیس → ⋯ → Connections)"
                )

    # ------------------------------------------------------------------ #
    def check_tasks_db(self) -> bool:
        raw = self._nv("NOTION_TASKS_DB")
        print("\n  دیتابیس Tasks (قلب اتوماسیون):")
        if not raw:
            print(f"    {NO} NOTION_TASKS_DB خالی")
            self.problems.append(
                "NOTION_TASKS_DB را بگذارید با: ./run.sh set NOTION_TASKS_DB <id>  "
                "(یا بسازید: python tools/setup_notion.py --key ... --write-env .env)"
            )
            return False

        db = self.get_db(clean_notion_id(raw))
        if db.get("object") != "database":
            print(f"    {NO} دسترسی ندارد: {db.get('message') or db.get('error')}")
            self.problems.append(
                "integration را در Notion به دیتابیس Tasks Share کنید "
                "(دیتابیس → ⋯ → Connections → انتخاب integration)"
            )
            return False

        title = "".join(t.get("plain_text", "") for t in db.get("title", []))
        print(f"    {OK} دیتابیس پیدا شد: {title or '(بدون عنوان)'}")

        props = db.get("properties", {})
        missing, wrong = [], []
        for name, ptype in required_task_props.items():
            if name not in props:
                missing.append(name)
            elif props[name].get("type") != ptype:
                wrong.append(f"{name} ({props[name].get('type')} بجای {ptype})")

        if missing:
            print(f"    {NO} پراپرتی‌های گم‌شده: {', '.join(missing)}")
            self.problems.append(
                f"این پراپرتی‌ها را به دیتابیس Tasks اضافه کنید: {', '.join(missing)}"
            )
        if wrong:
            print(f"    {WARN} نوع اشتباه: {', '.join(wrong)}")
            self.warnings.append(
                f"نوع این پراپرتی‌ها را عوض کنید: {', '.join(wrong)} "
                "(یا نامشان را در .env با NOTION_TASK_*_PROP ست کنید)"
            )

        # گزینه‌های Status
        status_prop = props.get("Status", {})
        stype = status_prop.get("type")
        if stype == "select":
            options = [o.get("name") for o in status_prop.get("select", {}).get("options", [])]
            print(f"    {WARN} Status از نوع select است (پیش‌فرض ما status) — کار می‌کند ولی...")
            self.warnings.append(
                "Status را از نوع Status بسازید یا NOTION_TASK_STATUS_PROP را ست کنید"
            )
        elif stype == "status":
            options = []
            groups = status_prop.get("status", {}).get("options", []) or []
            for g in (status_prop.get("status", {}).get("groups") or []):
                for o in g.get("option_ids", []) and [] or []:
                    pass
            # ساختار واقعی: options لیست تخت
            options = [o.get("name") for o in status_prop.get("status", {}).get("options", [])]
        else:
            options = []

        if options:
            missing_opts = [s for s in ["برای انجام", "در حال انجام", "منتظر بازبینی"] if s not in options]
            if missing_opts:
                print(f"    {NO} گزینه‌های گم‌شدهٔ Status: {', '.join(missing_opts)}")
                self.problems.append(
                    f"گزینه‌های Status را اضافه کنید: {', '.join(missing_opts)}"
                )
            else:
                print(f"    {OK} گزینه‌های Status کامل ({len(options)} گزینه)")

        # Assignee باید select با AG01..AG09 باشد
        assignee = props.get("Assignee", {})
        if assignee.get("type") == "select":
            opts = [o.get("name", "").upper() for o in assignee.get("select", {}).get("options", [])]
            missing_agents = [f"AG{i:02d}" for i in range(1, 10) if f"AG{i:02d}" not in opts]
            if missing_agents:
                print(f"    {WARN} گزینه‌های Assignee ناقص: {', '.join(missing_agents)}")
                self.warnings.append(
                    f"این گزینه‌ها را به Assignee اضافه کنید: {', '.join(missing_agents)}"
                )
            else:
                print(f"    {OK} Assignee: همهٔ AG01..AG09 موجود")
        else:
            print(f"    {NO} Assignee باید نوع Select باشد (الان: {assignee.get('type')})")
            self.problems.append("پراپرتی Assignee را از نوع Select بسازید")
        return True

    # ------------------------------------------------------------------ #
    def check_daily_log(self) -> None:
        raw = self._nv("NOTION_DAILY_LOG_DB")
        print("\n  دیتابیس daily_log:")
        if not raw:
            print(f"    {WARN} NOTION_DAILY_LOG_DB خالی (اختیاری)")
            self.warnings.append("daily_log خالی است → ثبت گزارش روزانه غیرفعال می‌شود")
            return
        db = self.get_db(clean_notion_id(raw))
        if db.get("object") == "database":
            print(f"    {OK} در دسترس است")
        else:
            print(f"    {NO} {db.get('message') or db.get('error')}")
            self.problems.append("NOTION_DAILY_LOG_DB در دسترس نیست — Share کنید")

    # ------------------------------------------------------------------ #
    def check_others(self) -> None:
        print("\n  سایر سرویس‌ها:")
        llm = self._nv("OPENAI_API_KEY")
        if llm.startswith("sk-"):
            print(f"  {OK} OPENAI_API_KEY تنظیم شده (اعتبار چک نمی‌شود تا هزینه نسازد)")
        else:
            print(f"  {NO} OPENAI_API_KEY خالی یا نامعتبر")
            self.problems.append("OPENAI_API_KEY را بگذارید — بدون آن هیچ ایجنتی پاسخ نمی‌دهد")

        mongo = self._nv("MONGODB_URI")
        if mongo and not mongo.startswith("mongodb://localhost") and "example" not in mongo:
            print(f"  {OK} MONGODB_URI تنظیم شده")
        else:
            print(f"  {WARN} MONGODB_URI محلی/نمونه است → تاریخچهٔ چت روی هاست ذخیره نمی‌شود")
            self.warnings.append("MONGODB_URI را به Atlas وصل کنید (تاریخچهٔ ۳۰ پیام گروه)")

        if self._nv("TASKS_AUTO_CLOSE").lower() in {"true", "1", "yes"}:
            print(f"  {WARN} TASKS_AUTO_CLOSE=true → نتیجه بدون تأیید مدیر «انجام شد» می‌شود")
        else:
            print(f"  {OK} TASKS_AUTO_CLOSE=false → نتیجه منتظر تأیید مدیر می‌ماند")

    # ------------------------------------------------------------------ #
    def create_test_task(self) -> None:
        print("\n  ساخت یک وظیفهٔ آزمایشی در Tasks:")
        raw = self._nv("NOTION_TASKS_DB")
        if not raw:
            print(f"    {NO} بدون NOTION_TASKS_DB ممکن نیست")
            return
        body = {
            "parent": {"database_id": clean_notion_id(raw)},
            "properties": {
                "Name": {"title": [{"type": "text", "text": {"content": "تست اتصال ✅"}}]},
                "Assignee": {"select": {"name": "AG01"}},
                "Status": {"status": {"name": "برای انجام"}},
                "Description": {"rich_text": [{"type": "text", "text": {"content": "این رکورد را پولر برمی‌دارد. اگر نمی‌خواهید اجرا شود، پاکش کنید."}}]},
                "TraceID": {"rich_text": [{"type": "text", "text": {"content": "wiringtest"}}]},
            },
        }
        res = http_json(
            "https://api.notion.com/v1/pages",
            {"Authorization": f"Bearer {self.key}", "Notion-Version": "2022-06-28"},
            method="POST",
            body=body,
        )
        if res.get("id"):
            print(f"    {OK} ساخته شد: {res.get('url')}")
            print("      → پولر ربات باید آن را ظرف ۳۰ ثانیه بردارد")
        else:
            print(f"    {NO} {res.get('message') or res.get('error')}")
            self.problems.append("ساخت وظیفهٔ آزمایشی ناموفق — نوع پراپرتی‌ها را چک کنید")

    # ------------------------------------------------------------------ #
    def run(self, test_task: bool = False) -> int:
        print("=" * 70)
        print("  بررسی اتصال: تلگرام ↔ Notion ↔ ربات")
        print("=" * 70)
        print("\n  تلگرام:")
        self.check_telegram()

        print("\n  Notion:")
        has_key = self.check_notion_key()
        if has_key:
            self.check_agent_dbs()
            self.check_tasks_db()
            self.check_daily_log()
            if test_task:
                self.create_test_task()

        self.check_others()

        print("\n" + "=" * 70)
        if self.problems:
            print(f"  {NO} {len(self.problems)} مشکل باید حل شود:")
            for i, p in enumerate(self.problems, 1):
                print(f"     {i}) {p}")
        if self.warnings:
            print(f"\n  {WARN} {len(self.warnings)} هشدار (اختیاری):")
            for w in self.warnings:
                print(f"     • {w}")
        if not self.problems:
            print(f"\n  {OK} همه‌چیز برای اجرا آماده است → ./run.sh start --polling")
        print("=" * 70)
        return 1 if self.problems else 0


def main() -> int:
    ap = argparse.ArgumentParser(description="بررسی اتصال Notion/تلگرام/ربات")
    ap.add_argument("--env", default=str(ROOT / ".env"))
    ap.add_argument("--test-task", action="store_true", help="ساخت وظیفهٔ آزمایشی در Notion")
    args = ap.parse_args()

    env_path = Path(args.env)
    if not env_path.exists():
        print(f"❌ فایل {env_path} وجود ندارد. اول: ./run.sh fix-env <TOKEN>")
        return 1

    env = load_env(env_path)
    # متغیرهای محیطی سیستم اولویت دارند
    for k, v in os.environ.items():
        if k in env or k.startswith(("TELEGRAM_", "NOTION_", "OPENAI_", "MONGODB_", "TASKS_")):
            env.setdefault(k, v)

    return Checker(env).run(test_args := args.test_task)


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