"""build_mention_task_workflow.py — ورک‌فلوی n8n: منشن ایجنت → وظیفه در Notion.

می‌سازد: n8n/workflows/03-mention-to-notion-task.json

تفاوت با 02-telegram-polling.json:
    02 → منشن = پاسخ فوری در تلگرام (بدون Notion)
    03 → منشن = وظیفه در Notion، ایجنت انجام می‌دهد، نتیجه در هر دو جا

⚠️ مهم: 02 و 03 را هم‌زمان Active نکنید — هر دو getUpdates می‌زنند و
    به هم Conflict می‌دهند. و اگر ربات پایتونی هم polling می‌کند،
    فقط یکی باید فعال باشد.
"""

from __future__ import annotations

import json
from pathlib import Path

OUT_DIR = Path(__file__).resolve().parent / "workflows"
OUT_FILE = OUT_DIR / "03-mention-to-notion-task.json"

# --------------------------------------------------------------------------- #
#  گره ۱: بررسی وضعیت (پیکربندی)
# --------------------------------------------------------------------------- #
JS_CONFIG = r"""
// ── ۰) بررسی پیکربندی ────────────────────────────────────────────────────────
// همهٔ مقادیر از Environment Variables در n8n خوانده می‌شوند.
// در n8n → Settings → Environment Variables (یا فایل .env کنار n8n).

const env = (k, d = '') => $env[k] || process.env[k] || d;

const cfg = {
  tgToken:      env('TELEGRAM_BOT_TOKEN'),
  notionKey:    env('NOTION_API_KEY'),
  tasksDb:      env('NOTION_TASKS_DB'),
  notionVer:    env('NOTION_API_VERSION', '2022-06-28'),
  openaiKey:    env('OPENAI_API_KEY'),
  model:        env('OPENAI_MODEL', 'gpt-4o'),

  // نام پراپرتی‌ها در دیتابیس شما — با tools/notion_map.py پیدا کنید
  pTitle:       env('NOTION_TASK_TITLE_PROP', 'Name'),
  pAssignee:    env('NOTION_TASK_ASSIGNEE_PROP', 'Assignee'),
  pStatus:      env('NOTION_TASK_STATUS_PROP', 'Status'),
  pDescription: env('NOTION_TASK_DESCRIPTION_PROP', 'Description'),
  pResult:      env('NOTION_TASK_RESULT_PROP', 'Result'),
  pRequester:   env('NOTION_TASK_REQUESTER_PROP', 'Requester'),
  pSource:      env('NOTION_TASK_SOURCE_PROP', 'Source'),
  pChatId:      env('NOTION_TASK_CHATID_PROP', 'ChatID'),
  pTrace:       env('NOTION_TASK_TRACE_PROP', 'TraceID'),

  // مقدار وضعیت «برای انجام»
  statusTodo:   env('NOTION_TASK_STATUS_TODO', 'برای انجام'),
  statusDoing:  env('NOTION_TASK_STATUS_DOING', 'در حال انجام'),
  statusDone:   env('NOTION_TASK_STATUS_DONE', 'انجام شد'),

  // فیلترها
  minChars:     Number(env('MENTION_TASK_MIN_CHARS', '12')),
  allowBots:    env('MENTION_TASK_ALLOW_BOTS', 'false') === 'true',

  agents: ['AG01','AG02','AG03','AG04','AG05','AG06','AG07','AG08','AG09'],
};

const missing = [];
if (!cfg.tgToken) missing.push('TELEGRAM_BOT_TOKEN');
if (!cfg.notionKey) missing.push('NOTION_API_KEY');
if (!cfg.tasksDb) missing.push('NOTION_TASKS_DB');

if (missing.length) {
  throw new Error(
    'متغیرهای محیطی غایب: ' + missing.join(', ') +
    ' — در n8n → Settings → Environment Variables تنظیم کنید.'
  );
}

return [{ json: cfg }];
"""

# --------------------------------------------------------------------------- #
#  گره ۲: خواندن پیام‌های جدید تلگرام
# --------------------------------------------------------------------------- #
JS_FETCH = r"""
// ── ۱) getUpdates از تلگرام ──────────────────────────────────────────────────
// offset در staticData ذخیره می‌شود تا بین اجراها گم نشود.
const cfg = $('Config').first().json;
const staticData = $getWorkflowStaticData('global');
const offset = staticData.tgOffset || 0;

const resp = await this.helpers.httpRequest({
  method: 'GET',
  url: `https://api.telegram.org/bot${cfg.tgToken}/getUpdates`,
  qs: { offset, timeout: 0, allowed_updates: JSON.stringify(['message']) },
  json: true,
});

if (!resp.ok) {
  throw new Error('getUpdates ناموفق: ' + JSON.stringify(resp).slice(0, 200));
}

const updates = resp.result || [];
if (updates.length) {
  staticData.tgOffset = updates[updates.length - 1].update_id + 1;
}

return updates.map(u => ({ json: u }));
"""

# --------------------------------------------------------------------------- #
#  گره ۳: نرمال‌سازی + تشخیص منشن
# --------------------------------------------------------------------------- #
JS_NORMALIZE = r"""
// ── ۲) استخراج پیام و منشن‌ها ────────────────────────────────────────────────
const cfg = $('Config').first().json;
const update = $json;
const msg = update.message || update.edited_message || update.channel_post;
if (!msg) return [];

const chat = msg.chat || {};
const user = msg.from || {};
const text = msg.text || msg.caption || '';

// ۱) پیام ربات‌ها → نادیده (جلوگیری از حلقه)
if (user.is_bot && !cfg.allowBots) return [];

// ۲) پیام خصوصی را به پایتون بسپار (ویزارد)
if (chat.type === 'private') return [];

// ۳) جست‌وجوی منشن‌ها — پشتیبانی @ag01 و @ag1 و @AG01
const found = [];
for (const ag of cfg.agents) {
  const short = 'ag' + ag.replace(/^AG0?/, '');
  const re = new RegExp(`@(${ag}|${short})\\b`, 'i');
  if (re.test(text)) found.push(ag);
}

if (!found.length) return [];   // منشنی نیست → کاری نکن

// ۴) طول متن بدون منشن
let body = text;
for (const ag of found) {
  body = body.replace(new RegExp(`@${ag}\\b`, 'gi'), '');
  body = body.replace(new RegExp(`@ag0?${Number(ag.slice(2))}\\b`, 'gi'), '');
}
body = body.replace(/\s+/g, ' ').trim().replace(/^[-—:,،]+|[-—:,،]+$/g, '');

// ۵) ریپلای — قبل از سنجش طول، چون «@ag09 وظیفه» روی یک پیام بلند معتبر است
const rt = msg.reply_to_message;
const replyText = rt ? (rt.text || rt.caption || '') : '';
const replyAuthor = rt && rt.from ? (rt.from.username || rt.from.first_name || '') : '';

// طول مؤثر = متن دستور + متن پیام ریپلای‌شده
const effectiveLen = body.length + (replyText ? Math.min(replyText.length, cfg.minChars) : 0);
if (effectiveLen < cfg.minChars) return [];   // «@ag01؟» را وظیفه نکن

// یک آیتم به ازای هر ایجنت منشن‌شده
return found.map(ag => ({
  json: {
    agent_id: ag,
    text: body,
    raw_text: text,
    chat_id: chat.id,
    chat_title: chat.title || 'خصوصی',
    chat_type: chat.type,
    message_id: msg.message_id,
    user_id: user.id || null,
    username: user.username || user.first_name || 'unknown',
    date: msg.date || Math.floor(Date.now() / 1000),
    reply_text: replyText,
    reply_author: replyAuthor,
  },
}));
"""

# --------------------------------------------------------------------------- #
#  گره ۴: ساخت پراپرتی‌های Notion
# --------------------------------------------------------------------------- #
JS_BUILD_PROPS = r"""
// ── ۳) ساخت payload برای Notion ──────────────────────────────────────────────
const cfg = $('Config').first().json;
const d = $json;

// عنوان: خط اول پیام ریپلای‌شده، یا خود متن
const firstLine = (d.reply_text.split('\n')[0] || d.text.split('\n')[0] || 'وظیفه').trim();
const title = firstLine.slice(0, 200);

const description = d.reply_text
  ? `متن پیام ریپلای‌شده (از ${d.reply_author || 'ناشناس'}):\n${d.reply_text}` +
    (d.text ? `\n\nدرخواست از منشن:\n${d.text}` : '')
  : d.text;

// شناسهٔ کوتاه برای پیگیری بین Notion و تلگرام
const trace = `${d.chat_id}:${d.message_id}:${d.agent_id}`;

const properties = {
  [cfg.pTitle]: {
    title: [{ text: { content: title } }],
  },
  [cfg.pAssignee]: {
    select: { name: d.agent_id },
  },
  [cfg.pStatus]: {
    status: { name: cfg.statusTodo },
  },
  [cfg.pDescription]: {
    rich_text: [{ text: { content: description.slice(0, 1900) } }],
  },
  [cfg.pRequester]: {
    rich_text: [{ text: { content: d.username } }],
  },
  [cfg.pSource]: {
    rich_text: [{ text: { content: 'telegram' } }],
  },
  [cfg.pChatId]: {
    rich_text: [{ text: { content: String(d.chat_id) } }],
  },
  [cfg.pTrace]: {
    rich_text: [{ text: { content: trace } }],
  },
};

return [{
  json: {
    ...d,
    title,
    description,
    trace,
    properties,
    notionUrl: `https://api.notion.com/v1/pages`,
  },
}];
"""

# --------------------------------------------------------------------------- #
#  گره ۵: ساخت صفحه در Notion
# --------------------------------------------------------------------------- #
JS_NOTION_BODY = r"""
// بدنهٔ درخواست Notion (برای HTTP Request node)
const cfg = $('Config').first().json;
const d = $json;

return [{
  json: {
    parent: { database_id: cfg.tasksDb },
    properties: d.properties,
  },
}];
"""

# --------------------------------------------------------------------------- #
#  گره ۶: تأیید در تلگرام
# --------------------------------------------------------------------------- #
JS_CONFIRM = r"""
// ── ۵) پاسخ به گروه: «وظیفه ثبت شد» ─────────────────────────────────────────
const cfg = $('Config').first().json;
const prev = $('Build Notion Props').first().json;
const page = $json;   // پاسخ Notion

const pageId = page.id || '';
const pageUrl = page.url || '';

// ساخت لینک کوتاه Notion (حذف https://www.notion.so/)
const shortUrl = pageUrl.replace('https://www.notion.so/', '') || pageId;

const text =
  `🧩 <b>وظیفه ثبت شد</b> → ${prev.agent_id}\n` +
  `<b>عنوان:</b> ${prev.title}\n` +
  (prev.reply_text ? `<b>منبع:</b> ریپلای روی پیام ${prev.reply_author || 'ناشناس'}\n` : '') +
  `<a href="${pageUrl}">مشاهده در Notion</a>\n` +
  `<code>${prev.trace}</code>`;

return [{
  json: {
    chat_id: prev.chat_id,
    reply_to_message_id: prev.message_id,
    text,
    agent_id: prev.agent_id,
    page_id: pageId,
    page_url: pageUrl,
  },
}];
"""

# --------------------------------------------------------------------------- #
#  گره ۷ (اختیاری): اجرای ایجنت — پاسخ LLM
# --------------------------------------------------------------------------- #
JS_BUILD_PROMPT = r"""
// ── ۶) ساخت پرامپت ایجنت برای اجرای فوری ────────────────────────────────────
// توجه: اگر ربات پایتونی polling می‌کند، این بخش را حذف کنید؛
//       پولر پایتون خودش وظیفه را می‌گیرد و اجرا می‌کند.
const cfg = $('Config').first().json;
const d = $('Build Notion Props').first().json;

const missions = {
  AG01: 'تحلیل بازار و رقبا. هر ادعا باید شاهد داشته باشد.',
  AG02: 'نوشتن کپی و متن تبلیغاتی.',
  AG03: 'تولید محتوا و تقویم انتشار.',
  AG04: 'طراحی گرافیک و هویت بصری.',
  AG05: 'توسعه وب و لندینگ.',
  AG06: 'سئو و کلمات کلیدی.',
  AG07: 'تحلیل داده و گزارش.',
  AG08: 'مدیریت کمپین و بودجه.',
  AG09: 'مشاور نهایی: وظیفه را به زیرکارها می‌شکند.',
};

const common = [
  'قواعد مشترک:',
  '۱) حدس نزن. اگر داده نداری بگو «نیازمند تأیید».',
  '۲) هر ادعا باید شاهد داشته باشد (عدد، لینک، یا نقل‌قول).',
  '۳) خانهٔ خالی را صفر یا تأیید حساب نکن.',
  '۴) تصمیم نهایی با مدیر پروژه است.',
  'پاسخ حداکثر ۱۵۰۰ کاراکتر، فارسی، بدون مقدمه.',
].join('\n');

const system = `تو ${d.agent_id} هستی.\nمأموریت: ${missions[d.agent_id] || ''}\n\n${common}`;

return [{
  json: {
    system,
    user: d.description,
    agent_id: d.agent_id,
    ...d,
  },
}];
"""

JS_SELF_CHECK = r"""
// ── ۷) خودبازبینی: ادعای بدون شاهد → «نیازمند تأیید» ───────────────────────
const prev = $('Build Prompt').first().json;
const content = ($json.choices?.[0]?.message?.content || '').trim();

if (!content) {
  return [{ json: { ...prev, answer: '⚠️ پاسخ خالی از مدل — دوباره تلاش کنید.' } }];
}

// اگر هیچ عددی/لینکی/نقل‌قولی نیست و ادعای قطعی دارد → علامت‌گذاری
const hasEvidence = /(\d|https?:\/\/|«|»|منبع|شاهد|طبق|بر اساس)/.test(content);
const isAssertive = /(است\.|هست\.|خواهد شد|تأیید می‌شود)/.test(content);

let answer = content;
if (isAssertive && !hasEvidence) {
  answer += '\n\n⚠️ <b>نیازمند تأیید</b> — این پاسخ شاهد مشخصی ندارد.';
}

return [{ json: { ...prev, answer, hasEvidence } }];
"""

JS_WRITE_RESULT = r"""
// ── ۸) نوشتن نتیجه در Notion ────────────────────────────────────────────────
const cfg = $('Config').first().json;
const d = $json;

return [{
  json: {
    page_id: d.page_id,
    body: {
      properties: {
        [cfg.pResult]: {
          rich_text: [{ text: { content: (d.answer || '').slice(0, 1900) } }],
        },
        [cfg.pStatus]: {
          status: { name: cfg.statusDone },
        },
      },
    },
  },
}];
"""

JS_SEND_ANSWER = r"""
// ── ۹) ارسال پاسخ در تلگرام ─────────────────────────────────────────────────
const cfg = $('Config').first().json;
const d = $('Self Check').first().json;

const header = `👀 <b>${d.agent_id}</b> — ${d.title}`;
let body = d.answer || '';

// تلگرام سقف ۴۰۹۶ کاراکتر دارد
const LIMIT = 3900;
if (body.length > LIMIT) body = body.slice(0, LIMIT) + '\n…(بریده شد)';

const text = `<b>${header}</b>\n\n${body}`;

return [{
  json: {
    chat_id: d.chat_id,
    reply_to_message_id: d.message_id,
    text,
  },
}];
"""

JS_IGNORE = r"""
// هیچ پیام منشنی نبود → پایان بی‌صدا
return [];
"""


# --------------------------------------------------------------------------- #
def node(name, ntype, params, pos, notes="", type_version=1, extra=None):
    n = {
        "parameters": params,
        "id": name.lower().replace(" ", "-"),
        "name": name,
        "type": ntype,
        "typeVersion": type_version,
        "position": list(pos),
        "notes": notes,
        "notesInFlow": bool(notes),
    }
    if extra:
        n.update(extra)
    return n


def build():
    nodes = [
        node(
            "Schedule Trigger", "n8n-nodes-base.scheduleTrigger",
            {"rule": {"interval": [{"field": "seconds", "secondsInterval": 15}]}},
            (-1400, 0), "هر ۱۵ ثانیه پیام‌های جدید را می‌خواند",
            type_version=1.2,
        ),
        node("Config", "n8n-nodes-base.code", {"jsCode": JS_CONFIG}, (-1200, 0),
             "خواندن کلیدها از Environment Variables"),
        node("Telegram getUpdates", "n8n-nodes-base.code", {"jsCode": JS_FETCH}, (-1000, 0),
             "getUpdates با ذخیرهٔ offset"),
        node("Detect Mentions", "n8n-nodes-base.code", {"jsCode": JS_NORMALIZE}, (-800, 0),
             "استخراج @ag01..@ag09 + فیلتر طول/ربات/پیوی"),
        node("Has Mention?", "n8n-nodes-base.filter",
             {"conditions": {"options": {"caseSensitive": True, "leftValue": "", "typeValidation": "strict"},
                             "conditions": [{"id": "c1",
                                             "leftValue": "={{ $json.agent_id }}",
                                             "rightValue": "",
                                             "operator": {"type": "string", "operation": "notEmpty", "singleValue": True}}],
                             "combinator": "and"},
              "options": {}},
             (-600, 0), "بدون منشن → توقف"),
        node("Build Notion Props", "n8n-nodes-base.code", {"jsCode": JS_BUILD_PROPS}, (-400, 0),
             "نگاشت به پراپرتی‌های دیتابیس شما"),
        node("Notion Payload", "n8n-nodes-base.code", {"jsCode": JS_NOTION_BODY}, (-200, 0),
             "بدنهٔ درخواست ساخت صفحه"),
        node("Create Notion Task", "n8n-nodes-base.httpRequest",
             {"method": "POST",
              "url": "https://api.notion.com/v1/pages",
              "authentication": "genericCredentialType",
              "genericAuthType": "httpHeaderAuth",
              "sendHeaders": True,
              "headerParameters": {"parameters": [
                  {"name": "Notion-Version", "value": "={{ $('Config').first().json.notionVer }}"},
                  {"name": "Content-Type", "value": "application/json"},
              ]},
              "sendBody": True,
              "specifyBody": "json",
              "jsonBody": "={{ JSON.stringify($json) }}",
              "options": {}},
             (0, 0), "ساخت رکورد وظیفه در Notion (Credential: Notion API)",
             type_version=4.2),
        node("Format Confirmation", "n8n-nodes-base.code", {"jsCode": JS_CONFIRM}, (200, 0),
             "ساخت پیام «وظیفه ثبت شد»"),
        node("Send Confirmation", "n8n-nodes-base.telegram",
             {"chatId": "={{ $json.chat_id }}",
              "text": "={{ $json.text }}",
              "additionalFields": {"parse_mode": "HTML",
                                   "reply_to_message_id": "={{ $json.reply_to_message_id }}"}},
             (400, 0), "تأیید ثبت در گروه",
             type_version=1.2, extra={"credentials": {"telegramApi": {"id": "telegram", "name": "Telegram"}}}),

        # ---- مسیر اجرای ایجنت (اختیاری) ----
        node("Build Prompt", "n8n-nodes-base.code", {"jsCode": JS_BUILD_PROMPT}, (200, 200),
             "پرامپت ایجنت — اگر ربات پایتونی دارید این مسیر را غیرفعال کنید",
             extra={"disabled": True}),
        node("OpenAI Chat", "n8n-nodes-base.httpRequest",
             {"method": "POST",
              "url": "https://api.openai.com/v1/chat/completions",
              "authentication": "genericCredentialType",
              "genericAuthType": "httpHeaderAuth",
              "sendHeaders": True,
              "headerParameters": {"parameters": [{"name": "Content-Type", "value": "application/json"}]},
              "sendBody": True,
              "specifyBody": "json",
              "jsonBody": "={{ JSON.stringify({model: $('Config').first().json.model, messages: [{role:'system',content:$json.system},{role:'user',content:$json.user}], temperature: 0.4, max_tokens: 1200}) }}",
              "options": {}},
             (400, 200), "فراخوانی مدل", type_version=4.2,
             extra={"disabled": True}),
        node("Self Check", "n8n-nodes-base.code", {"jsCode": JS_SELF_CHECK}, (600, 200),
             "ادعای بدون شاهد → «نیازمند تأیید»", extra={"disabled": True}),
        node("Write Result", "n8n-nodes-base.httpRequest",
             {"method": "PATCH",
              "url": "=https://api.notion.com/v1/pages/{{ $json.page_id }}",
              "authentication": "genericCredentialType",
              "genericAuthType": "httpHeaderAuth",
              "sendHeaders": True,
              "headerParameters": {"parameters": [
                  {"name": "Notion-Version", "value": "={{ $('Config').first().json.notionVer }}"},
                  {"name": "Content-Type", "value": "application/json"},
              ]},
              "sendBody": True,
              "specifyBody": "json",
              "jsonBody": "={{ JSON.stringify($json.body) }}",
              "options": {}},
             (800, 200), "نوشتن پاسخ + تغییر وضعیت به «انجام شد»", type_version=4.2,
             extra={"disabled": True}),
        node("Send Answer", "n8n-nodes-base.telegram",
             {"chatId": "={{ $json.chat_id }}",
              "text": "={{ $json.text }}",
              "additionalFields": {"parse_mode": "HTML",
                                   "reply_to_message_id": "={{ $json.reply_to_message_id }}"}},
             (1000, 200), "ارسال پاسخ ایجنت در گروه",
             type_version=1.2, extra={"disabled": True,
                                      "credentials": {"telegramApi": {"id": "telegram", "name": "Telegram"}}}),
    ]

    connections = {
        "Schedule Trigger": {"main": [[{"node": "Config", "type": "main", "index": 0}]]},
        "Config": {"main": [[{"node": "Telegram getUpdates", "type": "main", "index": 0}]]},
        "Telegram getUpdates": {"main": [[{"node": "Detect Mentions", "type": "main", "index": 0}]]},
        "Detect Mentions": {"main": [[{"node": "Has Mention?", "type": "main", "index": 0}]]},
        "Has Mention?": {"main": [[{"node": "Build Notion Props", "type": "main", "index": 0}], []]},
        "Build Notion Props": {"main": [[{"node": "Notion Payload", "type": "main", "index": 0}]]},
        "Notion Payload": {"main": [[{"node": "Create Notion Task", "type": "main", "index": 0}]]},
        "Create Notion Task": {"main": [[
            {"node": "Format Confirmation", "type": "main", "index": 0},
            {"node": "Build Prompt", "type": "main", "index": 0},
        ]]},
        "Format Confirmation": {"main": [[{"node": "Send Confirmation", "type": "main", "index": 0}]]},
        "Build Prompt": {"main": [[{"node": "OpenAI Chat", "type": "main", "index": 0}]]},
        "OpenAI Chat": {"main": [[{"node": "Self Check", "type": "main", "index": 0}]]},
        "Self Check": {"main": [[
            {"node": "Write Result", "type": "main", "index": 0},
            {"node": "Send Answer", "type": "main", "index": 0},
        ]]},
    }

    workflow = {
        "name": "03 — منشن ایجنت → وظیفه در Notion",
        "nodes": nodes,
        "connections": connections,
        "active": False,
        "settings": {"executionOrder": "v1", "saveManualExecutions": True,
                     "callerPolicy": "workflowsFromSameOwner"},
        "staticData": None,
        "pinData": {},
        "meta": {"templateCredsSetupCompleted": False},
        "tags": [{"name": "agents"}, {"name": "notion"}],
    }
    return workflow


def validate(wf: dict) -> list[str]:
    problems = []
    names = {n["name"] for n in wf["nodes"]}
    for src, conn in wf["connections"].items():
        if src not in names:
            problems.append(f"اتصال از نود ناموجود: {src}")
        for outputs in conn.get("main", []):
            for target in outputs:
                if target["node"] not in names:
                    problems.append(f"اتصال به نود ناموجود: {target['node']}")
    # نودهای یتیم (به‌جز Trigger)
    targeted = {t["node"] for c in wf["connections"].values()
                for outs in c.get("main", []) for t in outs}
    for n in wf["nodes"]:
        if n["name"] not in targeted and n["type"] != "n8n-nodes-base.scheduleTrigger":
            problems.append(f"نود بدون ورودی (یتیم): {n['name']}")
    return problems


def main() -> int:
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    wf = build()

    problems = validate(wf)
    if problems:
        print("✗ مشکلات ساختاری:")
        for p in problems:
            print("   -", p)
        return 1

    OUT_FILE.write_text(
        json.dumps(wf, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )
    total = len(wf["nodes"])
    active = sum(1 for n in wf["nodes"] if not n.get("disabled"))
    print(f"✓ {OUT_FILE.name}")
    print(f"  نودها: {total} ({active} فعال، {total - active} آمادهٔ فعال‌سازی)")
    print(f"  حجم: {OUT_FILE.stat().st_size // 1024}KB")
    print(f"  ساختار: {len(wf['connections'])} اتصال — معتبر")
    return 0


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