"""
Seed BizNode Knowledge Base (direct — no API auth needed)
==========================================================
Inserts articles directly into SQLite + Qdrant.

Run from: C:\nodesrunning\biznodemainnode
    python seed_kb.py
"""

import os, sys, uuid, json, time, requests

# Add project root to path
ROOT = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, ROOT)

OLLAMA_EMBED_URL = os.getenv("OLLAMA_EMBED_URL", "http://localhost:11434/api/embeddings")
EMBED_MODEL      = os.getenv("EMBEDDING_MODEL",  "nomic-embed-text")
QDRANT_URL       = os.getenv("QDRANT_URL",       "http://localhost:6333")
QDRANT_COLL      = "biznode_memory"

ARTICLES = [
    {
        "title": "What is BizNode?",
        "content": """BizNode is an autonomous AI business operator that runs on your local machine or USB drive.
It operates your business 24/7 through Telegram, manages leads, sends emails, and maintains
intelligent memory — all without cloud dependency or API fees.

BizNode uses a local AI brain powered by Qwen3.5 4B via Ollama, meaning all AI processing
happens on your own hardware. No data leaves your machine.

Key capabilities:
- Automatically responds to Telegram private messages from customers 24/7
- Monitors a Telegram community group, silently captures leads, responds when @mentioned
- BizBrain profiler: 4-step /help intake generates a full AI business intelligence profile
- Extracts and stores lead information from conversations
- Sends daily promotional emails to new leads (3 rotating HTML templates)
- Sends emails via your SMTP account
- Remembers customer context across all conversations
- Runs scheduled tasks and automations
- Accessible via owner dashboard at localhost:7777
- Registers on the 1BZ decentralized node network

Try the live demo bot: @biznode_bot on Telegram
Join the community: https://t.me/c/3710628018/1
Website: https://biznode.1bz.biz"""
    },
    {
        "title": "BizBrain Business Profiler — /help command",
        "content": """BizBrain is BizNode's AI-powered business intelligence profiler, activated via the /help command in Telegram.

HOW IT WORKS:
1. Send /help to @biznode_bot on Telegram
2. The bot asks you 4 questions about your business:
   - What type of business do you run?
   - What services or products do you offer?
   - Who is your target audience?
   - What are your main business challenges?
3. BizNode processes your answers using the local Ollama AI
4. A complete BizBrain Profile is generated with 7 sections:
   - Business Overview
   - Target Audience
   - Key Services
   - FAQs (auto-generated)
   - Workflow Triggers (automation ideas)
   - Suggested Menu Items for your bot
   - Growth Strategy

AFTER GENERATION:
- If you have a purchased BizNode license: the full profile is emailed to you automatically
- If you are on trial: a preview is shown in Telegram with a link to purchase

The BizBrain profile is used to configure your bot's knowledge base and automate your business workflow.
This is the fastest way to get BizNode set up for your specific business type."""
    },
    {
        "title": "Telegram Group Monitoring and Community Lead Generation",
        "content": """BizNode can silently monitor a Telegram group and automatically capture leads from member activity.

HOW IT WORKS:
- Set TELEGRAM_GROUP_ID in your .env (e.g. -1003710628018)
- The bot joins the group and monitors all messages
- Every message is logged as a lead with source="telegram_group"
- Leads appear in the dashboard under Leads & Actions
- The bot does NOT respond to every message — it stays silent

WHEN THE BOT RESPONDS IN THE GROUP:
- Only when directly @mentioned (e.g. "@biznode_bot what are your prices?")
- The bot replies using the same RAG knowledge base as private messages

SETUP STEPS:
1. Add your bot as admin to your Telegram group
2. Set TELEGRAM_GROUP_ID=-1003710628018 in .env
3. Set TELEGRAM_GROUP_LINK=https://t.me/c/3710628018/1 in .env
4. Restart the bot

DAILY DIGEST:
- The daily email digest includes a "Group Activity" section
- Shows count of group interactions and top messages from the day

JOIN THE BIZNODE COMMUNITY GROUP:
https://t.me/c/3710628018/1

Try the bot: @biznode_bot"""
    },
    {
        "title": "Daily Promotional Emails to New Leads",
        "content": """BizNode automatically sends daily promotional emails to leads with status="new".

HOW IT WORKS:
- Runs every day at 8AM UTC (configurable via PROMO_EMAIL_CRON in .env)
- Fetches all leads from the dashboard with status="new"
- Sends one of 3 rotating HTML email variants:
  1. Features variant — subject: "Automate your business with BizNode AI" — feature list + CTA
  2. Case Study variant — subject: "How businesses grow with AI automation" — story format + results
  3. Offer variant — subject: "Limited: Start your AI business node today" — urgency + pricing link
- Variant rotates by index (0, 1, 2, 0, 1, 2...) so each lead gets a different message
- After sending, the lead's status is updated to "contacted" to avoid duplicate emails

CONFIGURATION:
- PROMO_EMAIL_CRON=0 8 * * * (default — daily 8AM UTC)
- Change schedule in dashboard Setup → Email section
- Requires SMTP configured (SMTP_HOST, SMTP_USER, SMTP_PASSWORD in .env)

VIEW IN DASHBOARD:
- Dashboard → Marketing Hub → Sent Log shows all promotional emails
- Dashboard → Leads shows lead statuses (new → contacted)"""
    },
    {
        "title": "BizNode Pricing and Plans",
        "content": """BizNode offers three pricing tiers with different feature sets:

FREE TRIAL (10 days):
- Cost: Free, no credit card required
- Duration: 10 days full functionality
- How to start: Download BizNode.zip, run setup.bat, then python launcher.py
- Registration is automatic on first run
- 1 Telegram bot, 8 core features
- Core features: telegram_bot, dashboard, rag_kb, llm_chat, email_service, otp_service, workflow_engine, local_backup

BASIC LICENSE (Annual, BZN-XXXXX-XXXXX-XXXXX):
- Cost: Annual subscription
- Duration: 12 months, auto-renewal
- Purchase: https://buy.stripe.com/6oU3cvcoA6GN4697sJ7ss0j
- License key format: BZN-XXXXX-XXXXX-XXXXX (entered once, validated against server)
- Machine-bound: key locks to the first machine fingerprint on activation
- 7-day offline grace period (works without internet for 7 days after last validation)
- 1 Telegram bot allowed
- 8 core features (same as trial)
- No USB hardware required
- Stored locally in .license_key file
- BizBrain business profiler included
- 1BZ network registration included

PRO LICENSE (USB Hardware-Bound):
- Hardware-bound USB drive with Ed25519 cryptographic signature
- Factory device serial + volume serial = SHA-256 fingerprint (cannot be copied)
- Up to 5 Telegram bots (multi-bot with BOT_TOKEN_1 through BOT_TOKEN_5)
- All 27 features unlocked including:
  * BizChannel marketplace (bot-to-bot service exchange)
  * Video automation & content production
  * Social media & blog posting
  * AI agent employment services
  * Agent performance monitoring
  * Stripe & crypto payment processing
  * Affiliate & customer engagement
  * Cloud backup to Google Drive
  * Node network monitoring
  * API service access
  * Admin tools suite
- USBWatchdog monitors USB presence every 30 seconds
- Contact for pricing: biznode@1bz.biz or https://biznode.1bz.biz

PACKAGE DIFFERENCES:
- Basic package ZIP excludes: videoautomation/, bizchannel/, tools/admin/, pro-only services
- Pro package ZIP includes everything except secrets and runtime data
- Basic package: ~107 files | Pro package: ~197 files
- Built with: python scripts/build_package.py --tier basic (or --tier pro)

After trial expires, purchase Basic or Pro license to continue.
Try live demo: @biznode_bot on Telegram"""
    },
    {
        "title": "How to Install BizNode",
        "content": """Installation steps for BizNode:

REQUIREMENTS:
- Windows 10 or 11
- Python 3.10 or higher (python.org — tick "Add Python to PATH")
- Docker Desktop (docker.com)
- Minimum 8 GB RAM
- 15 GB free disk space

INSTALLATION STEPS:
1. Download BizNode.zip from https://biznode.1bz.biz
2. Extract the ZIP to a folder (e.g. C:\\BizNode)
3. Run setup.bat — installs packages, downloads AI model (~2.5 GB), starts Qdrant
4. Copy .env.example to .env and fill in your Telegram bot token
5. Run start.bat or: python launcher.py
6. Open dashboard at http://localhost:7777

SETUP TIME:
- 5-10 minutes for pip install
- 5-20 minutes to download AI model (depends on internet speed)

Registration happens automatically and your 10-day trial begins.
Download at: https://biznode.1bz.biz"""
    },
    {
        "title": "How to Configure BizNode and Set Up Telegram Bot",
        "content": """To configure BizNode you need a Telegram bot token and your Telegram user ID.

CREATING A TELEGRAM BOT:
1. Open Telegram and message @BotFather
2. Send /newbot
3. Choose a name and username for your bot
4. BotFather gives you a token like: 1234567890:ABCDefgh...
5. Copy this token

FINDING YOUR TELEGRAM USER ID:
1. Message @userinfobot on Telegram
2. It replies with your user ID (a number like 987654321)

CONFIGURING IN DASHBOARD:
1. Open http://localhost:7777
2. Go to Setup section
3. Enter Telegram Bot Token
4. Enter Owner Telegram ID
5. Set your business name and description
6. Click Save Settings, then Restart Bot

OPTIONAL — TELEGRAM GROUP MONITORING:
- Set TELEGRAM_GROUP_ID (your group's numeric ID, e.g. -1003710628018)
- Set TELEGRAM_GROUP_LINK (public link to your group)
- Bot will silently capture group leads and respond when @mentioned

Test by sending /start to your bot on Telegram.
Demo bot: @biznode_bot"""
    },
    {
        "title": "BizNode Features and Capabilities",
        "content": """BizNode v1.2 provides the following features:

TELEGRAM AI AGENT:
- Automatically responds to customer private messages 24/7
- Uses knowledge base (RAG) to answer questions
- Maintains conversation history per customer
- Onboarding flow with OTP email verification
- Rate limiting: 5 messages per minute per user

BIZBRAIN PROFILER (/help):
- 4-step business intake questionnaire
- Generates 7-section AI business intelligence profile
- Emails full profile to licensed users
- Configures bot's knowledge base automatically

COMMUNITY LEAD GENERATION:
- Monitor a Telegram group silently
- Auto-capture every group member as a lead
- Bot responds in group only when @mentioned
- Daily digest shows group activity stats

DAILY PROMOTIONAL EMAILS:
- Runs at 8AM UTC daily (configurable)
- 3 rotating HTML email variants sent to new leads
- Auto-marks leads as "contacted" after sending

LEAD MANAGEMENT:
- Extracts lead info from Telegram conversations and group
- Full CRM with client files, notes, status tracking
- View in dashboard Leads & Actions section

KNOWLEDGE BASE (RAG):
- Add business knowledge via text or file upload
- Semantic search with Qdrant vector store
- Use /help (BizBrain) to auto-generate KB content
- Seed from Setup section

EMAIL AUTOMATION:
- Daily digest report to owner
- Email inbox scanner — reply to digest with commands
- Promotional email campaigns
- Configure SMTP in dashboard Setup

TASK SCHEDULER:
- Schedule recurring tasks with APScheduler
- ClaudTask system for AI-powered automations

OWNER DASHBOARD:
- Web UI at localhost:7777
- Activity feed, chat, leads, network, reports, setup
- Marketing Hub: email logs, digest, inbox instructions

BACKUP SYSTEM:
- Encrypted backups of all data
- Providers: local, Google Drive, Dropbox, S3, NAS

NODE NETWORK:
- Ed25519 identity keypair
- Register on 1BZ decentralized network"""
    },
    {
        "title": "BizNode Trial Registration and Licensing",
        "content": """BizNode registration and licensing system:

FREE TRIAL (10 days):
- Run python launcher.py to register and start trial
- Register at https://biznode.1bz.biz
- 10 days full functionality, no credit card required
- After /help intake: preview profile shown, full profile requires license
- Stored in .registration file locally

BASIC LICENSE KEY:
- Format: BZN-XXXXX-XXXXX-XXXXX (e.g. BZN-GKYW2-F3XHE-JSAVY)
- Enter the key when prompted by launcher.py (step 1.5 in startup)
- Key is validated against server at https://biznode.1bz.biz/api_license.php
- First activation binds the key to your machine fingerprint
- Key cannot be used on a different machine after binding
- Saved locally in .license_key file for offline use
- 7-day offline grace: works without internet for 7 days after last server check
- After 7 days offline, must reconnect to internet for re-validation
- Purchase: https://buy.stripe.com/6oU3cvcoA6GN4697sJ7ss0j

PRO USB LICENSE:
- Insert USB with Ed25519 signed license files
- Required files on USB: registration.key, hardware.key, .biznode_license
- USB hardware fingerprint verified (factory serial — cannot be copied to another USB)
- USBWatchdog thread checks USB presence every 30 seconds
- If USB is removed, all services shut down immediately (exit code 77)
- Dashboard shows "Pro License Active"
- /help BizBrain profile emailed automatically
- Up to 5 bots with BOT_TOKEN_1 through BOT_TOKEN_5 in .env

TIER MANAGEMENT:
- services/tier_manager.py is the central source of truth
- get_current_tier() returns TRIAL, BASIC, or PRO
- is_feature_allowed("feature_name") checks if current tier permits it
- get_max_bots() returns 1 for Trial/Basic, 5 for Pro
- require_tier(TierLevel.PRO) decorator for FastAPI endpoint gating

CHECK YOUR STATUS:
- Run: python status.py
- Run: python services/tier_manager.py
- Or check Setup section in dashboard at http://localhost:7777
- API: GET /api/tier returns full tier info

Questions? Email: biznode@1bz.biz or message @biznode_bot on Telegram"""
    },
    {
        "title": "BizNode Troubleshooting",
        "content": """Common BizNode issues and solutions:

BOT NOT RESPONDING IN TELEGRAM:
- Check containers: docker compose ps
- Ensure TELEGRAM_BOT_TOKEN is in .env
- Restart: docker compose restart bot
- View logs: docker compose logs bot

DASHBOARD NOT LOADING:
- Run: python run_dashboard.py
- Or: docker compose up -d dashboard
- Default URL: http://localhost:7777

AI / OLLAMA NOT WORKING:
- Check: ollama list
- Pull models: ollama pull qwen3.5:4b
- Pull embeddings: ollama pull nomic-embed-text
- Verify URL in Setup: http://localhost:11434

QDRANT NOT CONNECTING:
- Start: docker compose up -d qdrant
- Verify URL in Setup: http://localhost:6333

SETUP.BAT ERRORS:
- Python not found: reinstall Python, tick "Add to PATH"
- Docker not found: install and start Docker Desktop

/help BIZBRAIN NOT WORKING:
- Check Ollama is running: http://localhost:11434
- Ensure bot is running and token is correct

CHECK OVERALL STATUS:
- Run: python status.py from your BizNode folder
- Or contact @biznode_bot on Telegram"""
    },
    {
        "title": "BizNode Version History and Roadmap",
        "content": """BizNode versions and upcoming features:

VERSION 1.2 (March 2026) — Current Version:
- BizBrain Profiler: /help command with 4-step business intake
- Telegram Group Monitoring: silent lead capture from community group
- Daily Promotional Emails: 3 rotating HTML variants at 8AM UTC
- Community group: https://t.me/c/3710628018/1
- Bot: @biznode_bot

VERSION 1.1 (February 2026):
- AI model: Qwen3.5 4B (improved reasoning, multilingual, 2.5 GB)
- ZIP distribution (no antivirus false positives)
- Auto-installs Ollama if missing
- Dashboard on Docker (port 7777)
- Multi-database: SQLite, MySQL, PostgreSQL
- ClaudTask automation system
- Multi-LLM: Ollama, Claude, OpenRouter
- Smart Telegram onboarding with OTP email verification
- Email Reporting Hub and daily digest
- Client Files CRM
- Encrypted backup system (5 providers)

VERSION 1.0 (January 2026):
- Telegram AI agent (24/7 responses)
- Owner dashboard (FastAPI + Alpine.js)
- Ollama LLM (Qwen2.5)
- Qdrant vector memory
- Task scheduler, backup system
- 1BZ node network

ROADMAP (Coming Soon):
- WhatsApp integration
- Web chat widget
- Voice message transcription
- Multi-node mesh networking

Download at: https://biznode.1bz.biz
Try live demo: @biznode_bot"""
    },
    {
        "title": "BizNode Community and Support",
        "content": """Get help and connect with other BizNode operators:

TELEGRAM BOT (live demo):
- Username: @biznode_bot
- Send /start to begin onboarding
- Send /help to try the BizBrain business profiler
- Ask any question about BizNode — the bot answers from its knowledge base

COMMUNITY GROUP:
- Join: https://t.me/c/3710628018/1
- Connect with other BizNode operators
- Share your BizBrain profiles and results
- Get tips on growing your business with AI

WEBSITE:
- https://biznode.1bz.biz — download, pricing, documentation, tutorial

EMAIL SUPPORT:
- biznode@1bz.biz

TUTORIAL:
- Full step-by-step guide at https://biznode.1bz.biz/tutorial.php
- Covers: installation, Telegram setup, BizBrain, knowledge base, email config

WHAT'S NEW:
- Latest features at https://biznode.1bz.biz/announcement.php"""
    },
    {
        "title": "Knowledge Base — How to Add and Manage Content",
        "content": """The BizNode knowledge base powers the AI bot's answers to customer questions.

METHOD 1 — BizBrain /help (Recommended):
1. Send /help to @biznode_bot on Telegram
2. Answer 4 questions about your business
3. BizBrain generates a full business profile automatically
4. This profile is embedded into your Qdrant knowledge base
5. Bot immediately starts answering questions based on your business context

METHOD 2 — Dashboard Seed:
1. Open http://localhost:7777 → Setup
2. Fill in Business Identity fields (name, type, services, description)
3. Click "Seed Knowledge Base"
4. Your business info is embedded into Qdrant

METHOD 3 — File Upload:
1. Dashboard → Upload .txt or .md files with business information
2. Files are embedded and stored in Qdrant automatically

METHOD 4 — Email Command:
- Reply to your daily digest email with:
  add: [your business information or FAQ here]
- BizNode processes the command and adds it to the knowledge base

VIEW KNOWLEDGE BASE:
- Dashboard → Chat section shows RAG search results
- Dashboard → Setup shows current instruction.md content"""
    },
]


# ── Helpers ──────────────────────────────────────────────────────────────────

def embed(text: str):
    r = requests.post(OLLAMA_EMBED_URL, json={"model": EMBED_MODEL, "prompt": text}, timeout=60)
    r.raise_for_status()
    return r.json().get("embedding", [])


def store_qdrant(vector, payload):
    r = requests.put(
        f"{QDRANT_URL}/collections/{QDRANT_COLL}/points",
        json={"points": [{"id": str(uuid.uuid4()), "vector": vector, "payload": payload}]},
        timeout=15,
    )
    r.raise_for_status()


def ensure_collection(dim=768):
    r = requests.get(f"{QDRANT_URL}/collections/{QDRANT_COLL}", timeout=5)
    if r.status_code == 404:
        requests.put(
            f"{QDRANT_URL}/collections/{QDRANT_COLL}",
            json={"vectors": {"size": dim, "distance": "Cosine"}},
            timeout=10,
        ).raise_for_status()
        print(f"  Created Qdrant collection '{QDRANT_COLL}'")


def store_sqlite(title, content, summary, node_id):
    # Import lazily so we don't break if memory module has issues
    try:
        from memory.database import add_note
        add_note(node_id=node_id, title=title, content=content, summary=summary, tags="biznode,docs")
    except Exception as e:
        print(f"    [WARN] SQLite store skipped: {e}")


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

def main():
    print("=" * 55)
    print("  BizNode Knowledge Base Seeder")
    print(f"  {len(ARTICLES)} articles  |  direct SQLite + Qdrant")
    print("=" * 55)
    print()

    # Verify Qdrant
    try:
        requests.get(f"{QDRANT_URL}/healthz", timeout=5).raise_for_status()
    except Exception:
        print("[ERROR] Qdrant not reachable at", QDRANT_URL)
        print("        Run: docker compose up -d qdrant")
        return

    # Verify Ollama
    try:
        requests.get("http://localhost:11434/api/tags", timeout=5).raise_for_status()
    except Exception:
        print("[ERROR] Ollama not running at localhost:11434")
        return

    ensure_collection()

    ok = 0
    for i, art in enumerate(ARTICLES, 1):
        title   = art["title"]
        content = art["content"]
        summary = content[:300].replace("\n", " ").strip()
        node_id = str(uuid.uuid4())

        print(f"[{i}/{len(ARTICLES)}] {title}")

        try:
            vector = embed(summary)
            if not vector:
                print("    [FAIL] empty embedding")
                continue

            store_qdrant(vector, {
                "node_id": node_id,
                "title":   title,
                "content": content,
                "summary": summary,
                "tags":    "biznode,docs",
                "type":    "note",
            })

            store_sqlite(title, content, summary, node_id)
            print(f"    [OK] embedded + stored (dim={len(vector)})")
            ok += 1

        except Exception as e:
            print(f"    [FAIL] {e}")

        time.sleep(0.5)

    print()
    print("=" * 55)
    print(f"  Done: {ok}/{len(ARTICLES)} articles seeded")
    print("=" * 55)
    if ok == len(ARTICLES):
        print()
        print("Bot can now answer questions about BizNode pricing,")
        print("installation, features, troubleshooting, and more.")


if __name__ == "__main__":
    main()
