"""
Seed DZITSystem Knowledge Base Articles
========================================
Inserts DZIT/blockchain articles into SQLite + Qdrant.

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

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

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": "DZITSystem Smart Contract — Overview",
        "content": """DZITSystem is a Polygon-based smart contract that powers the 1BZ decentralized business identity network.

Contract address: 0x14811c0497c958ffdc4ccf5b4f576b0bc19c44fd (Polygon Mainnet)
View on PolygonScan: https://polygonscan.com/address/0x14811c0497c958ffdc4ccf5b4f576b0bc19c44fd

KEY CAPABILITIES:
- Creates virtual accounts (DZIDs) linked to email addresses
- Stores DZIT-backed credit points on the blockchain
- Role-based access: ADMIN_ROLE, BACKEND_ROLE, MASTER_ROLE
- Every service is provably recorded with a 1 DZIT proof-of-service transfer

HOW IT CONNECTS TO BIZNODE:
- When a customer purchases a DZITPACKAGE via Stripe, BizNode automatically creates a DZID account on the Polygon blockchain
- Credit points are deposited based on the package tier purchased
- A service ticket is created with the blockchain transaction hash as proof
- The customer receives an email with their DZID, credits, and a PolygonScan verification link

The DZITSystem uses two tokens:
- DZIT (0x4B37872c868571d4ad1f822c43d4e1B123FB43d8) — ERC20 gas/fee token
- Credit points — abstract points inside the contract, backed by DZIT tokens

Learn more: https://dzit.1bz.biz"""
    },
    {
        "title": "DZID — Virtual Identity Accounts",
        "content": """A DZID is a unique 6-character alphanumeric code (A-Z, 0-9) that serves as your identity across the entire 1BZ network.

EXAMPLES: A7K3M2, X9P1B4, Q5R8T0

There are over 2.18 billion possible DZIDs (36^6 combinations).

HOW A DZID IS CREATED:
1. Customer purchases a DZITPACKAGE via Stripe
2. BizNode generates a random 6-character DZID
3. EmailCreationAccount is called on the DZITSystem smart contract (Polygon)
4. confirmOTP activates the account, linking the DZID to the email hash and wallet
5. Credit points are deposited via adminDepositPoints

WHAT A DZID STORES ON-CHAIN:
- email_hash (keccak256 hash — privacy preserved, email NOT stored on-chain)
- wallet address (Polygon address, or zero address if unknown)
- credit_points (DZIT-backed credits)
- active status (boolean)

ONE EMAIL = ONE DZID:
- If a DZID already exists for an email, new purchases deposit points to the existing DZID
- You cannot have multiple DZIDs per email

YOUR DZID IS USED FOR:
- Accessing 1BZ network services
- Tracking credit point balance
- Verifying service delivery on PolygonScan
- Connecting to the Telegram bot and AI assistant"""
    },
    {
        "title": "DZIT Credit Tiers and Pricing",
        "content": """DZIT credits are purchased through Stripe and deposited to your DZID account on the Polygon blockchain.

DZITPACKAGE — One-Time Membership (creates DZID + deposits credits):

Starter:     $10   = 10 credits    (0% bonus)
Business:    $100  = 110 credits   (10% bonus)
BizPlus:     $500  = 600 credits   (20% bonus)
Enterprise:  $1000 = 1,300 credits (30% bonus)
Ultra:       $10000= 15,000 credits(50% bonus)

TOPUP — Balance Reload (deposits credits to existing DZID):

$10   = 11 credits  (10% bonus)
$100  = 120 credits (20% bonus)
$500  = 600 credits (20% bonus)
$1000 = 1,300 credits (30% bonus)

KEY FACTS:
- Credits are NOT 1:1 with dollars — higher tiers get bonus credits
- If you don't have a DZID yet and purchase a TOPUP, one is created automatically
- Credits are backed by DZIT tokens on the Polygon blockchain
- Your balance is verifiable on PolygonScan

Purchase at: https://dzit.1bz.biz"""
    },
    {
        "title": "Proof-of-Service — Blockchain Verification",
        "content": """Every service rendered through the 1BZ/DZIT system is backed by a verifiable blockchain transaction.

HOW IT WORKS:
1. Customer pays via Stripe
2. BizNode processes the payment and creates the service
3. 1 DZIT token is transferred from the admin wallet to the DZITSystem contract
4. This creates a permanent transaction on Polygon
5. The transaction hash (tx_hash) is stored in the service ticket
6. Customer receives an email with a PolygonScan link to verify

WHAT YOU CAN VERIFY:
- Visit https://polygonscan.com/tx/0x{tx_hash}
- You'll see: 1 DZIT transferred from admin wallet (0xb96e...afe3) to DZITSystem contract (0x1481...44fd)
- Timestamp, block number, gas used — all permanently recorded

WHY THIS MATTERS:
- Neither the business nor the customer can dispute whether service was rendered
- The blockchain is the single source of truth
- No central authority needed — anyone can verify independently
- Records are immutable — cannot be altered or deleted

SERVICE TICKETS:
- Format: BN-YYYYMMDD-XXXXX (e.g., BN-20260309-A1B2C)
- Contains: service type, email, DZID, blockchain tx hashes, status
- Types: dzid_creation, topup, book_sale"""
    },
    {
        "title": "Payment Flow — Stripe to Blockchain",
        "content": """Complete payment flow from customer purchase to blockchain recording:

STEP 1 — CUSTOMER PAYS:
- Customer clicks a Stripe payment link on https://dzit.1bz.biz
- Completes Stripe checkout (card payment)

STEP 2 — WEBHOOK RECEIVED:
- Stripe sends checkout.session.completed event to https://biznode.1bz.biz/webhook.php
- Webhook verifies Stripe signature (HMAC-SHA256)
- Looks up payment_link in stripe_plinks table to determine category

STEP 3 — CATEGORY ROUTING:
- DZITPACKAGE: Creates DZID account + deposits tier-based credits
- TOPUP: Deposits credits to existing DZID (creates if needed)
- BOOKS: Records book sale, updates inventory

STEP 4 — BLOCKCHAIN OPERATIONS (DZITPACKAGE/TOPUP):
- Generate random DZID (6 chars)
- Call EmailCreationAccount on DZITSystem contract (Polygon)
- Call confirmOTP to activate account
- Call adminDepositPoints with tier-based credit amount
- Transfer 1 DZIT as proof-of-service

STEP 5 — RECORD & NOTIFY:
- Service ticket created (BN-YYYYMMDD-XXXXX)
- Payment recorded in dzit_stripe_tracker
- Credits recorded in dzit_ledger
- DZID account stored in dzid_accounts
- Customer receives styled HTML email with DZID, credits, and PolygonScan proof link

FALLBACK:
- If blockchain is unavailable, system falls back to legacy flow
- Voucher code generated, credits recorded in ledger only
- Can be reconciled to blockchain later"""
    },
    {
        "title": "1BZ Token Ecosystem",
        "content": """The 1BZ ecosystem uses four tokens, each with a specific role:

1BZ — Governance Token:
- Total supply: 11,000,000
- Used for governance decisions in the 1BZ network
- Represents ownership stake in the ecosystem

DZIT — Gas/Fee/Service Token:
- Contract: 0x4B37872c868571d4ad1f822c43d4e1B123FB43d8 (Polygon)
- Used as proof-of-service (1 DZIT per service rendered)
- Backs credit points in DZID accounts
- Required for ecosystem operations

BZeUSD — Settlement Stablecoin:
- Total supply: 1,000,000,000
- Used for business-to-business settlements
- Stable value pegged to USD

E2P — Participation Token:
- Engagement and participation rewards
- Earned through network activity

HOW DZIT CONNECTS TO BIZNODE:
- BizNode admin wallet holds DZIT tokens
- Every DZITPACKAGE purchase triggers 1 DZIT proof transfer
- Every TOPUP triggers 1 DZIT proof transfer
- Credit points deposited to DZIDs are backed by DZIT
- Admin wallet needs MATIC (for gas) and DZIT (for operations)

Token info: https://dzit.1bz.biz
Network: https://1bz.biz"""
    },
    {
        "title": "Service Ticket System — Tracking Every Service",
        "content": """Every service rendered by BizNode (DZID creation, topup, book sale) gets a unique service ticket.

TICKET FORMAT: BN-YYYYMMDD-XXXXX (e.g., BN-20260309-K7X2P)

WHAT A TICKET RECORDS:
- ticket_id: Unique identifier
- service_type: dzid_creation, topup, or book_sale
- email: Customer email
- dzid: Associated DZID (if applicable)
- stripe_event_id: Stripe payment event reference
- tx_hash: Main blockchain transaction hash
- proof_tx_hash: 1 DZIT proof-of-service transaction
- block_number: Polygon block where tx was confirmed
- status: pending → completed or failed
- details: JSON with payment amount, wallet, etc.
- timestamps: created_at, completed_at

TICKET LIFECYCLE:
1. Created immediately when payment is received (status: pending)
2. Updated with blockchain tx hashes as operations complete
3. Marked completed when all operations succeed
4. Marked failed with error details if something goes wrong

Tickets are stored in both MySQL (site DB) and PostgreSQL (local node) for redundancy."""
    },
    {
        "title": "Email Notification Pipeline — Payment to Inbox",
        "content": """BizNode sends branded HTML emails at key stages of payment processing.

THREE EMAIL TYPES:

1. PENDING NOTIFICATION (immediate, <5 seconds after payment):
   - Subject: "Payment Received — Processing [service] (Ticket BN-...)"
   - Contains: Service ticket ID, processing status
   - Purpose: Confirm payment was received, set expectations
   - Sent BEFORE blockchain operations start

2. DZID WELCOME EMAIL (after blockchain completes, ~30 seconds):
   - Subject: "Your DZIT Account [DZID] — Welcome to the Network"
   - Contains: DZID code (gold, large font), email, credit points, service ticket, PolygonScan proof link
   - Includes: BizNode logo (inline via cid:biznode_logo), dark-themed design
   - Links: DZITSystem contract on PolygonScan, dzit.1bz.biz

3. TOPUP CONFIRMATION (after blockchain completes):
   - Subject: "DZIT Topup: +X Credits (Ticket BN-...)"
   - Contains: DZID, credits added, service ticket, PolygonScan proof link
   - Same branded design as welcome email

EMAIL DESIGN:
- Dark theme background (#0a1628)
- Gold accent for DZID (#d4a853)
- Green accent for credits (#22c55e)
- BizNode logo from logos/logo.png
- Plain text fallback for non-HTML clients
- Contact: biznode@1bz.biz with ticket ID for support"""
    },
    {
        "title": "Stripe Webhook Architecture — Event Processing",
        "content": """The Stripe webhook system connects customer payments to blockchain operations.

ARCHITECTURE (Pull Model):
- Stripe → webhook.php (VPS) → dzit_stripe_tracker (MySQL) → local node polls every 2 min

WEBHOOK FLOW:
1. Customer completes Stripe checkout
2. Stripe sends checkout.session.completed to webhook.php on VPS
3. webhook.php verifies HMAC-SHA256 signature
4. Looks up payment_link in stripe_plinks table → determines category
5. Inserts event into dzit_stripe_tracker table
6. Sends Telegram alert to admin
7. Forwards event to mainnode admin API (best-effort)

CATEGORY ROUTING:
- DZITPACKAGE → PaymentOrchestrator.process_dzitpackage() → create DZID + deposit credits
- TOPUP → PaymentOrchestrator.process_topup() → deposit credits to existing DZID
- BOOKS → PaymentOrchestrator.process_book_sale() → record sale + deliver PDF

LOCAL PROCESSING:
- webhook_sync_service.py polls VPS every 2 minutes
- Picks up unprocessed events (node_processed = 0)
- Routes to PaymentDispatcher → PaymentOrchestrator
- Acknowledges processed events back to VPS

IMPORTANT: Webhook endpoint must be configured in Stripe Dashboard:
- URL: https://biznode.1bz.biz/webhook.php
- Events: checkout.session.completed
- Events from: "Your account" (NOT "Connected accounts")"""
    },
    {
        "title": "DataVault Package Billing — /mr Marketing Reports",
        "content": """DataVault packages bundle multiple AI reports into a single purchasable product.

CURRENT PACKAGE: Marketing Reports (/mr)
- Package ID: mr-marketing-reports
- Contains 8 AI-powered reports (salesreport, seoaudit, competitors, socialmedia, adcampaign, emailmarketing, conversion, marketresearch)
- Public price: 10 BZeUSD
- Node price: 1 DZIT credit

PURCHASE FLOW (BZeUSD — Public):
1. User sends /mr to @biznode_bot
2. Bot shows package info with wallet address
3. User sends 10 BZeUSD to BizNode wallet on Polygon
4. User sends /mr_verify <order_id> <polygonscan_url>
5. System verifies payment on PolygonScan
6. Reports are generated and delivered

PURCHASE FLOW (DZIT — Registered Nodes):
1. User sends /mr to @biznode_bot
2. If user's email has DZID with sufficient credits, auto-deducts 1 DZIT
3. Reports generated and delivered instantly
4. No manual payment verification needed

DATABASE TABLES:
- datavault_packages: Package definitions (id, name, commands, pricing)
- datavault_package_orders: Order tracking (order_id, buyer, amount, status, polygonscan_url)

API ENDPOINTS:
- GET /api/datavault/packages/{id} — Package details
- POST /api/datavault/packages/{id}/order — Create order
- POST /api/datavault/packages/verify — Verify BZeUSD payment
- GET /api/datavault/packages/{id}/orders — List orders"""
    },
]


# ── Helpers (same as seed_kb.py) ─────────────────────────────────────────

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):
    try:
        from memory.database import add_note
        add_note(node_id=node_id, title=title, content=content, summary=summary, tags="dzit,blockchain,dzitsystem")
    except Exception as e:
        print(f"    [WARN] SQLite store skipped: {e}")


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

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

    try:
        requests.get(f"{QDRANT_URL}/healthz", timeout=5).raise_for_status()
    except Exception:
        print("[ERROR] Qdrant not reachable at", QDRANT_URL)
        return

    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":    "dzit,blockchain,dzitsystem",
                "type":    "note",
                "source":  "dzitsystem_kb",
            })

            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 DZIT system,")
        print("DZIDs, credit tiers, blockchain proof, and more.")


if __name__ == "__main__":
    main()
