"""
BizNode Support Knowledge Base Seeder
======================================
Seeds support articles into a dedicated Qdrant collection so users can
search for help after installation via @biznode_bot or the dashboard.

Collection : biznode_support
Tags       : "support", "error", "setup", "faq" (per article)

Usage:
    python scripts/seed_support_kb.py

    # Dry-run (print articles without embedding):
    python scripts/seed_support_kb.py --dry-run

    # Reset collection and re-seed:
    python scripts/seed_support_kb.py --reset

To add your own articles, edit the SUPPORT_ARTICLES list below.
Each article is a dict with keys:
    title    - short title
    content  - full explanation / answer
    tags     - list of tags (always include "support")
    keywords - list of search keywords
"""

import os
import sys
import json
import uuid
import argparse

# ── Load .env ────────────────────────────────────────────────────────────────

def _load_env():
    env_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".env")
    cfg = {}
    if os.path.exists(env_path):
        with open(env_path, encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if "=" in line and not line.startswith("#"):
                    k, v = line.split("=", 1)
                    cfg[k.strip()] = v.strip()
    return cfg

_ENV = _load_env()

OLLAMA_EMBED_URL = _ENV.get("OLLAMA_EMBED_URL", "http://localhost:11434/api/embeddings")
EMBEDDING_MODEL  = _ENV.get("EMBEDDING_MODEL",  "nomic-embed-text")
QDRANT_HOST      = _ENV.get("QDRANT_HOST",       "localhost")
QDRANT_PORT      = _ENV.get("QDRANT_PORT",       "6333")
QDRANT_URL       = f"http://{QDRANT_HOST}:{QDRANT_PORT}"
COLLECTION       = "biznode_support"

# ── Support Articles ─────────────────────────────────────────────────────────
# Edit this list to add your own support content.
# The script embeds each article and stores it in Qdrant tagged "support".

SUPPORT_ARTICLES = [

    # ── Installation Errors ──────────────────────────────────────────────────

    {
        "title": "Error: No module named 'langgraph'",
        "content": (
            "This error means the langgraph Python package is not installed in your environment. "
            "Fix: Run the following command in your terminal:\n\n"
            "    python -m pip install --user -r requirements.txt\n\n"
            "This installs all required packages including langgraph, langchain-core, qdrant-client, "
            "and others. After installation, restart the dashboard:\n\n"
            "    python run_dashboard.py\n\n"
            "From BizNode v1.1, the dashboard auto-installs missing packages on startup."
        ),
        "tags": ["support", "error", "installation", "python"],
        "keywords": ["langgraph", "module not found", "import error", "pip install"],
    },

    {
        "title": "Error: No module named 'qdrant_client'",
        "content": (
            "The qdrant-client Python package is not installed. "
            "Fix: Run:\n\n"
            "    python -m pip install --user qdrant-client\n\n"
            "Or install everything at once:\n\n"
            "    python -m pip install --user -r requirements.txt"
        ),
        "tags": ["support", "error", "installation", "python"],
        "keywords": ["qdrant_client", "qdrant", "module not found", "pip"],
    },

    {
        "title": "Error: 404 Not Found for url: http://localhost:11434/api/generate",
        "content": (
            "This means Ollama is running but the AI model (e.g. qwen3.5:4b) has not been pulled yet. "
            "Fix: Pull the model inside the Docker container:\n\n"
            "    docker compose exec ollama ollama pull qwen3.5:4b\n\n"
            "This downloads approximately 4-5 GB. Run it once — the model persists in ./memory/ollama/. "
            "Also pull the embedding model:\n\n"
            "    docker compose exec ollama ollama pull nomic-embed-text"
        ),
        "tags": ["support", "error", "ollama", "model"],
        "keywords": ["404", "ollama", "api/generate", "model not found", "pull model"],
    },

    {
        "title": "Telegram bot not responding to messages",
        "content": (
            "If the bot does not reply to Telegram messages, check these steps:\n\n"
            "1. Check the bot container is running:\n"
            "       docker compose ps\n\n"
            "2. Check container logs for errors:\n"
            "       docker compose logs bot --tail 50\n\n"
            "3. Most common cause: TELEGRAM_BOT_TOKEN is empty in .env\n"
            "   Fix: Open .env and set:\n"
            "       TELEGRAM_BOT_TOKEN=your_token_here\n"
            "   Then restart:\n"
            "       docker compose up -d --force-recreate bot\n\n"
            "4. If you see 'CRITICAL: BOT_TOKEN is not set' in logs, the token is missing or wrong."
        ),
        "tags": ["support", "error", "telegram", "bot"],
        "keywords": ["bot not responding", "telegram", "BOT_TOKEN", "not set", "restart bot"],
    },

    {
        "title": "Docker error: project name must not be empty",
        "content": (
            "This error occurs when running 'docker compose' from a drive root (e.g. E:\\) "
            "where Docker cannot determine a project name. "
            "Fix: Always run docker compose from inside the project directory:\n\n"
            "    cd C:\\Users\\YourName\\BizNode\n"
            "    docker compose up -d\n\n"
            "Alternatively, the docker-compose.yml includes 'name: biznode' to prevent this. "
            "If the error persists, specify the project name explicitly:\n\n"
            "    docker compose -p biznode up -d"
        ),
        "tags": ["support", "error", "docker"],
        "keywords": ["project name", "empty", "docker compose", "drive root"],
    },

    {
        "title": "Docker containers stuck as 'unhealthy'",
        "content": (
            "The qdrant and ollama Docker images do not include curl, so healthcheck-based "
            "dependency conditions will always fail. "
            "Fix: The docker-compose.yml has been updated to use simple depends_on without "
            "health conditions. If you see unhealthy containers, remove healthcheck blocks "
            "from your docker-compose.yml:\n\n"
            "Remove any 'healthcheck:' and 'condition: service_healthy' blocks. "
            "Use simple depends_on:\n\n"
            "    depends_on:\n"
            "      - qdrant\n"
            "      - ollama"
        ),
        "tags": ["support", "error", "docker", "healthcheck"],
        "keywords": ["unhealthy", "healthcheck", "depends_on", "service_healthy", "curl"],
    },

    {
        "title": "pip install fails with 'Access is denied'",
        "content": (
            "This happens on Windows when pip cannot write to the system Python directory. "
            "Fix: Use the --user flag to install to your user profile instead:\n\n"
            "    python -m pip install --user -r requirements.txt\n\n"
            "Or run PowerShell as Administrator and try again without --user. "
            "Using 'python -m pip' instead of just 'pip' also helps resolve PATH issues."
        ),
        "tags": ["support", "error", "installation", "windows"],
        "keywords": ["access denied", "pip", "install", "windows", "administrator"],
    },

    # ── Setup & Configuration ────────────────────────────────────────────────

    {
        "title": "How to get a Telegram Bot Token",
        "content": (
            "To create a Telegram bot and get its token:\n\n"
            "1. Open Telegram and search for @BotFather\n"
            "2. Send: /newbot\n"
            "3. Follow the prompts — give your bot a name and username\n"
            "4. BotFather will send you a token like: 123456789:ABCdef...\n"
            "5. Copy this token and paste it into the installer Config page or "
            "   the dashboard Setup tab under 'Telegram Bot Token'\n\n"
            "To get your Owner Telegram ID:\n"
            "1. Search for @userinfobot on Telegram\n"
            "2. Send /start — it replies with your numeric user ID\n"
            "3. Paste this number as 'Owner Telegram ID' in the config"
        ),
        "tags": ["support", "setup", "telegram", "faq"],
        "keywords": ["telegram token", "bot token", "BotFather", "owner ID", "userinfobot"],
    },

    {
        "title": "How to configure Gmail for SMTP email",
        "content": (
            "To send emails via Gmail, use an App Password (not your Gmail password):\n\n"
            "1. Go to myaccount.google.com → Security\n"
            "2. Enable 2-Step Verification\n"
            "3. Go to App Passwords → Create a new app password for 'Mail'\n"
            "4. Copy the 16-character password\n\n"
            "Dashboard Setup settings:\n"
            "    SMTP Host: smtp.gmail.com\n"
            "    SMTP Port: 587\n"
            "    SMTP User: your.email@gmail.com\n"
            "    SMTP Password: (the 16-char App Password)\n"
            "    Agent Email: your.email@gmail.com"
        ),
        "tags": ["support", "setup", "email", "gmail", "faq"],
        "keywords": ["gmail", "smtp", "email", "app password", "587"],
    },

    {
        "title": "How to set up the Business Identity for better AI responses",
        "content": (
            "To make your bot respond in context of your business:\n\n"
            "1. Open the dashboard at http://localhost:7777\n"
            "2. Go to Setup tab → scroll to Business Identity section\n"
            "3. Fill in: Business Name, AI Persona Name, Business Type, "
            "   Description, Services, Communication Tone, and Greeting Message\n"
            "4. Click 'Save Identity' — this updates instruction.md with your business context\n"
            "5. Click 'Seed Knowledge Base' — embeds your business info into Qdrant "
            "   so the AI can answer questions about your business\n\n"
            "After this, /start in Telegram will show a personalised greeting instead of "
            "a generic command list."
        ),
        "tags": ["support", "setup", "business", "faq"],
        "keywords": ["business identity", "persona", "greeting", "knowledge base", "seed"],
    },

    {
        "title": "How to pull Ollama models",
        "content": (
            "Ollama models must be pulled once before the AI can respond. "
            "If you installed using the installer, this is done automatically for local deployments. "
            "For USB/manual deployments, pull manually:\n\n"
            "    docker compose exec ollama ollama pull qwen3.5:4b\n"
            "    docker compose exec ollama ollama pull nomic-embed-text\n\n"
            "qwen3.5:4b is the main LLM (~4.5 GB). nomic-embed-text is the embedding model (~500 MB). "
            "Models are stored in ./memory/ollama/ and persist across restarts. "
            "To list installed models:\n\n"
            "    docker compose exec ollama ollama list"
        ),
        "tags": ["support", "setup", "ollama", "model", "faq"],
        "keywords": ["ollama", "pull model", "qwen3.5:4b", "nomic-embed-text", "download model"],
    },

    # ── Dashboard & Usage ────────────────────────────────────────────────────

    {
        "title": "Dashboard shows 'Not configured' warning",
        "content": (
            "BizNode requires at minimum a Telegram Bot Token and Owner Telegram ID. "
            "Fix:\n\n"
            "1. Open http://localhost:7777\n"
            "2. Go to Setup tab\n"
            "3. Enter your Telegram Bot Token and Owner Telegram ID\n"
            "4. Click Save Configuration\n\n"
            "The warning banner disappears once these two fields are set. "
            "Other fields (email, LLM model, etc.) are optional but recommended."
        ),
        "tags": ["support", "dashboard", "setup"],
        "keywords": ["not configured", "warning", "setup", "bot token", "owner ID"],
    },

    {
        "title": "Chat in dashboard returns an error",
        "content": (
            "Common causes of chat errors in the dashboard:\n\n"
            "1. 'No module named langgraph' — run: python -m pip install --user -r requirements.txt\n"
            "2. '404 from Ollama' — pull the model: docker compose exec ollama ollama pull qwen3.5:4b\n"
            "3. 'Connection refused' — Ollama or Qdrant container is not running: docker compose up -d\n"
            "4. Slow/timeout — the LLM is loading for the first time; wait 30 seconds and retry\n\n"
            "Check all containers are running:\n"
            "    docker compose ps"
        ),
        "tags": ["support", "dashboard", "chat", "error"],
        "keywords": ["chat error", "dashboard chat", "langgraph", "404", "connection refused"],
    },

    {
        "title": "How to view bot and container logs",
        "content": (
            "To debug issues, view container logs:\n\n"
            "View bot logs (last 50 lines):\n"
            "    docker compose logs bot --tail 50\n\n"
            "Follow logs in real time:\n"
            "    docker compose logs bot -f\n\n"
            "View Ollama logs:\n"
            "    docker compose logs ollama --tail 30\n\n"
            "View Qdrant logs:\n"
            "    docker compose logs qdrant --tail 30\n\n"
            "Check all container statuses:\n"
            "    docker compose ps"
        ),
        "tags": ["support", "debugging", "logs", "faq"],
        "keywords": ["logs", "docker logs", "debug", "container status", "docker ps"],
    },

    # ── Owner Menu & Commands ─────────────────────────────────────────────────

    {
        "title": "BizNode owner menu and bot commands",
        "content": (
            "The owner gets a full categorized menu in Telegram with 13 buttons:\n\n"
            "- My Profile: business profile, masked emails, stats\n"
            "- Recent Leads: real-time lead count and list\n"
            "- Daily Report: queries, users, leads, verified count\n"
            "- Recent Queries: last 10 customer questions\n"
            "- Server Status: Ollama, Qdrant, Dashboard health\n"
            "- Services & Pricing: list of services with prices\n"
            "- License Purchases: all purchase records\n"
            "- Transactions: transaction history\n"
            "- Affiliate Links: manage affiliate/referral links\n"
            "- Send Email: compose and send email via SMTP\n"
            "- Knowledge Base: search support articles\n"
            "- Dashboard: opens web dashboard at port 7777\n"
            "- Customer Menu Preview: see what customers see\n\n"
            "Text commands also work: 'my profile', 'show leads', 'server status', "
            "'daily report', 'recent queries', 'send email to X subject Y body Z', "
            "'block user 12345', 'unblock user 12345'.\n\n"
            "Email and phone updates require OTP verification for security."
        ),
        "tags": ["support", "owner", "menu", "commands", "faq"],
        "keywords": ["owner menu", "bot commands", "profile", "leads", "report", "status", "send email"],
    },

    # ── Tier System ───────────────────────────────────────────────────────────

    {
        "title": "BizNode Basic vs Pro tier features",
        "content": (
            "BizNode has two license tiers:\n\n"
            "**Basic License — $200 USD or 200 BZeUSD**\n"
            "- 1 Telegram bot\n"
            "- AI chatbot with business knowledge\n"
            "- Customer lead capture & CRM\n"
            "- Email automation (SMTP)\n"
            "- Knowledge base (Qdrant RAG)\n"
            "- Dashboard with 170+ API endpoints\n"
            "- Workflow engine\n"
            "- Daily digest reports\n"
            "- License key: BZN-XXXXX-XXXXX-XXXXX (server-validated)\n\n"
            "**Pro License — $499 USD or 499 BZeUSD**\n"
            "Everything in Basic PLUS:\n"
            "- Up to 5 Telegram bots\n"
            "- USB hardware-bound (Ed25519 signed)\n"
            "- BizChannel marketplace\n"
            "- AI agent employment services\n"
            "- Agent performance monitoring\n"
            "- Stripe & crypto payments\n"
            "- Affiliate & customer engagement\n"
            "- Cloud backup (Google Drive)\n"
            "- Node network monitoring\n"
            "- API service access\n"
            "- Priority technical support\n\n"
            "Trial: 10-day free trial with Basic features (1 bot)."
        ),
        "tags": ["support", "pricing", "tier", "license", "faq"],
        "keywords": ["basic", "pro", "tier", "features", "price", "200", "499", "license", "trial"],
    },

    # ── BizChannel Marketplace ────────────────────────────────────────────────

    {
        "title": "BizChannel marketplace (Pro feature)",
        "content": (
            "BizChannel is an event-driven marketplace included in the Pro tier.\n\n"
            "Features:\n"
            "- Discovery: Telegram scanner finds relevant business channels\n"
            "- AI verification: fraud detection and reach scoring\n"
            "- Escrow: secure payments between buyers and sellers\n"
            "- Quoting: automated price quoting for services\n"
            "- SEO: AI-generated marketing content\n"
            "- Event system: publisher/consumer architecture for real-time updates\n\n"
            "BizChannel runs as a separate FastAPI service within the Pro package. "
            "It connects to the main BizNode database and uses the same Qdrant and Ollama services."
        ),
        "tags": ["support", "pro", "bizchannel", "marketplace"],
        "keywords": ["bizchannel", "marketplace", "discovery", "escrow", "pro feature"],
    },

    # ── Backup System ─────────────────────────────────────────────────────────

    {
        "title": "BizNode backup system",
        "content": (
            "BizNode includes automated backup for PostgreSQL and Qdrant:\n\n"
            "- Daily at 5 PM via Windows Task Scheduler (BizNodeDailyBackup)\n"
            "- PostgreSQL: pg_dump of all 51 tables\n"
            "- Qdrant: snapshot of biznode_memory and biznode_support collections\n"
            "- Google Drive upload (Pro tier)\n\n"
            "Manual commands:\n"
            "  python backup/run_backup.py        # Full backup + upload\n"
            "  python backup/run_backup.py --local # Local backup only\n"
            "  python backup/run_backup.py --check # Verify backup health\n\n"
            "Backup files are stored in the backup/ folder locally."
        ),
        "tags": ["support", "backup", "database", "faq"],
        "keywords": ["backup", "postgresql", "qdrant", "google drive", "pg_dump", "restore"],
    },

    # ── Affiliate Links ───────────────────────────────────────────────────────

    {
        "title": "Affiliate and referral link system",
        "content": (
            "BizNode includes an affiliate link management system:\n\n"
            "- Create affiliate/referral links in the dashboard (Affiliate Links section)\n"
            "- Track clicks and conversions\n"
            "- Customers see partner links via /affiliate command or customer menu\n"
            "- Owner manages links via the 'Affiliate Links' button in the owner menu\n\n"
            "The affiliate_service.py handles CRUD operations, click tracking, "
            "and formatting links for Telegram display."
        ),
        "tags": ["support", "affiliate", "marketing", "faq"],
        "keywords": ["affiliate", "referral", "links", "partner", "tracking", "clicks"],
    },

    # ── Service Manager ───────────────────────────────────────────────────────

    {
        "title": "Starting and stopping BizNode services",
        "content": (
            "BizNode runs multiple services that can be managed together:\n\n"
            "Start all services:\n"
            "  python service_manager.py start\n"
            "  (or) start.bat\n\n"
            "Stop all services:\n"
            "  python service_manager.py stop\n"
            "  (or) stop.bat\n\n"
            "Restart all services:\n"
            "  python service_manager.py restart\n"
            "  (or) restart.bat\n\n"
            "Check status:\n"
            "  python status.py\n\n"
            "Services: Dashboard (port 7777), Telegram Bot, Qdrant (Docker, port 6333), "
            "Ollama (native, port 11434), PostgreSQL (port 5432)."
        ),
        "tags": ["support", "services", "startup", "faq"],
        "keywords": ["start", "stop", "restart", "service manager", "status", "start.bat"],
    },

    # ── Customer Menu ─────────────────────────────────────────────────────────

    {
        "title": "Customer Telegram menu and interactions",
        "content": (
            "Customers interact with your BizNode bot via Telegram:\n\n"
            "Built-in menu categories:\n"
            "- Our Services: shows business services and pricing\n"
            "- Buy a License: purchase Basic ($200) or Pro ($499) license\n"
            "- Partner Links: affiliate and referral links\n\n"
            "Custom menu items can be added via the Dashboard Menu Builder section. "
            "These appear alongside the built-in categories.\n\n"
            "Customer commands:\n"
            "- /start — greeting and main menu\n"
            "- /buy_license — choose Basic/Pro and payment method (Stripe or crypto)\n"
            "- /verify_purchase REF OTP TX_HASH — verify crypto payment\n"
            "- /purchase_status REF — check purchase status\n"
            "- /affiliate — view partner/referral links\n\n"
            "All other messages go to the AI chatbot which answers using business knowledge."
        ),
        "tags": ["support", "customer", "menu", "telegram", "faq"],
        "keywords": ["customer menu", "buy license", "services", "affiliate", "start", "telegram"],
    },

    # ── Industry Packages (Vision) ────────────────────────────────────────────

    {
        "title": "BizNode industry-specific packages (coming soon)",
        "content": (
            "BizNode is designed as a universal automation core that can be customized "
            "for specific industries:\n\n"
            "Planned industry packages (built on Pro):\n"
            "- Lawyers: legal document generation, case management, compliance templates\n"
            "- Chartered Accountants: invoicing, tax document automation, audit workflows\n"
            "- Doctors: appointment booking, patient records, prescription management\n"
            "- Real Estate: property listings, client matching, contract generation\n"
            "- Restaurants: menu management, order processing, delivery coordination\n\n"
            "Each industry package includes the full Pro features plus specialized "
            "tools, templates, and workflows for that profession.\n\n"
            "The Basic automation core (AI chatbot, CRM, email, workflows) benefits "
            "every industry — industry packages add professional-specific features on top."
        ),
        "tags": ["support", "vision", "industry", "roadmap", "faq"],
        "keywords": ["industry", "lawyer", "accountant", "doctor", "real estate", "custom", "package"],
    },

    # ── Node Network ──────────────────────────────────────────────────────────

    {
        "title": "BizNode network and node identity",
        "content": (
            "Each BizNode instance has a unique identity (Ed25519 keypair) for "
            "peer-to-peer networking:\n\n"
            "- Node Identity: generated at first run, stored in identity/ folder\n"
            "- Trusted Nodes: register peers for cross-node collaboration\n"
            "- MCP Keys: capability tokens for inter-node API access\n"
            "- Network Monitoring: track node health and interactions (Pro)\n\n"
            "The 1BZ Network allows BizNode instances to discover and interact "
            "with each other. All inter-node collaboration is voluntary and user-governed.\n\n"
            "Dashboard sections: Node Network, MCP Keys, Network monitoring."
        ),
        "tags": ["support", "network", "node", "identity"],
        "keywords": ["node", "network", "identity", "MCP", "trusted nodes", "peer", "Ed25519"],
    },

    # ── Public Repository ────────────────────────────────────────────────────

    {
        "title": "BizNode public GitHub repository",
        "content": (
            "BizNode™ is open-source software available on GitHub:\n\n"
            "**Public Repository:** https://github.com/1bzdzit/biznode\n\n"
            "The public repo contains:\n"
            "- Full source code under Apache License 2.0\n"
            "- Legal framework: LICENSE, DISCLAIMER.md, LEGAL.md, TERMS.md, TRADEMARK.md\n"
            "- Documentation: ARCHITECTURE.md, TECHNICAL_DOCUMENTATION.md\n"
            "- Installation guide: INSTALL.txt\n\n"
            "The code is free to use, modify, and distribute under Apache 2.0. "
            "However, the BizNode™ trademark is NOT included in the open-source license — "
            "see TRADEMARK.md for brand usage rules.\n\n"
            "To report issues or contribute:\n"
            "  https://github.com/1bzdzit/biznode/issues\n\n"
            "Maintained by 1BZ DZIT DAO LLC."
        ),
        "tags": ["support", "github", "repository", "open-source", "faq"],
        "keywords": ["github", "repository", "source code", "open source", "download", "1bzdzit", "contribute"],
    },

    # ── Legal Framework ───────────────────────────────────────────────────────

    {
        "title": "BizNode legal framework and trademark policy",
        "content": (
            "BizNode™ includes a complete legal framework:\n\n"
            "**LICENSE** — Apache License 2.0\n"
            "- Free to use, modify, and distribute the code\n"
            "- Copyright 2026 1BZ DZIT DAO LLC\n"
            "- Does NOT grant rights to use the BizNode™ trademark (Section 6)\n\n"
            "**DISCLAIMER.md** — Liability disclaimer\n"
            "- Software provided 'AS IS' without warranty\n"
            "- Autonomous AI operation notice — deployer is responsible for all bot actions\n"
            "- Financial/blockchain features used at deployer's own risk\n"
            "- Deployer must comply with local laws (business, AI, email, data protection)\n\n"
            "**LEGAL.md** — Legal structure\n"
            "- 1BZ DZIT DAO LLC is the infrastructure provider, not the operator\n"
            "- Each node runs independently under deployer's control\n"
            "- No agency, partnership, or fiduciary relationship created\n\n"
            "**TERMS.md** — Deployment terms\n"
            "- Deployer accepts full responsibility for AI-generated content\n"
            "- Deployer responsible for email spam compliance and Telegram API compliance\n"
            "- 1BZ DZIT DAO LLC not liable for business losses or regulatory penalties\n\n"
            "**TRADEMARK.md** — Brand usage policy\n"
            "- BizNode™ is a trademark of 1BZ DZIT DAO LLC\n"
            "- Always use BizNode™ (with ™) on first reference\n"
            "- Forks must be renamed — cannot use 'BizNode' in fork name\n"
            "- May state 'Based on BizNode™ by 1BZ DZIT DAO LLC'\n"
            "- Do not register 'BizNode' as domain, business name, or trademark\n"
            "- Trademark roadmap: Common-law ™ → State (Wyoming) → USPTO federal ®\n\n"
            "All legal files are available at: https://github.com/1bzdzit/biznode"
        ),
        "tags": ["support", "legal", "trademark", "license", "faq"],
        "keywords": ["legal", "trademark", "license", "apache", "disclaimer", "terms", "copyright", "1BZ DZIT DAO LLC"],
    },

    # ── March 12 2026 — AI Assistant & New Commands ──────────────────────────

    {
        "title": "AI Assistant Mode & Tier 2 Tool Calling",
        "content": (
            "BizNode bot now works as an intelligent AI assistant instead of a rigid command-line tool.\n\n"
            "**How message routing works:**\n"
            "1. Tier 1 (Regex) — Short direct commands like 'show leads', 'status', 'report' are matched instantly (<50ms)\n"
            "2. Tier 2 (LLM Tool Calling) — If no regex matches, the message goes to Ollama's qwen3.5:4b model "
            "with 6 available tools. The LLM decides whether to use a tool or answer conversationally.\n\n"
            "**Available tools:**\n"
            "- send_email — compose and send email\n"
            "- get_leads — retrieve recent business leads\n"
            "- get_report — generate activity report\n"
            "- get_status — check bot and service health\n"
            "- search_knowledge_base — semantic search across KB\n"
            "- get_recent_queries — show customer questions\n\n"
            "**Examples:**\n"
            "- 'How's the business doing today?' → LLM calls get_status + get_leads\n"
            "- 'Draft an email to supplier about pricing' → LLM calls send_email\n"
            "- 'Good morning' → LLM responds conversationally, no tools\n\n"
            "You can talk naturally — no need to memorise exact commands."
        ),
        "tags": ["support", "ai", "assistant", "tool-calling", "faq"],
        "keywords": ["ai assistant", "tool calling", "tier 2", "natural language", "ollama", "LLM", "smart bot"],
    },

    {
        "title": "/help Command Guide",
        "content": (
            "The /help command shows a complete, role-aware command guide.\n\n"
            "**Owner sees:**\n"
            "- Business Management: /report, /leads, /queries, /status, /menu\n"
            "- Knowledge Base: /kbadd, /kbremove, /memory\n"
            "- Group & Marketing: /postgroup, /affiliate\n"
            "- Email: natural language ('send email to X about Y')\n"
            "- Payments: /services, /purchase_status\n"
            "- AI assistant tip — talk naturally\n"
            "- /bizbrain — 4-step AI business profile generator\n"
            "- /clear — clear conversation memory\n\n"
            "**Customer sees:**\n"
            "- Getting Started: /start, /menu, /role\n"
            "- Services & Payments: /services, /buy_license, /purchase_status, /wallet, /affiliate\n"
            "- Transactions: /transact, /pay, /negotiate\n"
            "- Conversation: /clear, /memory, /bizbrain\n\n"
            "Tip: You can talk to the bot like a real assistant — it understands natural language."
        ),
        "tags": ["support", "help", "commands", "guide", "faq"],
        "keywords": ["help", "commands", "guide", "owner", "customer", "menu"],
    },

    {
        "title": "Knowledge Base Management — /kbadd & /kbremove",
        "content": (
            "Owners can manage the AI knowledge base directly from Telegram.\n\n"
            "**Adding entries — /kbadd:**\n"
            "Two formats:\n"
            "1. /kbadd Title | Content here\n"
            "2. /kbadd Just the content (title auto-generated from first 60 chars)\n\n"
            "The entry is embedded using nomic-embed-text and stored in Qdrant's biznode_support collection. "
            "It becomes immediately searchable by customers.\n\n"
            "**Removing entries — /kbremove:**\n"
            "1. /kbremove 12345678 — remove by point ID (shown when you add)\n"
            "2. /kbremove return policy — semantic search, removes best match\n\n"
            "The bot confirms with title, ID, and similarity score.\n\n"
            "**How it powers the bot:**\n"
            "When customers ask questions, the bot embeds their question and searches KB for relevant entries. "
            "Top matches are injected into LLM context, so the bot answers with your specific business info."
        ),
        "tags": ["support", "knowledge-base", "kbadd", "kbremove", "faq"],
        "keywords": ["kbadd", "kbremove", "knowledge base", "add", "remove", "qdrant", "support articles"],
    },

    {
        "title": "Group Posting — /postgroup & Daily Updates",
        "content": (
            "**Manual group posting — /postgroup:**\n"
            "Post any message to your business Telegram group from a private chat:\n"
            "  /postgroup Check out our new features!\n"
            "  /grouppost is an alias — same functionality.\n"
            "Supports Markdown formatting. Owner only.\n\n"
            "**Automated daily business updates:**\n"
            "BizNode automatically posts a daily update to your Telegram group every 24 hours.\n"
            "Each post includes:\n"
            "- Current date and business status\n"
            "- Feature highlights (Smart Bot, BizChannel, Payment Agent)\n"
            "- Direct links to website pages:\n"
            "  - biznode.1bz.biz — Get Started\n"
            "  - biznode.1bz.biz/features.php — All Features\n"
            "  - biznode.1bz.biz/tutorial.php — Tutorial\n"
            "  - biznode.1bz.biz/update-guide.php — Update Guide\n\n"
            "The daily update runs automatically — no action required from the owner. "
            "Keeps your group active and drives website traffic."
        ),
        "tags": ["support", "group", "posting", "marketing", "daily-update"],
        "keywords": ["postgroup", "grouppost", "telegram group", "daily update", "marketing", "post"],
    },

    {
        "title": "/bizbrain — AI Business Profile Generator",
        "content": (
            "The /bizbrain command launches a 4-step AI business profile intake.\n\n"
            "**Questions asked:**\n"
            "1. What type of business do you run?\n"
            "2. What services or products do you offer?\n"
            "3. Who is your target audience?\n"
            "4. What are your main business challenges?\n\n"
            "After all 4 answers, the AI generates a personalised business profile with "
            "recommendations tailored to your industry and challenges.\n\n"
            "Previously this was triggered by /help — now /help shows the command guide, "
            "and /bizbrain is a dedicated command for the profile generator."
        ),
        "tags": ["support", "bizbrain", "profile", "faq"],
        "keywords": ["bizbrain", "business profile", "intake", "questions", "AI profile"],
    },

    {
        "title": "March 2026 Changelog — All New Features",
        "content": (
            "**March 2026 Release Summary:**\n\n"
            "1. AI Assistant Mode — bot responds naturally like an executive assistant\n"
            "2. Tier 2 Tool Calling — Ollama LLM decides when to use tools vs respond conversationally\n"
            "3. /help Command — complete role-aware command guide (owner vs customer views)\n"
            "4. /kbadd & /kbremove — manage knowledge base from Telegram\n"
            "5. /postgroup — post to business Telegram group\n"
            "6. Daily Business Updates — automated daily group posts with website links\n"
            "7. Webhook Payment Sync — VPS payment webhooks synced to local admin node\n"
            "8. /bizbrain — moved from /help to dedicated command\n\n"
            "Full documentation: https://biznode.1bz.biz/changelog-march2026.php\n\n"
            "All core features included in Basic and Pro packages. "
            "Admin-only features (daily updates, webhook sync) are exclusive to admin node."
        ),
        "tags": ["support", "changelog", "release", "march-2026", "faq"],
        "keywords": ["changelog", "march 2026", "new features", "release", "update", "what's new"],
    },

    # ── Version Control & Delta Updates ──────────────────────────────────────

    {
        "title": "How to Check Your BizNode Version — Step by Step",
        "content": (
            "There are 3 ways to check which version of BizNode you are running:\n\n"
            "**Method 1: Telegram Bot (easiest)**\n"
            "Step 1: Open your Telegram chat with @biznode_bot\n"
            "Step 2: Type /version and send\n"
            "Step 3: Bot shows your running version and the latest server version\n"
            "Step 4: If an update is available, it tells you the exact command to run\n"
            "Example response:\n"
            "  Running: 1.2.0\n"
            "  Latest: 1.3.0\n"
            "  Update available!\n"
            "  Run: python scripts/update_biznode.py\n\n"
            "**Method 2: VERSION File**\n"
            "Step 1: Open your BizNode installation folder\n"
            "Step 2: Find the file named VERSION (no extension)\n"
            "Step 3: Open it — it contains a single line with your version number (e.g., 1.2.0)\n\n"
            "**Method 3: Dashboard API**\n"
            "Step 1: Make sure your dashboard is running (python run_dashboard.py)\n"
            "Step 2: Open browser to http://localhost:7777/api/health\n"
            "Step 3: The JSON response includes a 'version' field\n\n"
            "**Check server version (what's available):**\n"
            "Visit: https://biznode.1bz.biz/api/version.php\n"
            "This returns the latest version, file count, and download URL."
        ),
        "tags": ["support", "version", "check", "how-to", "faq"],
        "keywords": ["check version", "version", "what version", "which version", "current version", "running version"],
    },

    {
        "title": "How to Update BizNode — Step by Step (Delta Updates)",
        "content": (
            "BizNode supports delta updates — you only download files that changed, "
            "not the entire package. Here is the step-by-step process:\n\n"
            "**Step 1: Check for updates**\n"
            "Open a terminal/command prompt in your BizNode folder and run:\n"
            "  python scripts/update_biznode.py --check\n"
            "This shows how many files changed, what will be updated, and download size.\n"
            "No changes are made — this is just a preview.\n\n"
            "**Step 2: Apply the update**\n"
            "If updates are available, run:\n"
            "  python scripts/update_biznode.py\n"
            "The updater will:\n"
            "  1. Compute checksums of all your local files\n"
            "  2. Send them to the BizNode server\n"
            "  3. Server compares and returns only changed files\n"
            "  4. Download each changed file (verified with MD5 checksum)\n"
            "  5. Update your local VERSION file\n\n"
            "**Step 3: Restart services**\n"
            "Either add --restart to auto-restart:\n"
            "  python scripts/update_biznode.py --restart\n"
            "Or restart manually:\n"
            "  python service_manager.py restart\n\n"
            "**What is PROTECTED (never overwritten):**\n"
            "- .env (your configuration and API keys)\n"
            "- identity/ folder (your node identity keys)\n"
            "- memory/biznode.db (your database)\n"
            "- backup credentials (Google Drive tokens)\n"
            "- logs/ folder\n"
            "Your data is always safe during updates.\n\n"
            "**Alternative: Full download**\n"
            "If you prefer, you can always download the full package from:\n"
            "  https://biznode.1bz.biz/download/BizNode.zip\n"
            "Extract and replace code files (keep your .env and identity/).\n\n"
            "**Troubleshooting:**\n"
            "- If update fails, check your internet connection\n"
            "- Use --force to retry even if versions match\n"
            "- Check logs/maintenance_*.log for details\n\n"
            "Full documentation: https://biznode.1bz.biz/changelog-march2026.php#version-control"
        ),
        "tags": ["support", "update", "how-to", "delta", "step-by-step", "faq"],
        "keywords": ["update", "how to update", "delta update", "update_biznode", "upgrade", "new version", "download update"],
    },

    {
        "title": "BizNode Version History",
        "content": (
            "**Version 1.2.0 — March 12, 2026 (Current)**\n"
            "- AI assistant mode with natural language understanding\n"
            "- Tier 2 LLM tool calling (Ollama qwen3.5:4b)\n"
            "- /help command with owner and customer guides\n"
            "- /kbadd and /kbremove — manage knowledge base from Telegram\n"
            "- /postgroup — post to Telegram group from private chat\n"
            "- Automated daily business updates to group with website links\n"
            "- Webhook payment sync (VPS to local admin node)\n"
            "- /version command and delta update system\n"
            "- /bizbrain — AI business profile generator\n"
            "- 34 knowledge base articles\n\n"
            "**Version 1.1.0 — March 7, 2026**\n"
            "- License purchase system (Stripe + crypto)\n"
            "- Affiliate and referral links\n"
            "- PostgreSQL database support\n"
            "- Telegram user tracking\n"
            "- Support knowledge base integration\n\n"
            "**Version 1.0.0 — February 2026**\n"
            "- Initial release\n"
            "- Telegram bot with AI assistant\n"
            "- Dashboard (FastAPI port 7777)\n"
            "- Qdrant vector knowledge base\n"
            "- Ollama local LLM\n"
            "- Email automation (SMTP)\n"
            "- Lead capture and CRM\n"
            "- Node identity system\n\n"
            "Check your version: /version in Telegram\n"
            "Update guide: https://biznode.1bz.biz/changelog-march2026.php#version-control"
        ),
        "tags": ["support", "version", "history", "changelog", "faq"],
        "keywords": ["version history", "changelog", "releases", "1.0", "1.1", "1.2", "what changed", "release notes"],
    },

    # ── Founder Profile ─────────────────────────────────────────────────────

    {
        "title": "BizNode Founder & CEO",
        "content": (
            "BizNode is built by the Founder & CEO of 1BZ DZIT DAO LLC.\n\n"
            "**Vision:** Autonomous AI business infrastructure that puts the power "
            "of automation in every business owner's hands.\n\n"
            "**Connect:**\n"
            "- LinkedIn: https://www.linkedin.com/in/1bz/\n"
            "- Email: biznode@1bz.biz\n"
            "- Website: https://biznode.1bz.biz\n"
            "- GitHub: https://github.com/1bzdzit/biznode\n\n"
            "**Company:** 1BZ DZIT DAO LLC\n\n"
            "Use /ceo or /founder in the bot to see the founder profile."
        ),
        "tags": ["support", "founder", "ceo", "about", "company"],
        "keywords": ["ceo", "founder", "owner", "who built", "who made", "about", "company", "1bz"],
    },

    # ── HTML Email Templates ────────────────────────────────────────────────

    {
        "title": "HTML Email Templates & Style Selection",
        "content": (
            "BizNode supports 5 built-in HTML email templates with the BizNode logo.\n\n"
            "**How to enable HTML emails:**\n"
            "1. Open the Dashboard -> Settings -> Email (SMTP) section\n"
            "2. Set Email Format to 'HTML (Styled)'\n"
            "3. Choose a style (1-5):\n"
            "   - Style 1: Professional - Clean white layout with indigo header bar\n"
            "   - Style 2: Modern Dark - Dark theme with gradient text effects\n"
            "   - Style 3: Elegant - Serif fonts, gold accents, refined look\n"
            "   - Style 4: Bold Gradient - Vibrant purple-pink gradient header\n"
            "   - Style 5: Minimal - Simple, no-frills clean layout\n\n"
            "**How it works:**\n"
            "- When EMAIL_FORMAT=html, all outgoing emails are automatically wrapped in the selected template\n"
            "- The BizNode logo is embedded inline (no external image hosting needed)\n"
            "- Plain text fallback is always included for email clients that don't support HTML\n"
            "- Templates are stored in the templates/ folder and can be customized\n\n"
            "**Settings:**\n"
            "- EMAIL_FORMAT: 'text' (default) or 'html'\n"
            "- EMAIL_STYLE: '1' through '5' (only used when format is html)\n"
            "- BUSINESS_NAME: Your business name shown in the email footer\n\n"
            "All email types use the selected style: lead notifications, approval requests, "
            "digest emails, promotional emails, and agent emails."
        ),
        "tags": ["support", "email", "html", "templates", "style", "configuration"],
        "keywords": ["html email", "email template", "email style", "styled email", "email format",
                      "professional email", "modern email", "elegant email", "bold email", "minimal email",
                      "email configuration", "email settings", "logo email"],
    },

    # ── PDF Update Packet System ──────────────────────────────────────────────

    {
        "title": "PDF Update Packet System",
        "content": (
            "BizNode uses signed PDF update packets to distribute updates without downloading files.\n\n"
            "**How it works:**\n"
            "1. Admin creates an update packet PDF with /sendupdate command\n"
            "2. PDF is posted to Telegram group (broadcast) or emailed to a specific node\n"
            "3. Receiving nodes download the PDF, verify the Ed25519 signature, and apply\n\n"
            "**Update types:**\n"
            "- updatetemplate: Email/UI template updates\n"
            "- updatemenu: Menu & navigation changes\n"
            "- updateworkflow: Workflow engine updates\n"
            "- updatebiz: Business configuration\n"
            "- updatekb: Knowledge base articles\n"
            "- updatetables: Database table migrations\n"
            "- updatedzit: DZIT credit updates (Pro only, requires OTP)\n"
            "- updatebzeusd: BZeUSD balance updates (Pro only, requires OTP)\n\n"
            "**Security:**\n"
            "- Every packet is signed with Ed25519 (node identity key)\n"
            "- Signature verified before any update is applied\n"
            "- Blockchain operations (DZIT/BZeUSD) require OTP sent to owner email + chat\n"
            "- Blockchain updates are Pro-only, all others work on Basic and Pro\n"
            "- Dangerous SQL patterns are blocked in table migrations\n"
            "- Protected keys (credentials) are never overwritten by remote config updates\n\n"
            "**Commands:**\n"
            "- /sendupdate <type> <version> <tier> <summary> -- create and send packet\n"
            "- /setpayload {json} -- set JSON payload before /sendupdate\n"
            "- /applyupdate <OTP> -- confirm blockchain update with OTP\n"
            "- Individual node: /sendupdate updatekb 1.2.1 all --email user@mail.com Summary"
        ),
        "tags": ["support", "updates", "pdf", "packets", "admin", "security"],
        "keywords": ["update packet", "pdf update", "sendupdate", "setpayload", "applyupdate",
                      "remote update", "broadcast", "signed update", "Ed25519",
                      "updatekb", "updatetemplate", "updatedzit", "updatebzeusd"],
    },

    # ── Ad Marketplace ──────────────────────────────────────────────────────

    {
        "title": "BizNode Ad Marketplace — Decentralized Advertising",
        "content": (
            "The BizNode Ad Marketplace is a decentralized advertising network powered by "
            "DZIT credits and BZeUSD tokens.\n\n"
            "**How it works (6 stages):**\n\n"
            "1. PROPOSE: Advertiser emails biznode@1bz.biz or uses /bo command. "
            "BizNode checks DZIT balance, sends OTP to registered email, and waits "
            "for confirmation via chat ID (24h window). 1 DZIT deducted only after "
            "OTP confirmed. No credits or no confirmation = proposal ignored.\n\n"
            "2. BROADCAST: PDF proposal sent to all registered bot emails, "
            "filtered by business category.\n\n"
            "3. QUOTE: Nodes have 24h to respond. Bot asks owner, owner sends quote.\n\n"
            "4. EVALUATE: BizNode AI evaluates group activity using harmonious scoring.\n"
            "   Formula: active_ratio = daily_active / total_members\n"
            "   harmonious_score = min(active_ratio * total_members, quoted_amount)\n"
            "   Example: 1000 members, 50 daily active, quote=100 -> score=50\n\n"
            "5. PUBLISH: Ad posted to /bo page, KB updated, menu updated (1 year), "
            "groups receive posts via PDF update.\n\n"
            "6. MONITOR: 15-day activity tracking. Incentives paid: "
            "50% BZeUSD + 50% DZIT credits via PDF update (Pro only, OTP required).\n\n"
            "**Pricing:**\n"
            "- Proposal fee: 1 DZIT\n"
            "- Per BiznodeBOT interaction: 1 DZIT\n"
            "- Node incentive: 50% BZeUSD + 50% DZIT\n"
            "- KB rewards: 5 BZeUSD + 5 DZIT per 10K harmonious interactions (10K+ groups)\n"
            "- Ad duration: 1 year (auto-removed)\n\n"
            "**Commands:** /bo, /bo submit, /bo quote <id> <amount>, /bo status <id>, "
            "/handle <ad_id>\n\n"
            "**Template Marketplace:** Buy/sell email templates through the network. "
            "Templates appear in menu column for 1 year."
        ),
        "tags": ["support", "marketplace", "advertising", "dzit", "bzeusd",
                 "blockchain", "pro", "incentives"],
        "keywords": ["ad marketplace", "advertising", "business opportunity", "bo",
                      "proposal", "quote", "harmonious", "incentive", "template sale",
                      "bzeusd", "dzit", "publish", "group posting", "monitor"],
    },

    {
        "title": "Ad Marketplace /bo Bot Commands - Complete Guide",
        "content": (
            "The /bo command is the entry point for the BizNode Ad Marketplace. "
            "It connects advertisers with node operators through Telegram.\n\n"
            "**Commands for everyone:**\n"
            "- /bo - Show marketplace help menu\n"
            "- /bo submit <title> - Submit an ad proposal (requires registration + DZIT)\n"
            "- /bo confirm <id> <otp> - Confirm proposal with OTP from email\n"
            "- /bo quote <id> <amount> - Submit a quote for a proposal (node owners)\n"
            "- /bo status <id> - Check proposal or campaign status\n\n"
            "**Owner/admin commands:**\n"
            "- /bo accept <id> - Accept the consolidated quote and publish campaign\n"
            "- /bo campaigns - List all active campaigns\n"
            "- /bo stats - Show marketplace aggregate statistics\n\n"
            "**Typical flow:**\n"
            "1. Advertiser: /bo submit DeFi Token Launch\n"
            "2. System sends OTP to registered email\n"
            "3. Advertiser: /bo confirm 1 483729\n"
            "4. 1 DZIT deducted, proposal broadcast to matching nodes\n"
            "5. Node owners: /bo quote 1 100\n"
            "6. Harmonious scoring evaluates each quote\n"
            "7. Advertiser: /bo accept 1\n"
            "8. Campaign published, 15-day monitoring starts\n"
            "9. After 15 days, incentives paid (50% BZeUSD + 50% DZIT)\n\n"
            "**Requirements:** Must have registered email and at least 1 DZIT credit "
            "to submit a proposal. OTP must be confirmed within 24 hours."
        ),
        "tags": ["support", "bot", "commands", "marketplace", "advertising"],
        "keywords": ["/bo", "bo submit", "bo quote", "bo confirm", "bo accept",
                     "bo status", "bo campaigns", "bo stats", "ad marketplace",
                     "proposal", "advertising commands"],
    },
    {
        "title": "Harmonious Scoring - How Ad Quote Evaluation Works",
        "content": (
            "Harmonious scoring is BizNode's fair pricing algorithm for the Ad Marketplace. "
            "It prevents node operators from quoting inflated amounts that exceed their "
            "actual group engagement.\n\n"
            "**Core formula:**\n"
            "  active_ratio = daily_active_members / total_members\n"
            "  harmonious_score = min(active_ratio * total_members, quoted_amount)\n\n"
            "The score is capped at the LOWER of actual daily active members and the "
            "quoted amount. This ensures nodes can only earn what their engagement justifies.\n\n"
            "**Payout split:**\n"
            "  bzeusd_payout = harmonious_score * 50%\n"
            "  dzit_payout = harmonious_score * 50%\n\n"
            "**Example 1 - Fair quote:**\n"
            "  1,000 members, 50 daily active, quote = 50\n"
            "  Score = min(50, 50) = 50 -> 25 BZeUSD + 25 DZIT\n\n"
            "**Example 2 - Inflated quote:**\n"
            "  1,000 members, 50 daily active, quote = 200\n"
            "  Score = min(50, 200) = 50 -> 25 BZeUSD + 25 DZIT (capped at activity)\n\n"
            "**Example 3 - Large active group:**\n"
            "  10,000 members, 2,000 active, quote = 100\n"
            "  Score = min(2000, 100) = 100 -> 50 BZeUSD + 50 DZIT (quote fully justified)\n\n"
            "**Verdicts:**\n"
            "- accepted: Quote fully justified by group activity\n"
            "- adjusted: Score reduced from original quote\n"
            "- reduced: Score significantly below quote (>50% reduction)\n"
            "- rejected: No engagement detected (score = 0)\n\n"
            "**Consolidated quote:** When multiple nodes submit quotes, all accepted "
            "payouts are summed and presented to the advertiser for final acceptance."
        ),
        "tags": ["support", "marketplace", "scoring", "evaluation", "pricing"],
        "keywords": ["harmonious scoring", "harmonious score", "quote evaluation",
                     "active ratio", "daily active", "bzeusd payout", "dzit payout",
                     "fair pricing", "inflated quote", "ad evaluation"],
    },
    {
        "title": "Ad Marketplace - How Your Node Earns From Advertising",
        "content": (
            "As a BizNode operator, your bot can earn BZeUSD tokens and DZIT credits "
            "by publishing advertisements in your Telegram groups.\n\n"
            "**How you earn:**\n"
            "1. An advertiser submits a proposal to the BizNode network\n"
            "2. Your bot receives the proposal via email (filtered by category)\n"
            "3. You review it and submit a quote using /bo quote <id> <amount>\n"
            "4. BizNode evaluates your quote using harmonious scoring\n"
            "5. If accepted, the ad is published in your group\n"
            "6. After 15 days of monitoring, you receive your incentive\n\n"
            "**Incentive split:** 50% BZeUSD (cash tokens) + 50% DZIT credits\n\n"
            "**Harmonious scoring protects you:**\n"
            "The system ensures fair payouts based on actual group activity. "
            "If your group has 1,000 members and 50 are active daily, your payout "
            "is capped at 50 (not an inflated quote of 200). This keeps the "
            "marketplace honest for everyone.\n\n"
            "**Pro node bonus:** Pro tier nodes receive incentive payments via "
            "blockchain (Polygon) with OTP security. Basic nodes receive credits "
            "directly to their account.\n\n"
            "**KB contribution rewards:** Groups with 10,000+ members that "
            "generate 10,000 harmonious /handle interactions earn an additional "
            "5 BZeUSD + 5 DZIT per tier.\n\n"
            "**15-day monitoring:** After your group publishes an ad, BizNode "
            "tracks activity for 15 days (messages, views, clicks, interactions) "
            "to verify genuine engagement before releasing payment."
        ),
        "tags": ["support", "marketplace", "earning", "incentives", "node"],
        "keywords": ["earn from advertising", "node income", "ad incentive",
                     "how to earn", "bzeusd earning", "dzit earning",
                     "group advertising", "15 day monitoring", "kb contribution",
                     "pro node payment", "harmonious scoring"],
    },
    {
        "title": "Ad Marketplace - How to Advertise Your Business on BizNode",
        "content": (
            "BizNode Ad Marketplace lets you reach thousands of active Telegram group "
            "members through a decentralized advertising network.\n\n"
            "**Step-by-step guide:**\n\n"
            "1. **Register:** Make sure you have a registered email with BizNode "
            "and at least 1 DZIT credit in your account.\n\n"
            "2. **Submit proposal:** Use /bo submit <your campaign title>\n"
            "   Example: /bo submit Summer Sale Promotion\n\n"
            "3. **Confirm with OTP:** You'll receive an OTP to your registered email. "
            "Confirm within 24 hours: /bo confirm <id> <otp>\n"
            "   1 DZIT is deducted only after you confirm.\n\n"
            "4. **Wait for quotes:** Your proposal is broadcast to node operators "
            "whose groups match your business category. They have 24 hours to "
            "submit quotes.\n\n"
            "5. **Review & accept:** Check quotes with /bo status <id>. Each quote "
            "is evaluated by harmonious scoring to ensure fair pricing. When ready, "
            "accept with /bo accept <id>.\n\n"
            "6. **Campaign goes live:** Your ad is published across accepted groups, "
            "added to the website, and your business gets a menu link for 1 year.\n\n"
            "7. **Track results:** 15-day monitoring tracks real engagement in each "
            "group. Use /bo status <id> to check campaign progress.\n\n"
            "**What you get:**\n"
            "- Ad posted to targeted Telegram groups\n"
            "- Menu link on BizNode website (1 year)\n"
            "- Knowledge base entry about your business\n"
            "- Activity monitoring dashboard\n\n"
            "**Costs:**\n"
            "- 1 DZIT per proposal submission\n"
            "- Campaign cost = sum of accepted node quotes (BZeUSD + DZIT)\n"
            "- Ads auto-expire after 1 year"
        ),
        "tags": ["support", "marketplace", "advertising", "how-to", "getting-started"],
        "keywords": ["advertise on biznode", "how to advertise", "submit proposal",
                     "campaign cost", "ad pricing", "business promotion",
                     "telegram advertising", "bo submit", "1 year ad",
                     "menu link", "business opportunity"],
    },

    # ── DZIT & Payment System ─────────────────────────────────────────────────

    {
        "title": "How DZID Accounts Work — Virtual Identity on Polygon",
        "content": (
            "A DZID is your unique 6-character identity code (e.g., RXHUMP) "
            "in the 1BZ decentralized business network. It's created on the "
            "Polygon blockchain when you purchase a DZITPACKAGE.\n\n"
            "**How to get a DZID:**\n"
            "1. Visit https://dzit.1bz.biz and choose a package (Starter $10 to Ultra $10,000)\n"
            "2. Complete Stripe checkout with your email\n"
            "3. BizNode automatically creates your DZID on the Polygon blockchain\n"
            "4. You receive a branded email with your DZID, credit points, and a PolygonScan verification link\n\n"
            "**What your DZID stores on-chain:**\n"
            "- Email hash (keccak256 — your actual email is never on the blockchain)\n"
            "- Credit points (DZIT-backed)\n"
            "- Wallet address\n"
            "- Active status\n\n"
            "**One email = one DZID.** If you already have a DZID and purchase again, "
            "credits are added to your existing account.\n\n"
            "**Use your DZID for:** Accessing network services, tracking credits, "
            "verifying service delivery on PolygonScan, and connecting to @biznode_bot."
        ),
        "tags": ["support", "dzit", "dzid", "blockchain", "account", "getting-started"],
        "keywords": ["dzid", "virtual account", "polygon", "blockchain identity",
                     "how to get dzid", "what is dzid", "create account",
                     "6 character code", "email hash"],
    },
    {
        "title": "DZIT Credit Tiers — Pricing and Bonuses",
        "content": (
            "DZIT credits are purchased through Stripe and deposited to your DZID "
            "account on the Polygon blockchain. Higher tiers earn bonus credits.\n\n"
            "**DZITPACKAGE — First-Time Membership (creates DZID + credits):**\n"
            "- Starter: $10 = 10 credits (0% bonus)\n"
            "- Business: $100 = 110 credits (10% bonus)\n"
            "- BizPlus: $500 = 600 credits (20% bonus)\n"
            "- Enterprise: $1,000 = 1,300 credits (30% bonus)\n"
            "- Ultra: $10,000 = 15,000 credits (50% bonus)\n\n"
            "**TOPUP — Reload Credits (existing DZID):**\n"
            "- $10 = 11 credits (10% bonus)\n"
            "- $100 = 120 credits (20% bonus)\n"
            "- $500 = 600 credits (20% bonus)\n"
            "- $1,000 = 1,300 credits (30% bonus)\n\n"
            "**Key facts:**\n"
            "- Credits are NOT 1:1 with dollars — higher tiers get more per dollar\n"
            "- If you don't have a DZID yet and purchase a TOPUP, one is created automatically\n"
            "- Credits are backed by DZIT tokens on Polygon\n"
            "- Your balance is verifiable on PolygonScan\n\n"
            "Purchase at: https://dzit.1bz.biz"
        ),
        "tags": ["support", "dzit", "pricing", "credits", "tiers"],
        "keywords": ["dzit credits", "credit tiers", "pricing", "how much",
                     "starter", "business", "bizplus", "enterprise", "ultra",
                     "topup", "bonus credits", "cost"],
    },
    {
        "title": "Service Tickets — Proof of Every Transaction",
        "content": (
            "Every service rendered by BizNode gets a unique service ticket "
            "linked to blockchain transaction hashes as proof-of-service.\n\n"
            "**Ticket format:** BN-YYYYMMDD-XXXXX (e.g., BN-20260309-K7X2P)\n\n"
            "**What a service ticket contains:**\n"
            "- Unique ticket ID\n"
            "- Service type (dzid_creation, topup, book_sale)\n"
            "- Your email address\n"
            "- DZID (if applicable)\n"
            "- Blockchain transaction hash (tx_hash)\n"
            "- Proof-of-service transaction hash\n"
            "- Block number on Polygon\n"
            "- Status (pending → completed or failed)\n"
            "- Timestamps (created, completed)\n\n"
            "**How to verify your ticket:**\n"
            "Your confirmation email includes a PolygonScan link. Click it to see "
            "the immutable blockchain record of your transaction — 1 DZIT transferred "
            "as proof that service was rendered.\n\n"
            "**If something goes wrong:**\n"
            "You'll receive a 'Processing' email immediately with your ticket ID. "
            "Use this ticket ID when contacting biznode@1bz.biz for support."
        ),
        "tags": ["support", "service-ticket", "blockchain", "proof", "verification"],
        "keywords": ["service ticket", "BN-", "ticket id", "proof of service",
                     "verify transaction", "polygonscan", "tx hash",
                     "how to verify", "support ticket"],
    },
    {
        "title": "Payment Flow — From Stripe Checkout to Blockchain",
        "content": (
            "Here's what happens after you complete a Stripe payment on https://dzit.1bz.biz:\n\n"
            "**Step 1 — Payment confirmed:** Stripe processes your card payment and sends "
            "a webhook notification to the BizNode server.\n\n"
            "**Step 2 — Immediate email:** You receive a 'Payment Received' email with "
            "your service ticket ID and processing status.\n\n"
            "**Step 3 — Blockchain operations (takes ~30 seconds):**\n"
            "- Your DZID is created on the Polygon blockchain (if new)\n"
            "- Credit points are deposited based on your tier\n"
            "- 1 DZIT token is transferred as proof-of-service\n\n"
            "**Step 4 — Confirmation email:** You receive a branded email with:\n"
            "- Your DZID code\n"
            "- Credit points balance\n"
            "- Service ticket reference\n"
            "- PolygonScan link to verify the blockchain transaction\n\n"
            "**Supported payment methods:**\n"
            "- Credit/debit card via Stripe\n"
            "- BZeUSD (stablecoin) on Polygon — send to the BizNode wallet, "
            "then verify with /mr_verify command\n"
            "- DZIT credits — deducted directly for registered nodes\n\n"
            "All payments are non-refundable once blockchain operations are confirmed."
        ),
        "tags": ["support", "payment", "stripe", "flow", "how-to"],
        "keywords": ["payment flow", "how payment works", "stripe checkout",
                     "what happens after payment", "blockchain confirmation",
                     "email notification", "processing time", "refund"],
    },
    {
        "title": "Email Notifications — What Emails You'll Receive",
        "content": (
            "BizNode sends branded HTML emails at key points in your journey:\n\n"
            "**1. Payment Received (immediate):**\n"
            "- Subject: 'Payment Received — Processing [service] (Ticket BN-...)'\n"
            "- Includes your service ticket ID\n"
            "- Sent within seconds of Stripe confirmation\n\n"
            "**2. DZID Welcome (after blockchain completes):**\n"
            "- Subject: 'Your DZIT Account [DZID] — Welcome to the Network'\n"
            "- Shows your DZID, credit points, service ticket\n"
            "- Includes PolygonScan link to verify blockchain proof\n"
            "- Sent ~30 seconds after payment\n\n"
            "**3. Credit Topup Confirmation:**\n"
            "- Subject: 'DZIT Topup: +X Credits (Ticket BN-...)'\n"
            "- Shows credits added, DZID, blockchain proof link\n\n"
            "**All emails include:**\n"
            "- BizNode logo\n"
            "- Dark-themed professional design\n"
            "- Service ticket reference for support\n"
            "- PolygonScan verification link\n"
            "- Contact: biznode@1bz.biz\n\n"
            "Not receiving emails? Check your spam folder. Emails are sent from "
            "the SMTP configured in your node's .env file."
        ),
        "tags": ["support", "email", "notifications", "dzid", "payment"],
        "keywords": ["email notification", "not receiving email", "payment email",
                     "welcome email", "confirmation email", "dzid email",
                     "check spam", "biznode logo email"],
    },
    {
        "title": "Marketing Reports (/mr) — DataVault Package",
        "content": (
            "The /mr command in @biznode_bot generates a bundle of 8 professional "
            "AI-powered marketing reports for any website URL.\n\n"
            "**Reports included:**\n"
            "1. Sales Report — revenue analysis and projections\n"
            "2. SEO Audit — technical SEO, keywords, backlinks\n"
            "3. Competitor Analysis — market positioning\n"
            "4. Social Media Report — platform presence\n"
            "5. Ad Campaign Report — advertising effectiveness\n"
            "6. Email Marketing Report — campaign metrics\n"
            "7. Conversion Analysis — funnel optimization\n"
            "8. Market Research — industry trends\n\n"
            "**Pricing:**\n"
            "- Public: 10 BZeUSD (send to BizNode wallet, verify with /mr_verify)\n"
            "- Registered nodes: 1 DZIT credit (auto-deducted)\n\n"
            "**How to order:**\n"
            "1. Send /mr to @biznode_bot\n"
            "2. View pricing and wallet address\n"
            "3. Send 10 BZeUSD to the displayed wallet on Polygon\n"
            "4. Use /mr_verify <order_id> <polygonscan_url> to confirm payment\n"
            "5. Reports are generated and sent as PDFs\n\n"
            "Registered nodes with sufficient DZIT credits get instant processing."
        ),
        "tags": ["support", "datavault", "marketing", "reports", "mr", "how-to"],
        "keywords": ["mr command", "marketing reports", "datavault", "sales report",
                     "seo audit", "competitor analysis", "10 bzeusd", "1 dzit",
                     "how to order reports", "/mr", "/mr_verify"],
    },
    {
        "title": "Blockchain Verification — How to Check on PolygonScan",
        "content": (
            "Every DZIT service is backed by a verifiable Polygon blockchain transaction.\n\n"
            "**How to verify your transaction:**\n"
            "1. Open the PolygonScan link from your confirmation email\n"
            "2. Or go to https://polygonscan.com/tx/0x{your_tx_hash}\n"
            "3. You'll see the transaction details:\n"
            "   - From: BizNode admin wallet\n"
            "   - To: DZITSystem smart contract\n"
            "   - Value: 1 DZIT token\n"
            "   - Block number and timestamp\n"
            "   - Transaction status (Success/Failed)\n\n"
            "**What you can verify independently:**\n"
            "- DZITSystem contract: https://polygonscan.com/address/0x14811c0497c958ffdc4ccf5b4f576b0bc19c44fd\n"
            "- DZIT token: https://polygonscan.com/token/0x4B37872c868571d4ad1f822c43d4e1B123FB43d8\n\n"
            "**Why this matters:**\n"
            "- Neither party can dispute whether service was delivered\n"
            "- Records are immutable — cannot be altered or deleted\n"
            "- No central authority needed — anyone can verify\n"
            "- Proves the exact time service was rendered"
        ),
        "tags": ["support", "blockchain", "verification", "polygonscan", "how-to"],
        "keywords": ["polygonscan", "verify transaction", "blockchain proof",
                     "check transaction", "tx hash", "how to verify",
                     "dzit contract", "polygon mainnet"],
    },

    # ── ADD YOUR OWN ARTICLES BELOW ──────────────────────────────────────────
    # Copy the format above and add as many as you need.

    # ── BizChannel Detailed Knowledge Base (from bizchannel.md) ──────────────

    {
        "title": "What is BizChannel — Decentralized Ad Marketplace Overview",
        "content": (
            "BizChannel is a decentralized advertising marketplace built on the 1BZ network. "
            "It connects advertisers who want to promote their business with BizNode operators "
            "who run Telegram bots in active communities.\n\n"
            "**The Problem It Solves:**\n"
            "Traditional Telegram advertising is broken — fake engagement, inflated member counts, "
            "no accountability, and no fair pricing. Advertisers overpay for bot-filled groups "
            "while honest community owners get undervalued.\n\n"
            "**The BizChannel Solution:**\n"
            "- Harmonious Scoring — Payouts capped by real engagement, not inflated quotes\n"
            "- AI Verification — Ollama LLM verifies ad delivery and engagement quality\n"
            "- Blockchain Escrow — BZeUSD payments secured on Polygon, released only after verification\n"
            "- 15-Day Monitoring — Daily activity tracking proves real engagement over time\n"
            "- 50/50 Split — All payouts split between BZeUSD (liquid) and DZIT (ecosystem credits)\n"
            "- No Middlemen — Event-driven architecture, automated from proposal to payout\n\n"
            "**Three Roles:**\n"
            "- Advertiser: Any business that submits ad proposals and pays BZeUSD + 1 DZIT fee\n"
            "- Node Owner: BizNode operator running bots in Telegram groups, earns payouts\n"
            "- Admin (Market Maker): Manages marketplace, monitors campaigns, earns 5% platform fee\n\n"
            "BizChannel runs as a separate FastAPI service (port 7778) within the Pro package. "
            "It shares the same database, Qdrant, and Ollama services as the main BizNode dashboard.\n\n"
            "Website: https://bizchannel.1bz.biz"
        ),
        "tags": ["support", "bizchannel", "marketplace", "overview", "faq"],
        "keywords": ["what is bizchannel", "bizchannel overview", "decentralized advertising",
                     "ad marketplace", "telegram advertising", "bizchannel explained",
                     "how bizchannel works", "bizchannel features"],
    },

    {
        "title": "How to Submit an Ad Proposal on BizChannel — Step-by-Step Advertiser Guide",
        "content": (
            "Follow these steps to submit an advertising proposal on BizChannel:\n\n"
            "**Prerequisites:**\n"
            "- A registered BizNode account (email + Telegram)\n"
            "- At least 1 DZIT credit in your account (check with /balance)\n"
            "- BZeUSD for your campaign budget\n"
            "- Your ad copy and website URL\n\n"
            "**Step 1: Check Your DZIT Balance**\n"
            "Send /balance to @biznode_bot. You need at least 1 DZIT.\n"
            "If insufficient, purchase on DX (https://dx.1bz.biz).\n\n"
            "**Step 2: Submit Your Proposal**\n"
            "In Telegram, send:\n"
            "    /bo submit DeFi Token Launch Promotion\n\n"
            "The system checks your DZIT balance >= 1, generates a 6-digit OTP, "
            "and sends it to your registered email. OTP is valid for 24 hours.\n\n"
            "**Step 3: Confirm with OTP**\n"
            "Check your email for the OTP, then confirm:\n"
            "    /bo confirm <proposal_id> <otp>\n"
            "Example: /bo confirm 42 482913\n\n"
            "The system verifies both the OTP hash (SHA-256) and your Telegram chat_id. "
            "1 DZIT is deducted only after successful confirmation.\n\n"
            "**Step 4: Wait for Quotes (24 hours)**\n"
            "Your proposal is broadcast to node owners whose bots match your business category. "
            "They have 24 hours to submit quotes.\n\n"
            "**Step 5: Review Quotes**\n"
            "Check status:\n"
            "    /bo status <proposal_id>\n"
            "You will see each quote with bot name, group size, active members, quoted price, "
            "harmonious score, and the consolidated total cost.\n\n"
            "**Step 6: Accept the Consolidated Quote**\n"
            "If you are happy with the quotes:\n"
            "    /bo accept <proposal_id>\n"
            "This publishes your campaign — ads posted in all accepted groups, "
            "menu links added to each bot, and 15-day monitoring begins.\n\n"
            "**Step 7: Monitor Your Campaign**\n"
            "Use /bo status <id> to track 15-day engagement metrics including "
            "active members, click-through rates, and engagement scores."
        ),
        "tags": ["support", "bizchannel", "advertiser", "how-to", "step-by-step"],
        "keywords": ["submit ad proposal", "how to advertise bizchannel", "bo submit",
                     "bo confirm", "otp confirmation", "dzit balance", "ad proposal",
                     "advertiser guide", "bizchannel step by step"],
    },

    {
        "title": "How Harmonious Scoring Works in BizChannel",
        "content": (
            "Harmonious scoring is BizChannel's fair pricing algorithm. It prevents node owners "
            "from quoting inflated amounts that exceed their group's real engagement.\n\n"
            "**Core Formula:**\n"
            "    active_ratio = daily_active_members / total_members\n"
            "    effective_active = active_ratio * total_members\n"
            "    harmonious_score = min(effective_active, quoted_amount)\n\n"
            "The score is capped at the LOWER of actual daily active members and the quoted amount.\n\n"
            "**Payout Split (50/50):**\n"
            "    bzeusd_payout = harmonious_score * 0.50\n"
            "    dzit_payout = harmonious_score * 0.50\n\n"
            "**Verdict Rules:**\n"
            "- rejected: harmonious_score = 0 (no active engagement, no payout)\n"
            "- reduced: score < quoted * 0.5 (significantly below quote, payout slashed)\n"
            "- adjusted: score < quoted (reduced from original, fair market adjustment)\n"
            "- accepted: score >= quoted (quote fully justified by real activity)\n\n"
            "**Example 1 — Fair Quote (Accepted):**\n"
            "Group: 5,000 members, 1,200 daily active. Quote: $100.\n"
            "active_ratio = 1,200/5,000 = 0.24\n"
            "harmonious_score = min(1,200, 100) = 100.00\n"
            "Verdict: ACCEPTED. Payout: $50 BZeUSD + 50 DZIT\n\n"
            "**Example 2 — Inflated Quote (Adjusted):**\n"
            "Group: 50,000 members, 800 daily active. Quote: $5,000.\n"
            "active_ratio = 800/50,000 = 0.016\n"
            "harmonious_score = min(800, 5,000) = 800.00\n"
            "Verdict: ADJUSTED. Payout: $400 BZeUSD + 400 DZIT (not the $2,500 + $2,500 they wanted)\n\n"
            "**Example 3 — Dead Group (Rejected):**\n"
            "Group: 100,000 members, 0 daily active. Quote: $10,000.\n"
            "harmonious_score = min(0, 10,000) = 0.00\n"
            "Verdict: REJECTED. Payout: $0\n\n"
            "**Consolidated Quotes:** When multiple nodes quote on the same proposal, "
            "all accepted payouts are summed and presented to the advertiser for final acceptance."
        ),
        "tags": ["support", "bizchannel", "harmonious", "scoring", "pricing", "algorithm"],
        "keywords": ["harmonious scoring", "how scoring works", "active ratio",
                     "fair pricing bizchannel", "quote evaluation", "harmonious formula",
                     "bizchannel scoring", "accepted adjusted reduced rejected"],
    },

    {
        "title": "How Node Owners Earn Money on BizChannel",
        "content": (
            "As a BizNode operator, your Telegram bot can earn BZeUSD tokens and DZIT credits "
            "by publishing advertisements in your groups through BizChannel.\n\n"
            "**Step 1: Register Your Bot**\n"
            "Register your bot in the BizChannel marketplace:\n"
            "    /bo register @your_bot_username <category> <group_id>\n"
            "Example: /bo register @cryptoalpha_bot crypto -1001234567890\n\n"
            "**Step 2: Wait for Proposals**\n"
            "When advertisers submit proposals matching your category, you receive an email with "
            "campaign details, budget range, and a 24-hour deadline to quote.\n\n"
            "**Step 3: Submit Your Quote**\n"
            "    /bo quote <proposal_id> <amount>\n"
            "Example: /bo quote 42 200 (means 'I will run this ad for $200')\n"
            "Quote honestly — harmonious scoring verifies real engagement.\n\n"
            "**Step 4: Wait for Evaluation**\n"
            "The harmonious scoring engine evaluates your quote based on real group activity.\n\n"
            "**Step 5: Campaign Published**\n"
            "If the advertiser accepts, ads are posted in your group, "
            "menu links added to your bot, and 15-day monitoring begins.\n\n"
            "**Step 6: Earn Your Payout (After 15 Days)**\n"
            "- BZeUSD credited to your bc_wallets balance\n"
            "- DZIT credited to your dzit_balances\n"
            "- Pro nodes receive signed PDF update packet\n\n"
            "**Incentive Split:** 50% BZeUSD (liquid) + 50% DZIT (ecosystem credits)\n\n"
            "**Example Earnings (5,000-member group, 1,200 daily active, $100 quote):**\n"
            "Harmonious score = 100.00 (ACCEPTED). Payout: $50 BZeUSD + 50 DZIT\n\n"
            "**Tips for Maximizing Earnings:**\n"
            "1. Keep your group active — daily active members impact harmonious score\n"
            "2. Quote fairly — inflated quotes get adjusted down\n"
            "3. Run an engaging bot — /handle interactions earn KB rewards\n"
            "4. Register in specific categories — targeted ads pay more\n"
            "5. Upgrade to Pro — signed PDF packets for compliance + priority matching"
        ),
        "tags": ["support", "bizchannel", "node-owner", "earning", "how-to"],
        "keywords": ["node owner earn", "how to earn bizchannel", "bot earnings",
                     "register bot bizchannel", "bo register", "bo quote",
                     "bizchannel payout", "node income", "advertising earnings"],
    },

    {
        "title": "BizChannel Campaign Lifecycle — 6-Stage Pipeline",
        "content": (
            "Every BizChannel ad campaign follows a 6-stage event-driven pipeline, "
            "from proposal to payout.\n\n"
            "**Stage 1: PROPOSE**\n"
            "Advertiser submits proposal via /bo submit. System checks DZIT balance >= 1, "
            "generates 6-digit OTP (24-hour validity), sends to registered email. "
            "Advertiser confirms via /bo confirm <id> <otp>. "
            "Dual verification: OTP hash (SHA-256) + Telegram chat_id must both match. "
            "1 DZIT deducted only after confirmation.\n\n"
            "**Stage 2: BROADCAST**\n"
            "Broadcast worker queries verified bots from bc_registered_bots, "
            "filters by business_category match. Sends structured email to each node owner "
            "with proposal details and 24-hour quoting deadline.\n\n"
            "**Stage 3: QUOTE**\n"
            "Node owners review the proposal and submit quotes via /bo quote <id> <amount>. "
            "Quote includes bot_username, group_id, total_members, daily_active_members, "
            "quoted_amount, and node_tier. Quotes stored in bc_ad_quotes.\n\n"
            "**Stage 4: EVALUATE**\n"
            "Harmonious scoring worker calculates: "
            "active_ratio = daily_active / total_members, "
            "harmonious_score = min(active_ratio * total_members, quoted_amount). "
            "50/50 payout split (BZeUSD + DZIT). Verdict: rejected/reduced/adjusted/accepted.\n\n"
            "**Stage 5: PUBLISH**\n"
            "Advertiser reviews quotes via /bo status <id> and accepts via /bo accept <id>. "
            "System creates bc_ad_campaigns record, posts ad in each accepted group, "
            "adds menu link to bot (valid for campaign duration), creates KB article.\n\n"
            "**Stage 6: MONITOR (15 Days)**\n"
            "Daily monitoring for 15 days tracks: active_members, messages_count, ad_views, "
            "ad_clicks, handle_interactions, activity_score. "
            "After day 15: AD_INCENTIVE_PAID event triggers payouts to node owners.\n\n"
            "**Status Flow:**\n"
            "pending_otp -> awaiting_otp -> confirmed -> quoting -> evaluating -> "
            "accepted -> published -> monitoring -> completed"
        ),
        "tags": ["support", "bizchannel", "lifecycle", "pipeline", "campaign"],
        "keywords": ["campaign lifecycle", "bizchannel stages", "6 stage pipeline",
                     "propose broadcast quote evaluate publish monitor",
                     "ad campaign flow", "bizchannel pipeline", "campaign stages"],
    },

    {
        "title": "DZIT Credits and OTP Security in BizChannel",
        "content": (
            "DZIT is the universal gas credit across the 1BZ ecosystem. Every BizChannel "
            "action that costs money uses DZIT as the transaction fee.\n\n"
            "**DZIT Flow in BizChannel:**\n"
            "1. Advertiser buys DZIT on DX (Dzit Exchange) or earns via services\n"
            "2. Advertiser pays 1 DZIT proposal fee to submit an ad\n"
            "3. Platform receives 1 DZIT as proposal fee\n"
            "4. Node owners earn 50% of payout in DZIT\n"
            "5. DZIT spent on other 1BZ services (CopyGuard, IPVault, SmartPDF, Fax)\n"
            "6. Cycle repeats — DZIT circulates through the entire 1BZ ecosystem\n\n"
            "**Why BizChannel Uses 24-Hour OTP (Not 5-Minute):**\n"
            "Standard BizNode operations use 5-minute OTP windows. BizChannel uses 24-hour "
            "windows because ad proposals involve significant budget decisions, advertisers may "
            "need time to review their submission, and cross-timezone team coordination is common.\n\n"
            "**Dual Verification Protocol:**\n"
            "Step 1: OTP sent to registered email\n"
            "Step 2: User confirms via Telegram bot (/bo confirm <id> <otp>)\n"
            "Step 3: System verifies BOTH:\n"
            "    - OTP hash matches (SHA-256)\n"
            "    - Telegram chat_id matches registered account\n"
            "This proves the same person controls both the email and Telegram account.\n\n"
            "**No Silent Deductions — DZIT is NEVER deducted without explicit OTP confirmation:**\n"
            "1. Balance check: dzit_balances.credit >= 1.0\n"
            "2. OTP sent to email\n"
            "3. User must actively confirm\n"
            "4. Only after confirmation: 1 DZIT deducted from dzit_balances\n"
            "5. Transaction logged in dzit_transactions with reference\n\n"
            "Purchase DZIT at: https://dzit.1bz.biz"
        ),
        "tags": ["support", "bizchannel", "dzit", "otp", "security"],
        "keywords": ["dzit credits bizchannel", "otp security", "24 hour otp",
                     "dual verification", "no silent deductions", "dzit proposal fee",
                     "bizchannel dzit", "bizchannel otp", "dzit balance"],
    },

    {
        "title": "BizChannel 15-Day Monitoring Protocol",
        "content": (
            "After a campaign is published, BizChannel tracks engagement daily for 15 days "
            "before releasing payouts to node owners.\n\n"
            "**Why 15 Days?**\n"
            "15 days provides enough data to distinguish real engagement from initial curiosity "
            "spikes. An ad might get views on day 1 from novelty, but sustained engagement "
            "over 15 days proves genuine audience interest.\n\n"
            "**Daily Metrics Tracked (6 metrics):**\n"
            "- active_members: Users who opened the group today (Telegram group stats)\n"
            "- messages_count: Messages sent in the group today\n"
            "- ad_views: How many users saw the ad post (post analytics)\n"
            "- ad_clicks: How many clicked the ad link (URL click tracking)\n"
            "- handle_interactions: /handle bot command usage in the group\n"
            "- activity_score: (active_members / total_members) * 100\n\n"
            "**Monitoring Timeline:**\n"
            "Day 0:   Campaign published, ad posted in groups\n"
            "Day 1:   First monitoring check — baseline metrics\n"
            "Day 2-7: Daily checks — establishing engagement pattern\n"
            "Day 8-14: Daily checks — sustained engagement verification\n"
            "Day 15:  Final check — monitoring complete\n\n"
            "**What Happens After 15 Days:**\n"
            "1. Monitoring status set to 'completed'\n"
            "2. All daily metrics aggregated\n"
            "3. AD_INCENTIVE_PAID event published\n"
            "4. Incentive worker credits payouts:\n"
            "   - bzeusd_payout to provider's bc_wallets\n"
            "   - dzit_payout to provider's dzit_balances\n"
            "   - Transactions logged as ad_incentive_bzeusd and ad_incentive_dzit\n"
            "5. Pro nodes flagged for Ed25519-signed PDF update packet\n"
            "6. Campaign continues running — ads stay posted for full duration (default 365 days)\n\n"
            "Monitoring data stored in bc_ad_monitoring table (11 columns)."
        ),
        "tags": ["support", "bizchannel", "monitoring", "15-day", "tracking"],
        "keywords": ["15 day monitoring", "monitoring protocol", "bizchannel monitoring",
                     "daily metrics", "activity tracking", "engagement monitoring",
                     "ad monitoring", "monitoring timeline", "what happens after monitoring"],
    },

    {
        "title": "BizChannel KB Contribution Rewards",
        "content": (
            "Node owners who contribute to the BizNode Knowledge Base through their bots "
            "earn additional rewards when their groups reach critical mass.\n\n"
            "**Eligibility Requirements:**\n"
            "- Group must have 10,000+ total members\n"
            "- Bot must be actively responding to /handle commands in the group\n"
            "- Interactions tracked in bc_ad_monitoring.handle_interactions\n\n"
            "**Reward Formula:**\n"
            "    tiers_earned = handle_interactions // 10,000\n"
            "    bzeusd_reward = tiers_earned * $5.00\n"
            "    dzit_reward = tiers_earned * 5.00 DZIT\n\n"
            "**Reward Tiers:**\n"
            "- 5,000 /handle interactions = 0 tiers = $0 + 0 DZIT (below threshold)\n"
            "- 10,000 interactions = 1 tier = $5 BZeUSD + 5 DZIT\n"
            "- 25,000 interactions = 2 tiers = $10 BZeUSD + 10 DZIT\n"
            "- 100,000 interactions = 10 tiers = $50 BZeUSD + 50 DZIT\n\n"
            "**Why This Exists:**\n"
            "KB contribution rewards incentivize node owners to run helpful, engaging bots "
            "that genuinely serve community members — not just post ads. The more your bot "
            "helps users through /handle interactions, the more bonus income you earn.\n\n"
            "These rewards are paid on top of the regular campaign payouts (50% BZeUSD + 50% DZIT)."
        ),
        "tags": ["support", "bizchannel", "kb-rewards", "incentives", "node-owner"],
        "keywords": ["kb contribution rewards", "handle interactions", "bonus rewards",
                     "bizchannel rewards", "10000 interactions", "kb rewards formula",
                     "node owner bonus", "bizchannel incentives"],
    },

    {
        "title": "BizChannel Bot Commands — Complete Reference",
        "content": (
            "All BizChannel commands use the /bo prefix in Telegram:\n\n"
            "**Commands for All Users:**\n"
            "- /bo — Show BizChannel marketplace help menu\n"
            "- /bo submit <title> — Submit an ad proposal (requires DZIT balance >= 1)\n"
            "  Example: /bo submit DeFi Token Launch\n"
            "- /bo confirm <id> <otp> — Confirm proposal with OTP from email (24h validity)\n"
            "  Example: /bo confirm 42 482913\n"
            "- /bo quote <id> <amount> — Submit a quote for a proposal (node owners)\n"
            "  Example: /bo quote 42 200\n"
            "- /bo status <id> — Check proposal or campaign status with quote details\n"
            "  Example: /bo status 42\n\n"
            "**Admin/Owner Commands:**\n"
            "- /bo accept <id> — Accept the consolidated quote and publish campaign\n"
            "- /bo campaigns — List all active campaigns with monitoring status\n"
            "- /bo stats — Show aggregate marketplace statistics (proposals, campaigns, payouts)\n\n"
            "**Typical Flow:**\n"
            "1. Advertiser: /bo submit Summer Sale Promotion\n"
            "2. System sends OTP to registered email\n"
            "3. Advertiser: /bo confirm 1 483729\n"
            "4. 1 DZIT deducted, proposal broadcast to matching nodes\n"
            "5. Node owners: /bo quote 1 100\n"
            "6. Harmonious scoring evaluates each quote\n"
            "7. Advertiser: /bo accept 1\n"
            "8. Campaign published, 15-day monitoring starts\n"
            "9. After 15 days, incentives paid (50% BZeUSD + 50% DZIT)\n\n"
            "**Requirements:** Must have registered email and at least 1 DZIT credit to submit. "
            "OTP must be confirmed within 24 hours."
        ),
        "tags": ["support", "bizchannel", "commands", "bot", "reference"],
        "keywords": ["bizchannel commands", "bo commands", "bo submit", "bo confirm",
                     "bo quote", "bo accept", "bo status", "bo campaigns", "bo stats",
                     "bizchannel bot commands reference"],
    },

    {
        "title": "BizChannel Troubleshooting — Common Issues and Fixes",
        "content": (
            "Common BizChannel issues and how to fix them:\n\n"
            "**'insufficient_dzit' status when submitting proposal:**\n"
            "Your DZIT balance is less than 1. Purchase DZIT on DX exchange (https://dx.1bz.biz) "
            "or earn credits through other 1BZ services.\n\n"
            "**OTP not received after /bo submit:**\n"
            "Check your spam folder. Verify that SMTP is configured correctly in your node's .env. "
            "The OTP is sent to your registered email address.\n\n"
            "**No quotes received after 24 hours:**\n"
            "No bots are registered in your business category. Admin needs to register more bots "
            "or change the proposal category to 'general'.\n\n"
            "**Harmonious score = 0 (all quotes rejected):**\n"
            "The group has zero daily active members. Node owner needs to build an active community "
            "before they can earn from BizChannel.\n\n"
            "**Campaign not publishing after quotes accepted:**\n"
            "The advertiser must explicitly run /bo accept <id>. Campaigns do not auto-publish.\n\n"
            "**Monitoring not running / no daily checks:**\n"
            "The scheduler is not configured. Add 'bizchannel_daily_monitoring' job to "
            "automation/scheduler.py (daily at 6 AM).\n\n"
            "**Payouts not processing after 15 days:**\n"
            "The incentive worker may not be running. Check that runner.py is active and "
            "processing AD_INCENTIVE_PAID events.\n\n"
            "**API 500 errors on BizChannel endpoints:**\n"
            "Database tables may be missing. Run:\n"
            "    python -c \"from bizchannel.database.models import init_bizchannel_db; init_bizchannel_db()\"\n\n"
            "**Health Checks:**\n"
            "- API: curl http://localhost:7778/api/bizchannel/health\n"
            "- Stats: curl http://localhost:7778/api/bizchannel/marketplace/stats\n"
            "- Dashboard: http://localhost:7777/admin/bizchannel\n\n"
            "**Log Files:**\n"
            "- BizChannel API: logs/bizchannel.log\n"
            "- Workers: logs/bizchannel_workers.log\n"
            "- Bot: logs/bot.log (/bo command processing)"
        ),
        "tags": ["support", "bizchannel", "troubleshooting", "errors", "fixes"],
        "keywords": ["bizchannel troubleshooting", "bizchannel errors", "insufficient dzit",
                     "otp not received", "no quotes", "harmonious score zero",
                     "campaign not publishing", "monitoring not running", "bizchannel fix",
                     "bizchannel health check", "bizchannel logs"],
    },

    # ── Tier Enforcement & Gating ────────────────────────────────────────────

    {
        "title": "Tier Enforcement & Gating — Basic vs Pro Restrictions",
        "content": (
            "BizNode enforces tier-based access control across the bot, dashboard API, "
            "and route loading.\n\n"
            "**Bot Command Gating:**\n"
            "The following bot commands are Pro-only:\n"
            "- /crypto — cryptocurrency features\n"
            "- /affiliate — affiliate link management\n"
            "- /bizbrain — AI business profile generator\n"
            "- /bizchannel — marketplace commands\n"
            "If a Basic user tries these commands, the bot returns a friendly upgrade "
            "message explaining the feature is Pro-only with a link to purchase.\n\n"
            "**Dashboard API Gating:**\n"
            "22 dashboard API endpoints are gated with the @require_tier(TierLevel.PRO) "
            "decorator. Basic users calling these endpoints receive a 403 response "
            "with an upgrade prompt.\n\n"
            "**BizChannel Routes:**\n"
            "BizChannel FastAPI routes are conditionally loaded only when the node "
            "is running on a Pro tier license. On Basic tier, BizChannel endpoints "
            "are not registered at all.\n\n"
            "**Email Verification Shortcuts:**\n"
            "- Basic users can type 'skip' to bypass email verification during onboarding\n"
            "- OTP auto-skips if SMTP is not configured (prevents stuck customers)\n\n"
            "This ensures Basic users are never blocked by missing email setup "
            "while Pro users get the full feature set."
        ),
        "tags": ["support", "tier", "gating", "enforcement", "pro", "basic"],
        "keywords": ["tier enforcement", "gating", "require_tier", "pro only", "basic restrictions",
                     "upgrade message", "bot command gating", "api gating", "skip email",
                     "otp auto skip", "bizchannel routes"],
    },

    # ── Client Registration System ───────────────────────────────────────────

    {
        "title": "Client Registration System — VPS API for Node Tracking",
        "content": (
            "BizNode includes a client registration system that stores bot details "
            "on the VPS for group invites and support coordination.\n\n"
            "**VPS API Endpoint:**\n"
            "    POST https://biznode.1bz.biz/api_client_register.php\n\n"
            "**What it stores:**\n"
            "- chat_id: Telegram chat ID of the bot owner\n"
            "- email: Owner's email address\n"
            "- bot_name: The Telegram bot username\n\n"
            "**Purpose:**\n"
            "- Group invites: Admin can invite registered clients to Telegram groups\n"
            "- Support coordination: Link support tickets to specific bot installations\n"
            "- Network tracking: Know which nodes are active in the BizNode network\n\n"
            "Registration happens automatically during the setup wizard. "
            "No manual action is required from the client."
        ),
        "tags": ["support", "registration", "client", "vps", "api"],
        "keywords": ["client registration", "api_client_register", "register bot", "chat_id",
                     "group invites", "support coordination", "node tracking", "vps api"],
    },

    # ── Installation Fixes (v1.2+) ───────────────────────────────────────────

    {
        "title": "Installation Fixes (v1.2+) — Watchdog, Ollama, Docker Guards",
        "content": (
            "Version 1.2+ includes several installation reliability fixes:\n\n"
            "**Watchdog Skipped Status:**\n"
            "Non-critical services (e.g. BizChannel, video automation) now report "
            "'skipped' status instead of 'failed' when they are not installed or not "
            "applicable to the current tier. This prevents false alarms in the watchdog "
            "daemon and reduces unnecessary restart attempts.\n\n"
            "**Ollama Model Auto-Detect:**\n"
            "The system no longer hardcodes the Ollama model name. Instead, it queries "
            "Ollama's /api/tags endpoint to detect which models are installed and uses "
            "the first available model. This prevents 404 errors when a different model "
            "name is installed (e.g. qwen3:4b vs qwen3.5:4b).\n\n"
            "**Docker Safety Guards:**\n"
            "Docker commands now check whether Docker Desktop is installed and running "
            "before attempting container operations. If Docker is not available, the "
            "system gracefully skips Docker-dependent services instead of crashing.\n\n"
            "**Support Email Service:**\n"
            "Improved error handling for SMTP failures — the support email service "
            "now retries with exponential backoff and logs failures without blocking "
            "other services.\n\n"
            "**BizChannel Pro-Only Cleanup:**\n"
            "BizChannel files and routes are now cleanly excluded from Basic tier "
            "packages. Previously, some BizChannel imports could cause errors on "
            "Basic installations."
        ),
        "tags": ["support", "installation", "fixes", "watchdog", "ollama", "docker"],
        "keywords": ["installation fixes", "watchdog skipped", "ollama auto detect", "docker guards",
                     "support email", "bizchannel cleanup", "v1.2", "non-critical services",
                     "model auto detect", "docker safety"],
    },

    # ── Blog Platform ────────────────────────────────────────────────────────

    {
        "title": "Blog Platform — blog.1bz.biz Publishing System",
        "content": (
            "BizNode includes an integrated blog platform at blog.1bz.biz for "
            "content marketing and SEO.\n\n"
            "**Technical Stack:**\n"
            "- PHP + MySQL backend\n"
            "- Local folder: C:\\nodesrunning\\blog-site\\\n"
            "- VPS: /home/1bzbiz/public_html/blog/\n"
            "- Apache vhost: /etc/httpd/conf.d/blog.1bz.biz.conf\n\n"
            "**Publishing API:**\n"
            "    POST https://blog.1bz.biz/api/publish.php\n"
            "    Header: api_key (required for authentication)\n\n"
            "**Posting Limits by Tier:**\n"
            "- Admin: Unlimited posts\n"
            "- Pro: 5 posts per month\n"
            "- Basic: 1 post per month\n\n"
            "**Auto Cross-Posting:**\n"
            "When a post is published, it is automatically cross-posted to:\n"
            "- Dev.to (@biznode)\n"
            "- Hashnode (1bz.hashnode.dev)\n\n"
            "Cross-posting happens via each platform's API and includes proper "
            "canonical URL linking back to the original blog post.\n\n"
            "**Usage:**\n"
            "Posts can be submitted via the publishing API or through the campaign "
            "engine's automated content generation pipeline."
        ),
        "tags": ["support", "blog", "publishing", "content", "cross-posting"],
        "keywords": ["blog platform", "blog.1bz.biz", "publishing api", "cross posting",
                     "dev.to", "hashnode", "posting limits", "content marketing",
                     "blog api", "publish.php"],
    },

    # ── Campaign Engine ──────────────────────────────────────────────────────

    {
        "title": "Campaign Engine — Automated Multi-Platform Posting",
        "content": (
            "The BizNode campaign engine automates content creation and distribution "
            "across multiple platforms.\n\n"
            "**How It Works:**\n"
            "The scheduler calls run_daily_campaign() which generates AI content "
            "and posts it to all configured platforms in a single run.\n\n"
            "**Configured Platforms:**\n"
            "- Telegram: @biznode_updates channel\n"
            "- Twitter: @shashikanthram\n"
            "- Dev.to: @biznode\n"
            "- Hashnode: 1bz.hashnode.dev\n"
            "- Blog: blog.1bz.biz\n\n"
            "**Scheduler:**\n"
            "The campaign scheduler runs daily content generation at 7 AM, "
            "order processing every 4 hours, and a weekly summary report on "
            "Monday at 9 AM.\n\n"
            "**Key Files:**\n"
            "- marketingteam/campaign_engine.py — core campaign logic\n"
            "- marketingteam/campaign_scheduler.py — scheduling configuration\n"
            "- marketingteam/generate_reports.py — AI content generation\n\n"
            "**Note:** The campaign engine is an admin-only feature and is not "
            "included in basic/ or pro/ packages."
        ),
        "tags": ["support", "campaign", "marketing", "automation", "admin"],
        "keywords": ["campaign engine", "run_daily_campaign", "multi-platform posting",
                     "telegram updates", "twitter posting", "dev.to", "hashnode",
                     "automated posting", "content generation", "campaign scheduler"],
    },

    # ── Support Dashboard ────────────────────────────────────────────────────

    {
        "title": "Support Dashboard — Ticket Management & Health Check",
        "content": (
            "The /support page provides a complete support ticket management interface.\n\n"
            "**Features:**\n"
            "- Ticket List: View all support tickets with status, priority, and timestamps\n"
            "- Stats Bar: Real-time counts of open, pending, and resolved tickets\n"
            "- Filters: Filter tickets by status, priority, date range, or keyword search\n"
            "- Reply System: Respond to tickets directly from the dashboard with formatted replies\n"
            "- Health Check: Monitor service health (Ollama, Qdrant, PostgreSQL, bot) from the support page\n\n"
            "**Ollama Analyzer:**\n"
            "The support dashboard integrates with Ollama to automatically categorize "
            "incoming tickets by topic, urgency, and suggested resolution. The analyzer "
            "prompt has been tuned to prevent hallucinated metrics — it only reports "
            "data that actually exists in the ticket.\n\n"
            "**Access:**\n"
            "Navigate to http://localhost:7777/support in the dashboard. "
            "The support page is available to node owners and admins."
        ),
        "tags": ["support", "dashboard", "tickets", "health-check", "analyzer"],
        "keywords": ["support dashboard", "ticket management", "support page", "ticket list",
                     "stats bar", "filters", "reply system", "health check", "ollama analyzer",
                     "ticket categorization", "/support"],
    },

    # ── Nodemonitor Integration ──────────────────────────────────────────────

    {
        "title": "Nodemonitor Integration — LLM Gateway, Qdrant KB, BizMesh VPN",
        "content": (
            "BizNode integrates with the Nodemonitor service for centralized AI model "
            "access, knowledge base management, and secure email delivery.\n\n"
            "**LLM Gateway:**\n"
            "The Nodemonitor provides access to 22+ language models through a unified API. "
            "The fallback chain is: Ollama (local) -> OpenRouter (cloud) -> Claude (Anthropic). "
            "If the local Ollama model fails, the request is automatically routed to the next "
            "provider in the chain.\n\n"
            "**Qdrant KB Management:**\n"
            "Nodemonitor manages shared Qdrant knowledge base collections that can be "
            "accessed by all nodes in the network. This enables cross-node knowledge sharing.\n\n"
            "**BizMesh VPN:**\n"
            "BizMesh is a WireGuard-based VPN (subnet 10.50.0.0/24) that provides secure "
            "email delivery between nodes. All inter-node email traffic is encrypted and "
            "routed through the mesh network.\n\n"
            "**API Gateway:**\n"
            "The Nodemonitor API runs at http://1bz.biz:7333/ with 77 routes on FastAPI. "
            "Authentication uses a master API key via header.\n\n"
            "**Integration Reference:**\n"
            "Full documentation available in NODEMONITOR_INTEGRATION.md in the project root."
        ),
        "tags": ["support", "nodemonitor", "llm", "gateway", "qdrant", "vpn", "bizmesh"],
        "keywords": ["nodemonitor", "llm gateway", "22 models", "fallback chain", "openrouter",
                     "claude", "bizmesh", "wireguard", "vpn", "email security", "api gateway",
                     "1bz.biz:7333", "qdrant kb", "cross-node"],
    },

    # === 7-Tier Marketplace System ===
    {
        "title": "BizNode 7-Tier System — Pricing & Features",
        "content": (
            "BizNode offers 7 commercial tiers:\n\n"
            "BASIC ($20) — 1 bot, API-hosted, AI agent identity, 10 DZIT credits. No software install needed.\n"
            "STANDARD ($50) — 5 bots, API-hosted, same features as Basic but with multi-bot support.\n"
            "PRO ($100) — 5 bots, API-hosted, escrow payments enabled, earn DZIT for published services, 1 published workflow.\n"
            "BIZPLUS ($150) — 5 bots, API-hosted, everything in Pro plus up to 5 published workflows for 1 year.\n"
            "BIZMAX ($200) — 1 bot, local node software installation, own Ollama LLM + Qdrant KB, plus all BizPlus features.\n"
            "BIZNODE ($499) — 5 bots, local node + USB hardware key, full platform with all features.\n"
            "1BZNODE ($1500) — 5 bots, local node + USB, everything in BizNode plus 1500 bonus DZIT credits.\n\n"
            "All tiers include: DZID activation at dzit.1bz.biz, 10 free DZIT credits, AI agent identity registration, "
            "and smart contract account virtual ID.\n\n"
            "API-only tiers ($20-$150) require NO software installation — everything runs through BizNode's hosted infrastructure. "
            "Node-install tiers ($200+) include downloadable software with local AI and database."
        ),
        "tags": ["support", "pricing", "tier", "faq"],
        "keywords": ["tier", "pricing", "basic", "standard", "pro", "bizplus", "bizmax", "biznode", "1bznode", "cost", "price"],
    },
    {
        "title": "API-Only Tiers — No Install Required",
        "content": (
            "The first 4 tiers (Basic $20, Standard $50, Pro $100, BizPlus $150) are API-only. "
            "This means NO software installation is needed. Your AI agent runs on BizNode's infrastructure.\n\n"
            "How it works:\n"
            "1. Purchase your tier via Stripe or crypto\n"
            "2. Register your Telegram bot token via @biznode_bot /setup command\n"
            "3. Complete the business questionnaire (6 questions about your business)\n"
            "4. Your bot goes live immediately — BizNode hosts it for you\n\n"
            "BizNode provides: shared LLM (AI model), shared knowledge base, tool execution, "
            "and Telegram bot hosting. Your business info is isolated — only your bot sees your data.\n\n"
            "Rate limit: 10 messages per hour per user interacting with your bot.\n"
            "Daily reports: emailed to you every day with query stats, topics, and usage."
        ),
        "tags": ["support", "setup", "tier", "faq", "hosted"],
        "keywords": ["api-only", "hosted", "no install", "basic", "standard", "pro", "bizplus", "setup"],
    },
    {
        "title": "Node-Install Tiers — Local Software",
        "content": (
            "Tiers BizMax ($200), BizNode ($499), and 1BZNode ($1500) include local node software.\n\n"
            "After purchase, you receive an installer via email. The setup wizard guides you through:\n"
            "- Choosing your database (SQLite, MySQL, or PostgreSQL)\n"
            "- Installing Ollama (local AI model) or connecting to shared LLM\n"
            "- Installing Qdrant (local knowledge base) or using shared KB\n"
            "- Selecting your industry for customized features\n"
            "- Registering with the BizNode network\n\n"
            "BizNode ($499) and 1BZNode ($1500) also require a USB hardware key for license validation.\n\n"
            "Local nodes run their own dashboard at http://localhost:7777 (or custom port) "
            "with full control over AI models, knowledge base, and bot configuration."
        ),
        "tags": ["support", "setup", "tier", "installation"],
        "keywords": ["bizmax", "biznode", "1bznode", "install", "local", "node", "usb", "ollama", "qdrant"],
    },

    # === Tool Marketplace ===
    {
        "title": "Tool Marketplace — Publishing & Discovery",
        "content": (
            "The BizNode Tool Marketplace lets AI agents publish tools that other agents can discover and call.\n\n"
            "How it works:\n"
            "1. Your bot auto-detects its installed tools (email, payment, database, etc.)\n"
            "2. You choose which tools to publish as public, registered, or private\n"
            "3. Set pricing per tool call (free for info tools, DZIT/BZeUSD for service tools)\n"
            "4. Published tools appear on registry.1bz.biz for global discovery\n"
            "5. Other bots can search and call your tools via the BizNode proxy\n\n"
            "Tool IDs follow the format BZTL-XXXXX. Each tool has a JSON schema describing "
            "its input parameters, output format, cost, and access level.\n\n"
            "Free tools (cost=0) are called directly. Paid tools go through escrow — "
            "payment is held until the service is delivered successfully.\n\n"
            "API endpoints: POST /api/tools/publish, GET /api/tools, GET /api/tools/search, "
            "POST /api/tools/{tool_id}/call, POST /api/tools/auto-detect"
        ),
        "tags": ["support", "marketplace", "tools", "faq"],
        "keywords": ["tool", "marketplace", "publish", "discover", "call", "registry", "BZTL", "escrow"],
    },
    {
        "title": "How to Publish Tools",
        "content": (
            "Publishing tools makes your bot's capabilities available to other AI agents.\n\n"
            "Step 1: Auto-detect your tools\n"
            "  Call POST /api/tools/auto-detect to scan your node for installed tools.\n"
            "  Returns a list of tools with their schemas.\n\n"
            "Step 2: Choose what to publish\n"
            "  Select which tools to make public. Set cost per call (0 = free).\n\n"
            "Step 3: Publish\n"
            "  Call POST /api/tools/publish with your agent_id and tools list.\n"
            "  Each tool gets a unique BZTL-XXXXX ID.\n\n"
            "Step 4: Sync to registry\n"
            "  Call POST /api/tools/sync-registry to push your tools to registry.1bz.biz.\n"
            "  Other agents can now find and call your tools.\n\n"
            "First publish is FREE. Tool updates cost 1 DZIT each.\n"
            "Requires Pro tier or higher for escrow-enabled paid tools."
        ),
        "tags": ["support", "marketplace", "tools", "how-to"],
        "keywords": ["publish", "tools", "auto-detect", "sync", "registry", "how to"],
    },
    {
        "title": "Tool Cost Calculator",
        "content": (
            "The cost calculator helps you estimate the total cost of calling multiple tools in a workflow chain.\n\n"
            "Usage: GET /api/tools/cost-calculator?tool_ids=BZTL-XXXXX,BZTL-YYYYY\n\n"
            "Returns: total DZIT cost, total BZeUSD cost, and per-tool breakdown.\n\n"
            "Example response:\n"
            "  total_dzit: 5.0\n"
            "  total_bzeusd: 0.0\n"
            "  tools: [{tool_id: BZTL-ABC12, name: send_email, cost: 2, currency: DZIT}, ...]\n\n"
            "Use this before executing workflows to ensure you have sufficient balance."
        ),
        "tags": ["support", "marketplace", "tools", "faq"],
        "keywords": ["cost", "calculator", "workflow", "chain", "DZIT", "BZeUSD", "estimate"],
    },

    # === Hosted Agents ===
    {
        "title": "Hosted Agents — Your AI Bot Without Installation",
        "content": (
            "Hosted agents are AI bots that run on BizNode's infrastructure. "
            "Available for all tiers, but especially designed for API-only tiers ($20-$150).\n\n"
            "When you register a hosted agent:\n"
            "1. You get a unique agent ID (BZHA-XXXXX)\n"
            "2. Your bot token is stored securely by BizNode\n"
            "3. BizNode runs your bot — polls Telegram, generates AI responses\n"
            "4. Your business KB is isolated (only your bot sees your data)\n"
            "5. You receive daily email reports with query stats\n\n"
            "Your bot answers customer questions using:\n"
            "- Shared LLM (AI model hosted by BizNode)\n"
            "- Your business knowledge base (seeded from your questionnaire answers)\n"
            "- Published tools (email, payment, etc.)\n\n"
            "API: POST /api/hosted-agents/register, GET /api/hosted-agents/{agent_id}"
        ),
        "tags": ["support", "hosted", "agent", "setup", "faq"],
        "keywords": ["hosted", "agent", "BZHA", "bot", "no install", "API", "register"],
    },
    {
        "title": "Bot Onboarding — Business Questionnaire",
        "content": (
            "After purchasing a tier and registering your bot, you need to teach your AI assistant about your business.\n\n"
            "Two ways to complete the questionnaire:\n\n"
            "1. Via Email: Reply to the welcome email with numbered answers (1-6)\n"
            "2. Via Bot: Send /start to your bot — it will ask 6 questions one by one\n\n"
            "The 6 questions:\n"
            "Q1: What is your business name and what do you do?\n"
            "Q2: What services or products do you offer and their prices?\n"
            "Q3: Who is your target audience?\n"
            "Q4: What are your business hours and location?\n"
            "Q5: Most common customer questions (with answers)?\n"
            "Q6: Contact information (email, phone, website, social media)?\n\n"
            "Each answer is immediately added to your bot's knowledge base.\n"
            "Update anytime: send /addinfo followed by new information to your bot.\n\n"
            "IMPORTANT: Do NOT include sensitive data (passwords, bank accounts, SSN, private keys)."
        ),
        "tags": ["support", "setup", "onboarding", "faq", "how-to"],
        "keywords": ["questionnaire", "onboarding", "business", "questions", "setup", "addinfo", "knowledge base"],
    },
    {
        "title": "Daily Bot Reports",
        "content": (
            "Every hosted bot owner receives a daily email report at 11 PM UTC.\n\n"
            "The report includes:\n"
            "- Total queries received that day\n"
            "- Number of unique users who messaged your bot\n"
            "- Top topics discussed (grouped by keywords)\n"
            "- Last 20 queries with timestamps and user names\n\n"
            "Reports are sent to the email address used during registration.\n"
            "If no queries were received that day, no report is sent.\n\n"
            "This helps you understand what your customers are asking about "
            "and improve your bot's knowledge base accordingly."
        ),
        "tags": ["support", "reports", "hosted", "faq"],
        "keywords": ["daily", "report", "email", "queries", "stats", "usage"],
    },
    {
        "title": "Rate Limits for Hosted Bots",
        "content": (
            "Each user interacting with a hosted bot can send up to 10 messages per hour.\n\n"
            "This is a sliding window limit — it counts messages in the last 60 minutes.\n"
            "If a user exceeds the limit, they receive a message: "
            "'You\\'ve reached the message limit (10 per hour). Please try again later.'\n\n"
            "Rate limits ensure fair usage across all hosted agents and prevent abuse.\n"
            "The limit applies per user per bot — different users each get their own 10/hr allowance.\n\n"
            "Bot owners are not subject to rate limits when using /addinfo or /start commands."
        ),
        "tags": ["support", "hosted", "faq", "limits"],
        "keywords": ["rate limit", "10 per hour", "messages", "limit", "fair usage"],
    },

    # === Verification & Registry ===
    {
        "title": "Agent Verification — CA Verified Badge",
        "content": (
            "All registered agents start as 'unverified' on the BizNode registry.\n"
            "To get a CA Verified trust badge, you need to request verification.\n\n"
            "Verification process:\n"
            "1. Call POST /api/agent-registry/request-verification/{agent_id}\n"
            "2. Pay 10 BZeUSD (on-chain tx hash or deduct from account balance)\n"
            "3. Your application is sent to ca@1bz.biz for professional review\n"
            "4. CA team verifies your business information\n"
            "5. Status updated to 'verified' with CA reference number\n\n"
            "Cost: 10 BZeUSD for both legal entities and individual agents.\n\n"
            "Verified agents get:\n"
            "- 'CA Verified' trust badge on registry.1bz.biz\n"
            "- Higher visibility in tool marketplace search results\n"
            "- Increased trust from other agents calling your tools\n\n"
            "Verification is optional but recommended for serious businesses."
        ),
        "tags": ["support", "verification", "registry", "faq"],
        "keywords": ["verification", "CA", "verified", "badge", "10 BZeUSD", "trust", "registry"],
    },

    # === DZIT & Payments ===
    {
        "title": "DZIT Credits — How They Work",
        "content": (
            "DZIT is the utility token for the BizNode ecosystem.\n\n"
            "Every registered agent receives 10 free DZIT credits.\n"
            "1BZNode tier gets 1500 bonus DZIT (worth $1500 in services).\n\n"
            "DZIT is used for:\n"
            "- Calling paid tools published by other agents\n"
            "- Publishing tool updates (1 DZIT per update)\n"
            "- Marketplace transactions between agents\n"
            "- Agent verification (10 BZeUSD, not DZIT)\n\n"
            "Earn DZIT by:\n"
            "- Publishing tools that others call (Pro tier and above)\n"
            "- Providing services through the marketplace\n"
            "- Completing workflows for other agents\n\n"
            "Buy more DZIT at dzit.1bz.biz or earn them through the marketplace.\n"
            "Check balance: GET /api/hosted-agents/{agent_id}/balance"
        ),
        "tags": ["support", "dzit", "credits", "payment", "faq"],
        "keywords": ["DZIT", "credits", "balance", "earn", "spend", "token", "payment"],
    },
    {
        "title": "Escrow Payments Between Agents",
        "content": (
            "When a paid tool is called, BizNode acts as escrow.\n\n"
            "Flow:\n"
            "1. Agent A calls Agent B's paid tool (e.g., 5 DZIT)\n"
            "2. BizNode checks Agent A's balance (must have >= 5 DZIT)\n"
            "3. 5 DZIT deducted from Agent A's balance (held in escrow)\n"
            "4. Tool executes on Agent B's node\n"
            "5. On success: 5 DZIT credited to Agent B\n"
            "6. On failure: 5 DZIT refunded to Agent A\n\n"
            "Escrow is available for Pro tier ($100) and above.\n"
            "Basic and Standard tiers can only call free tools (cost=0).\n\n"
            "All transactions are logged for audit purposes."
        ),
        "tags": ["support", "escrow", "payment", "marketplace", "faq"],
        "keywords": ["escrow", "payment", "DZIT", "BZeUSD", "refund", "transaction", "balance"],
    },

    # === Legal & Terms ===
    {
        "title": "Service Terms & Disclaimers",
        "content": (
            "BizNode services are provided AS IS and AS AVAILABLE without warranties.\n\n"
            "KEY TERMS:\n\n"
            "NO LIABILITY: BizNode, 1BZ DZIT DAO LLC, its owners and affiliates shall NOT be "
            "held liable for any damages arising from service use, including:\n"
            "- Technical failures, server outages, software bugs\n"
            "- Natural disasters, force majeure events\n"
            "- Loss of data, revenue, or business opportunities\n"
            "- Inaccurate AI responses\n"
            "- Unauthorized access to data\n\n"
            "SERVICE CANCELLATION: BizNode reserves the right to suspend or cancel any account "
            "at any time, without prior notice, without stating any reason, and without refund obligation.\n\n"
            "REFUNDS: Available within 24 hours of purchase only if you have not used the service.\n\n"
            "Full terms at: biznode.1bz.biz/terms\n"
            "Legal info at: biznode.1bz.biz/legal"
        ),
        "tags": ["support", "legal", "terms", "disclaimer", "faq"],
        "keywords": ["terms", "disclaimer", "liability", "cancellation", "refund", "legal", "AS IS"],
    },
    {
        "title": "Information Disclosure Policy",
        "content": (
            "When you provide business information to your AI agent, please be aware:\n\n"
            "- Your information becomes part of your bot's knowledge base\n"
            "- Your bot WILL share this information with anyone who messages it\n"
            "- Do NOT include: passwords, bank accounts, SSN, private keys, or confidential client data\n"
            "- You are solely responsible for the accuracy of information provided\n"
            "- BizNode stores data securely but cannot guarantee against third-party attacks\n\n"
            "Update your bot's knowledge anytime with /addinfo command or by emailing biznode@1bz.biz.\n"
            "To remove information, contact support."
        ),
        "tags": ["support", "legal", "privacy", "faq"],
        "keywords": ["disclosure", "privacy", "information", "sensitive", "data", "security"],
    },

    # === Setup & Commands ===
    {
        "title": "The /setup Command — Complete Guide",
        "content": (
            "The /setup command in @biznode_bot starts the node setup wizard.\n\n"
            "For API-only tiers (Basic, Standard, Pro, BizPlus):\n"
            "  Step 1: Choose tier → Step 2: Choose industry → Review & confirm\n"
            "  (Database, LLM, and Qdrant are automatically set to hosted/shared)\n\n"
            "For node-install tiers (BizMax, BizNode, 1BZNode):\n"
            "  Step 1: Choose tier\n"
            "  Step 2: Choose database (SQLite/MySQL/PostgreSQL)\n"
            "  Step 3: Choose LLM (Own Ollama / Shared gateway)\n"
            "  Step 4: Choose Qdrant (Own / Shared)\n"
            "  Step 5: Choose industry\n"
            "  Step 6: Review & confirm\n\n"
            "After confirmation, an email is required. The installer files are sent to your email.\n"
            "8 industry options: General, Legal, Medical, Real Estate, Finance, Education, Retail, Consulting."
        ),
        "tags": ["support", "setup", "commands", "how-to"],
        "keywords": ["setup", "wizard", "command", "configure", "industry", "tier"],
    },
    {
        "title": "The /addinfo Command",
        "content": (
            "Use /addinfo in your customer bot to add information to your bot's knowledge base.\n\n"
            "Syntax: /addinfo <your business information>\n\n"
            "Examples:\n"
            "  /addinfo We offer free shipping on orders over $50\n"
            "  /addinfo Our return policy: 30 days, no questions asked\n"
            "  /addinfo Holiday hours: Dec 24 close at 2pm, Dec 25 closed\n\n"
            "Each /addinfo message is embedded and stored in your bot's KB namespace. "
            "Your bot will use this information when answering customer questions.\n\n"
            "There is no limit to how many /addinfo entries you can add."
        ),
        "tags": ["support", "commands", "how-to", "knowledge-base"],
        "keywords": ["addinfo", "add", "information", "knowledge base", "update", "command"],
    },

    # === 1BZ Ecosystem Shared KB (shared across ALL bots by default) ===
    {
        "title": "1BZ — Decentralized AI Business Infrastructure",
        "content": (
            "1BZ (1bz.biz) is a decentralized AI business infrastructure platform. "
            "It connects multiple specialized services into one ecosystem:\n\n"
            "BizNode (biznode.1bz.biz) — AI business operator and automation platform\n"
            "DZIT (dzit.1bz.biz) — Blockchain gas credits, virtual identity (DZID), smart contracts on Polygon\n"
            "CopyGuard (copyguard.1bz.biz) — Blockchain IP protection and ownership proof\n"
            "IPVault (ipvault.1bz.biz) — IP monetization via NFTs and resale rights\n"
            "SmartPDF (smartpdf.1bz.biz) — AI-interactive blockchain-certified documents\n"
            "Fax (fax.1bz.biz) — AI-powered blockchain fax service with ownership proof\n"
            "BizChannel (bizchannel.1bz.biz) — Decentralized ad marketplace for Telegram\n"
            "UBC (ubc.1bz.biz) — AI-powered publishing and data marketplace\n"
            "DX (dx.1bz.biz) — Dzit Exchange for discounted crypto trading\n"
            "FV (fv.1bz.biz) — AI face and voice verification\n\n"
            "The ecosystem flow: CopyGuard (protect) → IPVault (monetize) → SmartPDF (deliver) → "
            "DZIT (settle on Polygon) → BizNode (automate). All services consume DZIT gas credits."
        ),
        "tags": ["support", "ecosystem", "1bz", "shared-kb"],
        "keywords": ["1bz", "ecosystem", "biznode", "dzit", "copyguard", "ipvault", "smartpdf", "fax", "bizchannel", "dx", "fv"],
    },
    {
        "title": "DZIT — Blockchain Gas Credits on Polygon",
        "content": (
            "DZIT is the utility token powering the 1BZ ecosystem, built on the Polygon blockchain.\n\n"
            "What DZIT does:\n"
            "- Gas credits for all 1BZ services (BizNode, CopyGuard, SmartPDF, etc.)\n"
            "- Virtual identity (DZID) — your blockchain business identity\n"
            "- Smart contract account for automated payments\n"
            "- Settlement layer for inter-agent transactions\n\n"
            "How to get DZIT:\n"
            "- Every BizNode registration includes 10 free DZIT\n"
            "- Buy at dzit.1bz.biz with Stripe or crypto\n"
            "- Earn by publishing tools and services on BizNode marketplace\n"
            "- 1BZNode tier includes 1500 bonus DZIT\n\n"
            "DZIT is used across the entire ecosystem — protecting IP on CopyGuard, "
            "sending certified faxes, trading on DX Exchange, and running AI verification on FV."
        ),
        "tags": ["support", "dzit", "blockchain", "polygon", "shared-kb"],
        "keywords": ["dzit", "credits", "polygon", "blockchain", "gas", "token", "dzid", "identity"],
    },
    {
        "title": "CopyGuard — Blockchain IP Protection",
        "content": (
            "CopyGuard (copyguard.1bz.biz) provides blockchain-certified intellectual property protection.\n\n"
            "Features:\n"
            "- Register ownership proof on Polygon blockchain\n"
            "- Timestamp your creative works (documents, code, designs, music)\n"
            "- Generate blockchain certificates of authenticity\n"
            "- Legal evidence for copyright disputes\n"
            "- Integration with Fax service for certified delivery\n\n"
            "How it works:\n"
            "1. Upload your content to CopyGuard\n"
            "2. Content hash is registered on Polygon blockchain\n"
            "3. You receive a blockchain certificate with transaction ID\n"
            "4. Certificate is verifiable by anyone on PolygonScan\n\n"
            "Cost: DZIT credits per registration. Part of the ecosystem flow: "
            "CopyGuard (protect) → IPVault (monetize) → SmartPDF (deliver)."
        ),
        "tags": ["support", "copyguard", "ip", "blockchain", "shared-kb"],
        "keywords": ["copyguard", "ip", "protection", "copyright", "blockchain", "certificate", "ownership"],
    },
    {
        "title": "IPVault — Monetize Your Intellectual Property",
        "content": (
            "IPVault (ipvault.1bz.biz) turns your intellectual property into revenue through NFTs and resale rights.\n\n"
            "Features:\n"
            "- Mint NFTs from your protected IP (requires CopyGuard registration)\n"
            "- Set resale rights and royalty percentages\n"
            "- Marketplace for buying and selling IP licenses\n"
            "- Automated royalty distribution via smart contracts\n"
            "- Integration with DZIT for settlement\n\n"
            "Use cases:\n"
            "- Authors: sell book rights with automatic royalties\n"
            "- Developers: license code with usage tracking\n"
            "- Designers: sell design assets with resale rights\n"
            "- Musicians: distribute music rights via NFTs\n\n"
            "Flow: CopyGuard (prove ownership) → IPVault (create NFT/license) → SmartPDF (deliver to buyer)."
        ),
        "tags": ["support", "ipvault", "nft", "monetize", "shared-kb"],
        "keywords": ["ipvault", "nft", "monetize", "ip", "royalty", "license", "resale", "rights"],
    },
    {
        "title": "SmartPDF — AI-Interactive Blockchain Documents",
        "content": (
            "SmartPDF (smartpdf.1bz.biz) creates AI-interactive, blockchain-certified documents.\n\n"
            "Features:\n"
            "- Generate PDFs that can answer questions about their content\n"
            "- Blockchain certification — each document has a verifiable hash\n"
            "- AI chat interface embedded in the document\n"
            "- Tamper detection — any modification invalidates the certificate\n"
            "- Integration with CopyGuard for ownership proof\n\n"
            "Use cases:\n"
            "- Legal contracts that can explain their own terms\n"
            "- Technical manuals that answer user questions\n"
            "- Financial reports with interactive data exploration\n"
            "- Educational materials with built-in tutoring\n\n"
            "Cost: DZIT credits per document generated."
        ),
        "tags": ["support", "smartpdf", "documents", "ai", "shared-kb"],
        "keywords": ["smartpdf", "pdf", "document", "ai", "interactive", "blockchain", "certified"],
    },
    {
        "title": "DX Exchange — Discounted Crypto Trading",
        "content": (
            "DX Exchange (dx.1bz.biz) is the Dzit Exchange for discounted cryptocurrency trading.\n\n"
            "Features:\n"
            "- Trade major cryptocurrencies at discounted rates\n"
            "- USDT escrow for secure peer-to-peer trading\n"
            "- Integration with DZIT credits for fee discounts\n"
            "- Polygon-based settlement for fast, low-cost transactions\n"
            "- AI-powered price analysis and trade suggestions\n\n"
            "DX is part of the 1BZ ecosystem — trade crypto, earn DZIT, use credits across all services."
        ),
        "tags": ["support", "dx", "exchange", "crypto", "shared-kb"],
        "keywords": ["dx", "exchange", "crypto", "trading", "usdt", "escrow", "discounted"],
    },
    {
        "title": "FV Verify — AI Face & Voice Verification",
        "content": (
            "FV Verify (fv.1bz.biz) provides AI-powered face and voice verification for secure identity.\n\n"
            "Features:\n"
            "- Face recognition for identity verification\n"
            "- Voice biometrics for phone/call authentication\n"
            "- Liveness detection to prevent spoofing\n"
            "- Integration with DZID for blockchain-backed identity\n"
            "- API for embedding verification in your applications\n\n"
            "Use cases:\n"
            "- KYC (Know Your Customer) for financial services\n"
            "- Secure login without passwords\n"
            "- Remote identity verification for contracts\n"
            "- Age verification for restricted content\n\n"
            "Cost: DZIT credits per verification request."
        ),
        "tags": ["support", "fv", "verification", "face", "voice", "shared-kb"],
        "keywords": ["fv", "verify", "face", "voice", "biometric", "identity", "kyc", "authentication"],
    },
    {
        "title": "KB Sharing — How Cross-Bot Knowledge Works",
        "content": (
            "BizNode supports cross-bot knowledge base sharing. When your bot can't answer a question "
            "from its own KB, it can search shared KBs from other businesses.\n\n"
            "Three sharing modes:\n"
            "1. SHARED (free) — Your KB is searchable by all bots. Helps grow the network.\n"
            "2. PRIVATE — Only your bot can access your KB. Default for sensitive businesses.\n"
            "3. CHARGED — Other bots pay DZIT to search your KB. You earn 90%, BizNode keeps 10%.\n\n"
            "The 1BZ Ecosystem KB is always shared across all bots by default — it contains information "
            "about all 1BZ services (DZIT, CopyGuard, IPVault, SmartPDF, DX, FV, etc.).\n\n"
            "Set your sharing mode during onboarding (question 7) or later via the API:\n"
            "POST /api/kb-sharing/config with agent_id, sharing_mode, cost_per_query.\n\n"
            "Revenue from charged KB: 90% goes to the KB owner, 10% to BizNode platform fee."
        ),
        "tags": ["support", "kb", "sharing", "marketplace", "faq", "shared-kb"],
        "keywords": ["kb", "sharing", "knowledge base", "cross-bot", "charged", "shared", "private", "90%", "10%"],
    },

    # === Remote Support System ===
    {
        "title": "Remote Support — How /support Works",
        "content": (
            "BizNode provides AI-powered remote support through @biznode_bot.\n\n"
            "How to use:\n"
            "1. Open @biznode_bot on Telegram\n"
            "2. Type: /support my dashboard is not working\n"
            "3. The AI will automatically:\n"
            "   - Look up your registered node\n"
            "   - Run a health check on your node remotely via MCP\n"
            "   - Diagnose what's wrong (database, AI model, dashboard, etc.)\n"
            "   - Attempt auto-fix (restart down services)\n"
            "   - Report findings and next steps in chat\n\n"
            "No passwords shared. No screen sharing. No manual steps.\n"
            "The AI handles everything through secure Ed25519 signed commands.\n\n"
            "Available for BizMax ($200), BizNode ($499), and 1BZNode ($1500) tiers.\n"
            "API-only tiers ($20-$150) get KB search + AI chat support."
        ),
        "tags": ["support", "mcp", "remote", "how-to", "commands"],
        "keywords": ["support", "remote", "help", "fix", "diagnose", "health check", "mcp"],
    },
    {
        "title": "Support for Nodes Behind NAT (Home Networks)",
        "content": (
            "If your BizNode is behind a home router/firewall without port forwarding, "
            "the admin cannot reach your node directly for real-time support.\n\n"
            "You have two options:\n\n"
            "OPTION A: Automated Support (No Action Needed)\n"
            "Your node automatically reports health status to the BizNode network. "
            "The admin can see your status and send fix commands through the nodemonitor queue. "
            "Your node polls for pending commands every 2 minutes. No port forwarding or VPN needed.\n\n"
            "OPTION B: Real-Time Support Session\n"
            "For complex issues needing real-time diagnosis:\n"
            "1. Contact @biznode_supportbot on Telegram\n"
            "2. Choose a date and time for your support session\n"
            "3. You'll receive a WireGuard VPN configuration file\n"
            "4. Install WireGuard from wireguard.com/install\n"
            "5. Import the config — you'll get a private IP (10.50.0.x)\n"
            "6. At your scheduled time, the support team connects directly\n"
            "7. After the session, disconnect the VPN\n\n"
            "To book: message @biznode_supportbot with your BizNode ID and preferred time."
        ),
        "tags": ["support", "nat", "vpn", "wireguard", "faq"],
        "keywords": ["nat", "behind router", "firewall", "vpn", "wireguard", "support session", "port forwarding"],
    },
    {
        "title": "What Support Can and Cannot Fix",
        "content": (
            "WHAT SUPPORT CAN FIX:\n"
            "- Dashboard not responding (auto-restart)\n"
            "- Bot not responding (auto-restart)\n"
            "- Ollama model not loading (pull model command)\n"
            "- .env misconfiguration (update non-sensitive keys)\n"
            "- Knowledge base empty (seed KB articles remotely)\n"
            "- Outdated version (push update package)\n"
            "- Service crashes (analyze logs, suggest fixes)\n\n"
            "WHAT SUPPORT CANNOT DO:\n"
            "- Access your database passwords or Stripe keys\n"
            "- Run destructive commands (delete files, drop tables)\n"
            "- Access personal files outside BizNode directory\n"
            "- Modify sensitive .env variables (DB_PASSWORD, STRIPE_SECRET)\n"
            "- Control your node without your knowledge (all commands are logged)\n\n"
            "All support commands are Ed25519 signed, time-limited (24hr expiry), "
            "and logged on your node for transparency."
        ),
        "tags": ["support", "security", "faq"],
        "keywords": ["fix", "cannot", "security", "logged", "transparent", "password", "destructive"],
    },
    {
        "title": "Support Tiers — Response Time by Plan",
        "content": (
            "Support level depends on your BizNode tier:\n\n"
            "Basic to BizPlus ($20-$150): API-only support\n"
            "  - KB search + AI chat in @biznode_bot\n"
            "  - Instant automated responses\n"
            "  - No remote node access (runs on BizNode infrastructure)\n\n"
            "BizMax ($200): Remote MCP diagnostics\n"
            "  - AI-powered /support command\n"
            "  - Automated health check + auto-fix\n"
            "  - Instant response\n\n"
            "BizNode ($499): Full remote support\n"
            "  - Everything in BizMax\n"
            "  - Scheduled real-time support sessions via @biznode_supportbot\n"
            "  - Log analysis and manual investigation\n\n"
            "1BZNode ($1500): Priority support\n"
            "  - Everything in BizNode\n"
            "  - Priority scheduling for support sessions\n"
            "  - Dedicated support channel"
        ),
        "tags": ["support", "tier", "pricing", "faq"],
        "keywords": ["support tier", "response time", "priority", "bizmax", "biznode", "1bznode"],
    },
    {
        "title": "MCP Security — How Remote Commands Are Protected",
        "content": (
            "All remote support commands use MCP (Model Context Protocol) with Ed25519 cryptographic signing.\n\n"
            "Security features:\n"
            "- Every command is signed with the admin's Ed25519 private key\n"
            "- Your node verifies the signature before executing anything\n"
            "- Responses are signed by your node's key (tamper-proof)\n"
            "- Tokens expire after 24 hours\n"
            "- Destructive commands are blocked (rm, del, DROP, shutdown)\n"
            "- Sensitive env keys cannot be changed remotely (DB_PASSWORD, STRIPE_SECRET)\n"
            "- All commands are logged on your node\n\n"
            "Your node's admin_public.pem (embedded during installation) ensures only "
            "the official BizNode admin can send commands. No other party can control your node.\n\n"
            "Permission levels: admin (full), remote_control (restart+seed), support (read-only), "
            "diagnose (health check only)."
        ),
        "tags": ["support", "security", "mcp", "faq"],
        "keywords": ["mcp", "security", "ed25519", "signed", "encrypted", "permission", "safe"],
    },
    {
        "title": "How to Book a Real-Time Support Session",
        "content": (
            "For complex issues that need real-time diagnosis, book a support session:\n\n"
            "1. Open @biznode_supportbot on Telegram\n"
            "2. Send: 'I need real-time support for my BizNode'\n"
            "3. Provide:\n"
            "   - Your BizNode ID (shown in dashboard or /support command)\n"
            "   - Preferred date and time\n"
            "   - Brief description of the issue\n"
            "4. You'll receive:\n"
            "   - Confirmation of scheduled time\n"
            "   - WireGuard VPN config file (valid for 24 hours)\n"
            "   - Instructions to connect\n\n"
            "Available for BizNode ($499) and 1BZNode ($1500) tiers.\n"
            "1BZNode customers get priority scheduling.\n\n"
            "During the session, the support team connects directly to your node "
            "through a secure VPN tunnel and can diagnose, fix, and verify in real-time."
        ),
        "tags": ["support", "session", "booking", "vpn", "how-to"],
        "keywords": ["book", "session", "real-time", "support", "schedule", "appointment", "supportbot"],
    },
]


def _ensure_collection(reset: bool = False):
    import requests
    check = requests.get(f"{QDRANT_URL}/collections/{COLLECTION}", timeout=5)
    exists = check.status_code == 200
    if exists and reset:
        requests.delete(f"{QDRANT_URL}/collections/{COLLECTION}", timeout=5)
        exists = False
    if not exists:
        requests.put(
            f"{QDRANT_URL}/collections/{COLLECTION}",
            json={"vectors": {"size": 768, "distance": "Cosine"}},
            timeout=10,
        )
        print(f"[+] Created collection: {COLLECTION}")
    else:
        print(f"[i] Collection exists: {COLLECTION}")


def _embed(text: str) -> list:
    import requests
    r = requests.post(
        OLLAMA_EMBED_URL,
        json={"model": EMBEDDING_MODEL, "prompt": text},
        timeout=30,
    )
    return r.json().get("embedding", [])


def _upsert(point_id: str, vector: list, payload: dict):
    import requests
    requests.put(
        f"{QDRANT_URL}/collections/{COLLECTION}/points",
        json={"points": [{"id": point_id, "vector": vector, "payload": payload}]},
        timeout=10,
    )


# ── Main ──────────────────────────────────────────────────────────────────────

def seed(dry_run: bool = False, reset: bool = False):
    print(f"\nBizNode Support KB Seeder")
    print(f"  Qdrant : {QDRANT_URL}")
    print(f"  Model  : {EMBEDDING_MODEL}")
    print(f"  Articles: {len(SUPPORT_ARTICLES)}")
    print(f"  Collection: {COLLECTION}")
    if dry_run:
        print("\n[DRY RUN] Articles that would be seeded:\n")
        for i, a in enumerate(SUPPORT_ARTICLES, 1):
            print(f"  {i:2}. [{', '.join(a['tags'])}] {a['title']}")
        print(f"\nTotal: {len(SUPPORT_ARTICLES)} articles")
        return

    print()
    _ensure_collection(reset=reset)
    print()

    seeded = 0
    for i, article in enumerate(SUPPORT_ARTICLES, 1):
        title   = article["title"]
        content = article["content"]
        tags    = article.get("tags", ["support"])
        keywords = article.get("keywords", [])

        # Combine title + content for embedding
        embed_text = f"{title}\n\n{content}"
        print(f"  [{i:2}/{len(SUPPORT_ARTICLES)}] Embedding: {title[:60]}...", end=" ", flush=True)

        try:
            vector = _embed(embed_text)
            if not vector:
                print("SKIP (no vector returned)")
                continue

            _upsert(
                point_id=str(uuid.uuid5(uuid.NAMESPACE_DNS, title)),
                vector=vector,
                payload={
                    "title":    title,
                    "text":     content,
                    "tags":     tags,
                    "keywords": keywords,
                    "source":   "support_kb",
                },
            )
            print("OK")
            seeded += 1
        except Exception as e:
            print(f"FAILED ({e})")

    print(f"\n[OK] Seeded {seeded}/{len(SUPPORT_ARTICLES)} articles into '{COLLECTION}'")
    print(f"\nUsers can now search support articles via @biznode_bot or:")
    print(f"  curl {QDRANT_URL}/collections/{COLLECTION}/points/scroll")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Seed BizNode support knowledge base")
    parser.add_argument("--dry-run", action="store_true", help="Print articles without embedding")
    parser.add_argument("--reset",   action="store_true", help="Delete and recreate collection first")
    args = parser.parse_args()
    seed(dry_run=args.dry_run, reset=args.reset)
