"""
ساخت ورک‌فلوهای n8n از همان config/agents.yaml پروژه.

خروجی:
    n8n/workflows/01-telegram-agents-router.json   ← ورک‌فلوی اصلی (import در n8n)
    n8n/prompts/AG01.txt … AG09.txt                ← System Prompt آماده برای هر ایجنت
    n8n/workflows/00-mongo-setup.json              ← ساخت ایندکس‌های MongoDB

اجرا:
    python n8n/build_workflows.py
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

import yaml

BASE = Path(__file__).resolve().parent.parent
OUT = BASE / "n8n"
PROMPT_DIR = OUT / "prompts"
WORKFLOW_DIR = OUT / "workflows"


# --------------------------------------------------------------------------- #
#  توابع کمکی برای ساخت گره‌های n8n
# --------------------------------------------------------------------------- #
def node_name(name: str) -> str:
    return name


def code_node(name: str, js: str, position: list[int], notes: str = "") -> dict[str, Any]:
    return {
        "parameters": {"jsCode": js.strip() + "\n"},
        "id": _id(name),
        "name": name,
        "type": "n8n-nodes-base.code",
        "typeVersion": 2,
        "position": position,
        "notes": notes,
        "notesInFlow": bool(notes),
    }


def _id(name: str) -> str:
    return "n8n-" + "".join(ch.lower() if ch.isalnum() else "-" for ch in name)[:40]


def mongo_node(
    name: str,
    operation: str,
    position: list[int],
    *,
    collection: str = "chat_history",
    query: str = "{}",
    fields: str = "",
    limit: int | None = None,
    sort: str = "",
    extra: dict[str, Any] | None = None,
    notes: str = "",
) -> dict[str, Any]:
    parameters: dict[str, Any] = {
        "operation": operation,
        "collection": collection,
        "options": {},
    }
    if operation == "insert":
        parameters["fields"] = fields or "={{ $json }}"
    else:
        parameters["query"] = query
        if fields:
            parameters["fields"] = fields
    options: dict[str, Any] = {}
    if limit is not None:
        options["limit"] = limit
    if sort:
        options["sort"] = sort
    if options:
        parameters["options"] = options
    if extra:
        parameters.update(extra)
    return {
        "parameters": parameters,
        "id": _id(name),
        "name": name,
        "type": "n8n-nodes-base.mongoDb",
        "typeVersion": 1,
        "position": position,
        "credentials": {
            "mongoDb": {"id": "REPLACE_MONGO_CRED_ID", "name": "MongoDB - tg_agents"}
        },
        "notes": notes,
        "notesInFlow": bool(notes),
    }


def telegram_trigger(name: str, position: list[int]) -> dict[str, Any]:
    return {
        "parameters": {
            "updates": ["message", "edited_message"],
            "additionalFields": {},
        },
        "id": _id(name),
        "name": name,
        "type": "n8n-nodes-base.telegramTrigger",
        "typeVersion": 1.1,
        "position": position,
        "credentials": {
            "telegramApi": {"id": "REPLACE_TELEGRAM_CRED_ID", "name": "Telegram Bot"}
        },
        "webhookId": "REPLACE-TELEGRAM-WEBHOOK-ID",
    }


def telegram_send(
    name: str, position: list[int], text: str, parse_mode: str = "HTML"
) -> dict[str, Any]:
    return {
        "parameters": {
            "chatId": "={{ $('Normalize Message').item.json.chat_id }}",
            "text": text,
            "additionalFields": {
                "parse_mode": parse_mode,
                "appendAttribution": False,
            },
        },
        "id": _id(name),
        "name": name,
        "type": "n8n-nodes-base.telegram",
        "typeVersion": 1.2,
        "position": position,
        "credentials": {
            "telegramApi": {"id": "REPLACE_TELEGRAM_CRED_ID", "name": "Telegram Bot"}
        },
    }


def http_node(name: str, position: list[int], url: str, body: dict, headers: dict) -> dict[str, Any]:
    return {
        "parameters": {
            "method": "POST",
            "url": url,
            "sendHeaders": True,
            "headerParameters": {
                "parameters": [{"name": k, "value": v} for k, v in headers.items()]
            },
            "sendBody": True,
            "specifyBody": "json",
            "jsonBody": body,
            "options": {"timeout": 120000},
        },
        "id": _id(name),
        "name": name,
        "type": "n8n-nodes-base.httpRequest",
        "typeVersion": 4.2,
        "position": position,
    }


# --------------------------------------------------------------------------- #
#  کدهای JavaScript داخل گره‌ها
# --------------------------------------------------------------------------- #
JS_NORMALIZE = r"""
// ── ۱) نرمال‌سازی پیام تلگرام ──────────────────────────────────────────────
const update = $json;
const msg = update.message || update.edited_message || {};
const chat = msg.chat || {};
const user = msg.from || {};
const text = msg.text || msg.caption || '';

// نوع مدیا (برای آرشیو)
let media = null;
for (const k of ['photo', 'video', 'voice', 'audio', 'document', 'sticker']) {
  if (msg[k]) { media = k; break; }
}

// آیا این پیام از یک ربات است؟ (جلوگیری از حلقه)
const fromBot = !!user.is_bot;

return [{
  json: {
    message_id: msg.message_id ?? null,
    chat_id: chat.id ?? null,
    chat_type: chat.type ?? null,
    chat_title: chat.title ?? chat.username ?? null,
    user_id: user.id ?? null,
    username: user.username ?? (user.first_name || 'unknown'),
    sender_name: [user.first_name, user.last_name].filter(Boolean).join(' ') || 'unknown',
    is_bot: fromBot,
    text,
    has_media: media !== null,
    media_type: media,
    reply_to_message_id: msg.reply_to_message?.message_id ?? null,
    date: msg.date ? new Date(msg.date * 1000).toISOString() : new Date().toISOString(),
  }
}];
"""

JS_ROUTE = r"""
// ── ۲) روتینگ: @ag01..@ag08 / /all / /daily / ذخیره ───────────────────────
const item = $input.first().json;
const text = item.text || '';
const path = $execution?.resumeFormUrl ? '' : '';   // (بی‌استفاده)

if (item.is_bot) return [{ json: { ...item, route: 'ignore' } }];

const mention = text.match(/@(ag0[1-8])\b/i);
const isAll = /^\s*\/all(@\w+)?\b/i.test(text);
const isDaily = /^\s*\/daily(@\w+)?\b/i.test(text);
const isHelp = /^\s*\/(start|help)(@\w+)?\b/i.test(text);

let route = 'ignore';
let agent = null;
if (mention) { route = 'single'; agent = mention[1].toUpperCase(); }
else if (isAll) route = 'all';
else if (isDaily) route = 'daily';
else if (isHelp) route = 'help';

// متن سؤال بدون منشن/دستور
const question = text
  .replace(/@(ag0[1-9])\b/gi, '')
  .replace(/^\s*\/(all|daily|help|start)(@\w+)?/i, '')
  .trim();

return [{ json: { ...item, route, agent, question } }];
"""

JS_MAP_AGENT = r"""
// ── ۳) نگاشت ایجنت منشن‌شده به شناسه/دیتابیس ──────────────────────────────
const item = $input.first().json;
const MAP = {
  AG01: { db: 'NOTION_DB_MARKET',   name: 'استراتژیست بازار' },
  AG02: { db: 'NOTION_DB_COPY',     name: 'روایت‌ساز و کپی‌رایتر' },
  AG03: { db: 'NOTION_DB_CONTENT',  name: 'کارگردان محتوا و موشن' },
  AG04: { db: 'NOTION_DB_DESIGN',   name: 'طراح سیستم بصری' },
  AG05: { db: 'NOTION_DB_WEB',      name: 'توسعه‌دهنده وب' },
  AG06: { db: 'NOTION_DB_SEO',      name: 'متخصص سئو و رشد' },
  AG07: { db: 'NOTION_DB_DATA',     name: 'تحلیل‌گر داده' },
  AG08: { db: 'NOTION_DB_CAMPAIGN', name: 'کمپین و فروش B2B' },
};
const meta = MAP[item.agent] || {};
return [{ json: { ...item, agent_name: meta.name || item.agent, agent_db_env: meta.db || null } }];
"""

JS_BUILD_PROMPT = r"""
// ── ۵) ساخت Context ترکیبی: System Prompt + Notion + تاریخچه گروه ──────────
const item = $input.first().json;
const agent = item.agent;

// پرامپت‌ها از گره «Load Prompt» می‌آیند (فایل n8n/prompts/AGxx.txt)
const systemPrompt = item.system_prompt || '';

// رکوردهای Notion (اگر گره Notion خطا داد یا خالی بود → آرایه خالی)
let notionRows = [];
try {
  notionRows = $('Notion Records').all().map(i => i.json).filter(r => r && Object.keys(r).length);
} catch (e) { notionRows = []; }

// تاریخچه ۳۰ پیام آخر (به ترتیب قدیمی → جدید)
let history = [];
try {
  history = $('Chat History').all().map(i => i.json).filter(r => r && r.text !== undefined);
} catch (e) { history = []; }
history.sort((a, b) => new Date(a.date) - new Date(b.date));

const fmt = (m) => {
  const d = new Date(m.date);
  const stamp = d.toISOString().slice(0, 16).replace('T', ' ');
  return `[${stamp} UTC] @${m.username || 'unknown'}: ${(m.text || '').replace(/\s+/g, ' ').slice(0, 500)}`;
};
const historyBlock = history.length ? history.map(fmt).join('\n') : 'تاریخچه‌ای در دست نیست.';

const notionBlock = notionRows.length
  ? notionRows.slice(0, 10).map((r, i) => {
      const { _id, ...rest } = r;
      return `${i + 1}. ` + Object.entries(rest)
        .filter(([, v]) => v !== null && v !== undefined && v !== '')
        .map(([k, v]) => `${k}=${Array.isArray(v) ? v.join(',') : v}`).join(' | ');
    }).join('\n')
  : 'هیچ رکورد فعالی یافت نشد → یعنی «داده‌ای در دست نیست»، نه صفر و نه تأیید.';

const userPrompt = `# Context عملیاتی — ${agent} (${item.agent_name})

## بخش ب — داده‌های Notion (حداکثر ۱۰ رکورد اخیر)
${notionBlock}

## بخش ج — تاریخچه چت گروه (آخرین ${history.length} پیام)
${historyBlock}

---

## درخواست کاربر
${item.question || '(بدون متن)'}

## دستور پاسخ
۱. فقط در نقش ${agent} پاسخ بده و از مرز اختیار خودت بیرون نزن.
۲. هر ادعا شاهد داشته باشد: [شاهد: ...] — ادعای بدون شاهد → ⚠️ نیازمند تأیید.
۳. هیچ ردیف/عددی را حدس نزن. خانه خالی ≠ صفر و ≠ تأیید.
۴. فقط ابزار رایگان پیشنهاد بده.
۵. پایان: «✅ اقدام بعدی» (حداکثر ۳ مورد) و در صورت لزوم «⚠️ نیازمند تأیید مدیر».
`;

return [{
  json: {
    ...item,
    system_prompt: systemPrompt,
    user_prompt: userPrompt,
    notion_count: notionRows.length,
    history_count: history.length,
  }
}];
"""

JS_SELF_CHECK = r"""
// ── ۷) کنترل کیفیت خروجی ایجنت (قبل از ارسال) ─────────────────────────────
const item = $input.first().json;
const choice = item.choices?.[0]?.message?.content ?? item.content ?? '';
let answer = String(choice).trim();

const problems = [];
if (!answer) problems.push('پاسخ خالی است');
if (!/شاهد|نیازمند تأیید/.test(answer)) problems.push('هیچ شاهد/برچسب تأییدی ندارد');

// هشدار (نه مسدودسازی): برچسب‌گذاری خودکار
let flags = '';
if (!/\[شاهد/.test(answer)) flags += '\n\n⚠️ <i>این پاسخ هیچ شاهد صریحی ندارد — نیازمند تأیید مدیر.</i>';
if (flags) answer += flags;

const MAX = 3500;
const chunks = [];
let rest = answer;
while (rest.length > MAX) {
  let cut = rest.lastIndexOf('\n', MAX);
  if (cut < MAX * 0.5) cut = MAX;
  chunks.push(rest.slice(0, cut));
  rest = rest.slice(cut).trim();
}
if (rest) chunks.push(rest);

return chunks.map((chunk, i) => ({
  json: {
    ...item,
    answer: chunk,
    part: i + 1,
    parts: chunks.length,
    quality_problems: problems,
  }
}));
"""

JS_TELEGRAM_FORMAT = r"""
// ── ۸) قالب‌بندی پیام تلگرام (HTML) ────────────────────────────────────────
const item = $input.first().json;
const escape = (s) => String(s)
  .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
  .replace(/\*\*(.+?)\*\*/g, '<b>$1</b>')
  .replace(/`([^`]+)`/g, '<code>$1</code>');

const head = item.part === 1
  ? `<b>${item.agent} — ${item.agent_name}</b>\n\n`
  : `<b>${item.agent}</b> (ادامه ${item.part}/${item.parts})\n\n`;

return [{ json: { ...item, telegram_text: head + escape(item.answer) } }];
"""


# --------------------------------------------------------------------------- #
#  ساخت ورک‌فلو
# --------------------------------------------------------------------------- #
def build_main_workflow(agents: list[dict[str, Any]]) -> dict[str, Any]:
    nodes: list[dict[str, Any]] = []

    # --- تریگر و آرشیو -------------------------------------------------------
    nodes.append(telegram_trigger("Telegram Trigger", [-1000, 0]))
    nodes.append(
        code_node("Normalize Message", JS_NORMALIZE, [-800, 0], "نرمال‌سازی پیام تلگرام")
    )
    nodes.append(
        mongo_node("Save Message", "insert", [-600, 0], notes="آرشیو کامل پیام‌ها (chat_history)")
    )
    nodes.append(code_node("Route", JS_ROUTE, [-400, 0], "منشن/دستور/ذخیره"))
    nodes.append(
        {
            "parameters": {
                "rules": {
                    "values": [
                        {"conditions": {"options": {"caseSensitive": True, "version": 2},
                                        "conditions": [{"leftValue": "={{ $json.route }}", "rightValue": "single",
                                                        "operator": {"type": "string", "operation": "equals"}}],
                                        "combinator": "and"},
                         "outputKey": "single"},
                        {"conditions": {"options": {"caseSensitive": True, "version": 2},
                                        "conditions": [{"leftValue": "={{ $json.route }}", "rightValue": "all",
                                                        "operator": {"type": "string", "operation": "equals"}}],
                                        "combinator": "and"},
                         "outputKey": "all"},
                        {"conditions": {"options": {"caseSensitive": True, "version": 2},
                                        "conditions": [{"leftValue": "={{ $json.route }}", "rightValue": "daily",
                                                        "operator": {"type": "string", "operation": "equals"}}],
                                        "combinator": "and"},
                         "outputKey": "daily"},
                        {"conditions": {"options": {"caseSensitive": True, "version": 2},
                                        "conditions": [{"leftValue": "={{ $json.route }}", "rightValue": "help",
                                                        "operator": {"type": "string", "operation": "equals"}}],
                                        "combinator": "and"},
                         "outputKey": "help"},
                    ]
                },
                "options": {"fallbackOutput": "extra", "renameFallbackOutput": "ignore"},
            },
            "id": _id("Switch Route"),
            "name": "Switch Route",
            "type": "n8n-nodes-base.switch",
            "typeVersion": 3,
            "position": [-200, 0],
            "notes": "single / all / daily / help / ignore",
            "notesInFlow": True,
        }
    )

    # --- مسیر single --------------------------------------------------------
    nodes.append(code_node("Map Agent", JS_MAP_AGENT, [0, -260]))
    nodes.append(
        mongo_node(
            "Chat History",
            "aggregate",
            [200, -260],
            query=json.dumps(
                [
                    {"$match": {"chat_id": "={{ $json.chat_id }}", "is_bot": False}},
                    {"$sort": {"date": -1}},
                    {"$limit": 30},
                ],
                ensure_ascii=False,
            ),
            notes="آخرین ۳۰ پیام گروه",
        )
    )
    nodes.append(
        {
            "parameters": {
                "resource": "databasePage",
                "operation": "getAll",
                "databaseId": {"__rl": True, "value": "={{ $env." + "NOTION_DB_" + "}}",
                               "mode": "id"},
                "returnAll": False,
                "limit": 10,
                "filterType": "manual",
                "matchType": "anyFilter",
                "filters": {"conditions": []},
                "options": {},
            },
            "id": _id("Notion Records"),
            "name": "Notion Records",
            "type": "n8n-nodes-base.notion",
            "typeVersion": 2.2,
            "position": [200, -80],
            "notes": "دیتابیس مرتبط ایجنت — شناسه را دستی جایگزین کنید",
            "notesInFlow": True,
            "credentials": {"notionApi": {"id": "REPLACE_NOTION_CRED_ID", "name": "Notion API"}},
        }
    )
    nodes.append(
        {
            "parameters": {
                "mode": "runOnceForAllItems",
                "language": "javaScript",
                "jsCode": JS_LOAD_PROMPT,
            },
            "id": _id("Load Prompt"),
            "name": "Load Prompt",
            "type": "n8n-nodes-base.code",
            "typeVersion": 2,
            "position": [200, -440],
            "notes": "خواندن فایل n8n/prompts/AGxx.txt بر اساس $json.agent",
            "notesInFlow": True,
        }
    )
    nodes.append(code_node("Build Prompt", JS_BUILD_PROMPT, [420, -260]))
    nodes.append(
        http_node(
            "OpenAI Chat",
            [640, -260],
            "https://api.openai.com/v1/chat/completions",
            {
                "model": "gpt-4o",
                "temperature": 0.4,
                "max_tokens": 2000,
                "messages": [
                    {"role": "system", "content": "={{ $json.system_prompt }}"},
                    {"role": "user", "content": "={{ $json.user_prompt }}"},
                ],
            },
            {
                "Authorization": "=Bearer {{ $env.OPENAI_API_KEY }}",
                "Content-Type": "application/json",
            },
        )
    )
    nodes.append(code_node("Self Check", JS_SELF_CHECK, [860, -260], "برچسب شاهد + شکستن پیام"))
    nodes.append(code_node("Format Telegram", JS_TELEGRAM_FORMAT, [1080, -260]))
    nodes.append(telegram_send("Send Answer", [1300, -260], "={{ $json.telegram_text }}"))

    # --- مسیر all -----------------------------------------------------------
    nodes.append(
        code_node(
            "Fan Out Agents",
            r"""
// ── /all : یک آیتم برای هر ایجنت فعال (به‌جز AG09) ────────────────────────
const item = $input.first().json;
const ACTIVE = ['AG01','AG02','AG03','AG04','AG05','AG06','AG07','AG08'];
return ACTIVE.map((agent) => ({ json: { ...item, agent, route: 'single',
  agent_name: agent } }));
""",
            [0, 60],
            "۸ ایجنت فعال → ۸ آیتم",
        )
    )
    nodes.append(
        {
            "parameters": {
                "batchSize": 1,
                "options": {"reset": False},
            },
            "id": _id("Loop Agents"),
            "name": "Loop Agents",
            "type": "n8n-nodes-base.splitInBatches",
            "typeVersion": 3,
            "position": [200, 60],
            "notes": "اجرای ترتیبی برای رعایت محدودیت نرخ تلگرام",
            "notesInFlow": True,
        }
    )

    # --- مسیر daily ---------------------------------------------------------
    nodes.append(
        code_node(
            "Daily Summary",
            r"""
// ── /daily : خلاصه وضعیت روز از Notion (بدون LLM) ─────────────────────────
const item = $input.first().json;
const rows = [];
try { rows.push(...$('Notion Records').all().map(i => i.json)); } catch (e) {}
let logRows = [];
try { logRows = $('Daily Log').all().map(i => i.json); } catch (e) {}

const lines = [`📊 <b>خلاصه وضعیت روز</b>`, ''];
lines.push(`رکوردهای فعال دیتابیس مرتبط: <b>${rows.length}</b>`);
rows.slice(0, 10).forEach((r, i) => {
  const title = r.Name || r['نام'] || r.Title || r['عنوان'] || '(بدون عنوان)';
  lines.push(`${i + 1}. ${title}`);
});
if (logRows.length) {
  lines.push('', `<b>ثبت‌های اخیر daily_log:</b>`);
  logRows.slice(0, 8).forEach(r => lines.push(`• ${r.Agent || '—'} | ${r.Mission || '—'}`));
}
if (!rows.length && !logRows.length) {
  lines.push('', '⚠️ داده‌ای در دست نیست (نه صفر، نه تأیید).');
}
return [{ json: { ...item, telegram_text: lines.join('\n') } }];
""",
            [0, 200],
        )
    )
    nodes.append(telegram_send("Send Daily", [220, 200], "={{ $json.telegram_text }}"))

    # --- مسیر help ----------------------------------------------------------
    nodes.append(
        code_node(
            "Help Text",
            r"""
const help = `<b>راهنمای ربات ایجنت‌ها</b>

@ag01 … @ag08 — منشن کن تا فقط همان ایجنت پاسخ دهد
/all سؤال… — همه ایجنت‌های فعال (هر کدام پیام جدا)
/daily — خلاصه وضعیت روز از Notion
/help — همین راهنما

پیام‌های بدون منشن فقط ذخیره می‌شوند.`;
return [{ json: { ...$input.first().json, telegram_text: help } }];
""",
            [0, 340],
        )
    )
    nodes.append(telegram_send("Send Help", [220, 340], "={{ $json.telegram_text }}"))

    # --- اتصال‌ها -----------------------------------------------------------
    def connect(a: str, b: str, output_index: int = 0, output_name: str = "main") -> None:
        connections.setdefault(a, {"main": []})
        while len(connections[a]["main"]) <= output_index:
            connections[a]["main"].append([])
        connections[a]["main"][output_index].append({"node": b, "type": "main", "index": 0})

    connections: dict[str, Any] = {}

    connect("Telegram Trigger", "Normalize Message")
    connect("Normalize Message", "Save Message")
    connect("Save Message", "Route")
    connect("Route", "Switch Route")

    # Switch outputs: single(0) all(1) daily(2) help(3) fallback(4)
    connect("Switch Route", "Map Agent", 0)
    connect("Switch Route", "Fan Out Agents", 1)
    connect("Switch Route", "Daily Summary", 2)
    connect("Switch Route", "Help Text", 3)

    # single path
    connect("Map Agent", "Load Prompt")
    connect("Map Agent", "Chat History")
    connect("Map Agent", "Notion Records")
    connect("Load Prompt", "Build Prompt")
    connect("Chat History", "Build Prompt")
    connect("Notion Records", "Build Prompt")
    connect("Build Prompt", "OpenAI Chat")
    connect("OpenAI Chat", "Self Check")
    connect("Self Check", "Format Telegram")
    connect("Format Telegram", "Send Answer")

    # all path → همان مسیر single از طریق Loop
    connect("Fan Out Agents", "Loop Agents")
    connect("Loop Agents", "Map Agent", 0)

    connect("Daily Summary", "Send Daily")
    connect("Help Text", "Send Help")

    return {
        "name": "Telegram 9-Agent Router (n8n)",
        "nodes": nodes,
        "connections": connections,
        "active": False,
        "settings": {"executionOrder": "v1", "saveManualExecutions": True,
                     "callerPolicy": "workflowsFromSameOwner"},
        "staticData": None,
        "pinData": {},
        "meta": {"templateCredsSetupCompleted": False},
        "tags": [{"name": "telegram"}, {"name": "agents"}],
    }


JS_LOAD_PROMPT = r"""
// ── ۴) بارگذاری System Prompt ایجنت از فایل ───────────────────────────────
// مسیر پوشه پرامپت‌ها روی سرور ویندوز (در n8n > Settings > Environment Variables):
//   N8N_AGENTS_PROMPTS_DIR=C:\n8n\prompts
const fs = require('fs');
const path = require('path');

const item = $input.first().json;
const agent = item.agent;

const dir = process.env.N8N_AGENTS_PROMPTS_DIR || $env.N8N_AGENTS_PROMPTS_DIR || '';
const candidates = [
  path.join(dir, `${agent}.txt`),
  path.join(process.env.USERPROFILE || '.', 'n8n', 'prompts', `${agent}.txt`),
  path.join('.', 'n8n', 'prompts', `${agent}.txt`),
];

let system_prompt = '';
let loaded_from = null;
for (const c of candidates) {
  try {
    if (c && fs.existsSync(c)) {
      system_prompt = fs.readFileSync(c, 'utf8');
      loaded_from = c;
      break;
    }
  } catch (e) { /* ignore */ }
}

if (!system_prompt) {
  system_prompt = `تو ${agent} هستی. بدون شاهد ادعا نکن و هر ادعا را با [شاهد: ...] یا ⚠️ نیازمند تأیید علامت بزن.`;
}

return [{ json: { ...item, system_prompt, prompt_file: loaded_from } }];
"""


def build_mongo_setup_workflow() -> dict[str, Any]:
    return {
        "name": "00 - MongoDB setup (indexes)",
        "nodes": [
            {
                "parameters": {},
                "id": _id("Manual Trigger"),
                "name": "Manual Trigger",
                "type": "n8n-nodes-base.manualTrigger",
                "typeVersion": 1,
                "position": [-200, 0],
            },
            {
                "parameters": {
                    "operation": "createIndex",
                    "collection": "chat_history",
                    "keys": "chat_id:1,date:-1",
                    "options": {},
                },
                "id": _id("Index chat_id+date"),
                "name": "Index chat_id+date",
                "type": "n8n-nodes-base.mongoDb",
                "typeVersion": 1,
                "position": [100, 0],
                "credentials": {
                    "mongoDb": {"id": "REPLACE_MONGO_CRED_ID", "name": "MongoDB - tg_agents"}
                },
            },
            {
                "parameters": {
                    "operation": "createIndex",
                    "collection": "chat_history",
                    "keys": "chat_id:1,message_id:1",
                    "options": {"unique": True},
                },
                "id": _id("Index unique message"),
                "name": "Index unique message_id",
                "type": "n8n-nodes-base.mongoDb",
                "typeVersion": 1,
                "position": [320, 0],
                "credentials": {
                    "mongoDb": {"id": "REPLACE_MONGO_CRED_ID", "name": "MongoDB - tg_agents"}
                },
            },
        ],
        "connections": {
            "Manual Trigger": {"main": [[{"node": "Index chat_id+date", "type": "main", "index": 0}]]},
            "Index chat_id+date": {"main": [[{"node": "Index unique message_id", "type": "main", "index": 0}]]},
        },
        "settings": {"executionOrder": "v1"},
    }


def render_prompt_file(agent: dict[str, Any], common: str) -> str:
    """پرامپت کامل = نقش + قواعد مشترک + قرارداد ورودی/خروجی."""
    body = [
        f"# {agent['id']} — {agent['name']}",
        f"# نقش: {agent.get('role','')}",
        f"# مرز اختیار: {agent.get('authority','')}",
        "",
        agent["system_prompt"].strip(),
        "",
        "=" * 60,
        common.strip(),
        "",
        "=" * 60,
        "## قرارداد ورودی (ورک‌فلوی n8n)",
        "پیام کاربر شامل این بخش‌هاست: «بخش ب — داده‌های Notion» و «بخش ج — تاریخچه چت گروه».",
        "اگر هر بخش خالی بود، همان‌جا صریح بنویس «داده‌ای در دست نیست».",
        "",
        "## قرارداد خروجی",
        "- خروجی HTML ساده تلگرام (بدون بلوک کد Markdown).",
        "- هر ادعا: `[شاهد: ...]` — ادعای بدون شاهد: `⚠️ نیازمند تأیید`.",
        "- پایان: «✅ اقدام بعدی» و در صورت نیاز «⚠️ نیازمند تأیید مدیر».",
        "- حداکثر ~۳۵۰۰ کاراکتر (ورک‌فلو خودش پیام را به چند تکه می‌شکند).",
        "",
    ]
    return "\n".join(body)


def main() -> None:
    data = yaml.safe_load((BASE / "config" / "agents.yaml").read_text(encoding="utf-8"))
    agents = data.get("agents", [])
    common = data.get("common_rules", "")

    PROMPT_DIR.mkdir(parents=True, exist_ok=True)
    WORKFLOW_DIR.mkdir(parents=True, exist_ok=True)

    for agent in agents:
        target = PROMPT_DIR / f"{agent['id']}.txt"
        target.write_text(render_prompt_file(agent, common), encoding="utf-8")
    (PROMPT_DIR / "COMMON.txt").write_text(common.strip() + "\n", encoding="utf-8")

    workflow = build_main_workflow(agents)
    (WORKFLOW_DIR / "01-telegram-agents-router.json").write_text(
        json.dumps(workflow, ensure_ascii=False, indent=2), encoding="utf-8"
    )
    (WORKFLOW_DIR / "00-mongo-setup.json").write_text(
        json.dumps(build_mongo_setup_workflow(), ensure_ascii=False, indent=2), encoding="utf-8"
    )
    (WORKFLOW_DIR / "02-telegram-polling.json").write_text(
        json.dumps(build_polling_workflow(agents), ensure_ascii=False, indent=2), encoding="utf-8"
    )

    print(f"✅ {len(agents)} پرامپت ساخته شد → {PROMPT_DIR}")
    print(f"✅ ورک‌فلوها → {WORKFLOW_DIR}")
    for path in sorted(WORKFLOW_DIR.glob("*.json")):
        print(f"   • {path.name} ({path.stat().st_size // 1024} KB)")



JS_POLL_FETCH = r"""
// ── polling: خواندن پیام‌های جدید از Telegram getUpdates ──────────────────────
// offset در staticData ذخیره می‌شود تا بین اجراها گم نشود.
const botToken = $env.TELEGRAM_BOT_TOKEN || process.env.TELEGRAM_BOT_TOKEN || '';
if (!botToken) {
  throw new Error('TELEGRAM_BOT_TOKEN تنظیم نشده است. آن را در متغیرهای محیطی n8n بگذارید.');
}

const staticData = $getWorkflowStaticData('global');
const offset = staticData.tgOffset || 0;

// در n8n Code node، این helper برای درخواست‌های async در دسترس است
const resp = await this.helpers.httpRequest({
  method: 'GET',
  url: `https://api.telegram.org/bot${botToken}/getUpdates`,
  qs: { offset, timeout: 0, allowed_updates: JSON.stringify(['message', 'edited_message']) },
  json: true,
});

const updates = (resp.result || []);
if (updates.length === 0) {
  return [{ json: { _empty: true, route: 'ignore' } }];
}

staticData.tgOffset = updates[updates.length - 1].update_id + 1;

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


def build_polling_workflow(agents: list[dict[str, Any]]) -> dict[str, Any]:
    """نسخهٔ polling ورک‌فلوی اصلی: بدون نیاز به webhook و دامنهٔ HTTPS."""
    nodes: list[dict[str, Any]] = []
    connections: dict[str, Any] = {}

    def connect(src: str, dst: str, idx: int = 0) -> None:
        connections.setdefault(src, {"main": []})
        main = connections[src]["main"]
        while len(main) <= idx:
            main.append([])
        main[idx].append({"node": dst, "type": "main", "index": 0})

    # تریگر زمان‌بندی‌شده (هر ۵ ثانیه) — polling
    nodes.append({
        "parameters": {
            "rule": {"interval": [{"field": "seconds", "secondsInterval": 5}]},
        },
        "id": _id("Poll Trigger"),
        "name": "Poll Trigger",
        "type": "n8n-nodes-base.scheduleTrigger",
        "typeVersion": 1.2,
        "position": [-1200, 0],
        "notes": "هر ۵ ثانیه getUpdates — جایگزین webhook",
        "notesInFlow": True,
    })

    nodes.append(code_node(
        "Telegram getUpdates", JS_POLL_FETCH, [-1000, 0],
        "polling با offset ذخیره‌شده در staticData"
    ))

    nodes.append(code_node("Normalize Message", JS_NORMALIZE, [-800, 0], "نرمال‌سازی پیام"))
    nodes.append(mongo_node("Save Message", "insert", [-600, 0], notes="آرشیو chat_history"))

    # فیلتر پیام‌های خالی/قدیمی و ربات‌ها
    nodes.append({
        "parameters": {
            "conditions": {
                "options": {"caseSensitive": True, "version": 2},
                "conditions": [
                    {"leftValue": "={{ $json.chat_id }}", "rightValue": "",
                     "operator": {"type": "number", "operation": "exists", "singleValue": True}},
                    {"leftValue": "={{ $json.is_bot }}", "rightValue": False,
                     "operator": {"type": "boolean", "operation": "equals"}},
                ],
                "combinator": "and",
            },
            "options": {},
        },
        "id": _id("Only Real User Messages"),
        "name": "Only Real User Messages",
        "type": "n8n-nodes-base.filter",
        "typeVersion": 2.2,
        "position": [-400, 0],
        "notes": "پیام ربات‌ها و پیام‌های بدون chat_id رد می‌شوند",
    })

    nodes.append(code_node("Route", JS_ROUTE, [-200, 0], "منشن/دستور/ذخیره"))
    # از این‌جا به بعد همان گره‌های ورک‌فلوی اصلی است
    main_wf = build_main_workflow(agents)
    skip = {"Telegram Trigger", "Normalize Message", "Save Message", "Route"}
    reused = [n for n in main_wf["nodes"] if n["name"] not in skip]
    for n in reused:
        nodes.append(n)

    connect("Poll Trigger", "Telegram getUpdates")
    connect("Telegram getUpdates", "Normalize Message")
    connect("Normalize Message", "Save Message")
    connect("Save Message", "Only Real User Messages")
    connect("Only Real User Messages", "Route")
    connect("Route", "Switch Route")

    connect("Switch Route", "Map Agent", 0)
    connect("Switch Route", "Fan Out Agents", 1)
    connect("Switch Route", "Daily Summary", 2)
    connect("Switch Route", "Help Text", 3)

    connect("Map Agent", "Load Prompt")
    connect("Map Agent", "Chat History")
    connect("Map Agent", "Notion Records")
    connect("Load Prompt", "Build Prompt")
    connect("Chat History", "Build Prompt")
    connect("Notion Records", "Build Prompt")
    connect("Build Prompt", "OpenAI Chat")
    connect("OpenAI Chat", "Self Check")
    connect("Self Check", "Format Telegram")
    connect("Format Telegram", "Send Answer")

    connect("Fan Out Agents", "Loop Agents")
    connect("Loop Agents", "Map Agent", 0)

    connect("Daily Summary", "Send Daily")
    connect("Help Text", "Send Help")

    return {
        "name": "Telegram 9-Agent Router — POLLING (no HTTPS needed)",
        "nodes": nodes,
        "connections": connections,
        "active": False,
        "settings": {"executionOrder": "v1", "saveManualExecutions": True,
                     "callerPolicy": "workflowsFromSameOwner"},
        "staticData": None,
        "pinData": {},
        "meta": {"templateCredsSetupCompleted": False},
        "tags": [{"name": "telegram"}, {"name": "agents"}, {"name": "polling"}],
    }

if __name__ == "__main__":
    main()


# =========================================================================== #
#  ورک‌فلوی Polling — برای سرورهای ویندوزی بدون دامنهٔ HTTPS
# --------------------------------------------------------------------------- #
#  تلگرام برای webhook فقط HTTPS روی پورت ۴۴۳ را قبول می‌کند. روی ویندوز سرور
#  بدون دامنه/SSL، تنها راه کار کردن n8n با تلگرام، polling است:
#     Schedule Trigger → getUpdates → Normalize → (استفادهٔ مجدد از مسیر اصلی)
# =========================================================================== #

