"""
core/ai_knowledge.py

SwiftPOS platform knowledge base — split into named sections.
ai_service.py uses get_relevant_sections() to inject only the sections
relevant to each user query, keeping the prompt small for free-tier models.
"""

# ---------------------------------------------------------------------------
# Each entry is a standalone section of the knowledge base.
# 'keywords' are matched against the user's message to decide inclusion.
# 'always' = True means the section is always included regardless of keywords.
# ---------------------------------------------------------------------------

KNOWLEDGE_SECTIONS = {

    "roles": {
        "always": False,
        "keywords": ["role", "admin", "manager", "cashier", "permission", "access", "staff role",
                     "who can", "what can"],
        "content": """
## USER ROLES
Your company has 3 staff roles. Access is strictly enforced:

| Role    | Access Level |
|---------|-------------|
| Admin   | Full access to all features, settings, staff management, reports, and inventory |
| Manager | Sales, inventory, reports, analytics, customer management; cannot manage staff or change settings |
| Cashier | POS terminal only; can process sales and view the customer list |

Role permissions can be fine-tuned under Analytics → Role Permissions.
""",
    },

    "navigation": {
        "always": False,
        "keywords": ["navigate", "menu", "sidebar", "hub", "where is", "find", "go to"],
        "content": """
## NAVIGATION HUBS
The sidebar groups features into four Hubs:
- Sales Hub     — POS, Receipts, Customers, Credit Sales, Reports
- Inventory Hub — Products, Categories, Suppliers, Purchase Orders, Stock Adjustments, Barcode Center
- Insights Hub  — Analytics, AI Assistant, Notifications, Expenses, Stock Forecast
- Admin Hub     — Staff, Settings, Branches, Promo Codes, Audit Logs, Subscriptions
""",
    },

    "dashboard": {
        "always": False,
        "keywords": ["dashboard", "home", "overview", "today", "summary", "chart", "widget"],
        "content": """
## DASHBOARD (/dashboard/)
Main homepage for Admin and Manager roles. Displays:
- Today's revenue, transaction count, unique customers, average order value
- Yesterday comparison + % growth; weekly and monthly sales totals
- Top 5 selling items (last 24 hours)
- Payment method breakdown (Cash, Transfer, Card/POS, Mobile Money)
- Cashier performance leaderboard and recent activity timeline
- 7-day revenue chart
- Subscription plan usage bars (products, orders, staff, categories)
- Low stock and out-of-stock product counts
""",
    },

    "pos": {
        "always": False,
        "keywords": ["pos", "point of sale", "sale", "sell", "cashier", "cart", "checkout",
                     "complete sale", "payment method", "split payment", "promo code", "discount",
                     "credit sale", "credit sales", "receipt", "offline", "scan", "barcode pos",
                     "grid pos", "classic pos", "v1", "v2", "wholesale", "bundle", "variant"],
        "content": """
## POS TERMINAL — Classic V1 (/sales/pos/)
Step-by-step workflow:
1. Search for a product by name/SKU or browse category tabs.
2. Click a product to add to cart; use +/- to adjust quantity.
3. If the product has variants (Size, Colour, etc.) a picker modal appears.
4. Optionally select an existing customer or type a walk-in name/phone.
5. Optionally apply a Discount (flat or %) or a Promo Code.
6. Choose Payment Method: Cash, Bank Transfer, Card/POS Terminal, Mobile Money, or Split Payment.
   - Split Payment: divide amount between two methods.
   - Credit Sale: enter partial payment; balance is saved as credit.
7. Click "Complete Sale" — receipt is generated. Print or send via WhatsApp.

Key capabilities:
- Offline-capable: orders queue locally and sync when online.
- Bundles: single line item; stock deducted from all components.
- Wholesale pricing: auto-applies when quantity hits configured minimum.
- Customer price lists: auto-apply when a customer with a price list is selected.
- VAT: auto-calculated when VAT rate is set in Settings.

## SMART GRID POS — V2 (/sales/pos/grid/)
Visual grid of product image tiles. Plan-gated. Same checkout as Classic V1.
Switch modes in Settings → POS Interface Mode.

## BARCODE POS (/sales/barcode-pos/)
Scan barcodes via USB/Bluetooth scanner or device camera. Each scan adds the product instantly.
Requires products to have a Barcode field. Enable camera scanner in Settings.
""",
    },

    "receipts": {
        "always": False,
        "keywords": ["receipt", "reprint", "invoice", "print"],
        "content": """
## RECEIPTS (/sales/receipts/ and /sales/receipts/<id>/)
View and reprint all completed order receipts. Each receipt shows:
- Company logo, customised header/footer text
- Order number, date, time, cashier name
- Itemised list with quantities, unit prices, discounts, VAT
- Payment method, amount paid, outstanding balance (credit orders)
Receipts can be sent to customers via WhatsApp if the API is configured in Settings.
""",
    },

    "transactions": {
        "always": False,
        "keywords": ["transaction", "order history", "order list", "reverse", "refund",
                     "cancel order", "void", "history"],
        "content": """
## TRANSACTION HISTORY (/sales/transactions/)
Full list of all orders (completed, pending, cancelled). Filterable by date range,
payment method, cashier, status. Search by order number, customer name, or phone.

Role-dependent actions:
- View full order details and receipt
- Reverse/refund a completed order (stock is automatically restored)
- Clear outstanding credit from the transaction detail
""",
    },

    "credit": {
        "always": False,
        "keywords": ["credit", "owing", "balance", "debt", "outstanding", "clear credit",
                     "credit customer", "owe"],
        "content": """
## CREDIT SALES (/sales/credit-customers/)
Lists every order with an outstanding balance. For each entry:
- Customer name, phone, order number, sale date, amount owed
- "Clear Credit" button — records a partial or full payment and updates the balance
- WhatsApp reminder — sends a payment reminder to the customer's phone

How to clear credit:
  Sales → Credit Customers → find the customer → Clear Credit → enter amount received.
""",
    },

    "customers": {
        "always": False,
        "keywords": ["customer", "client", "price list", "loyalty", "contact"],
        "content": """
## CUSTOMERS (/sales/customers/)
Persistent customer records. Features:
- Add / Edit / Delete customer profiles (name, phone, email, address, notes)
- View each customer's order history, lifetime spend, and outstanding credit balance
- Assign a Price List for automatic custom pricing at POS
- Filter to show only customers with an outstanding balance

## PRICE LISTS
Create named sets of price overrides (e.g. Wholesale Rate, VIP, Staff).
Assign to a customer — prices apply automatically at POS when that customer is selected.
How to create: Sales → Customers → Price Lists → Create → add product price overrides → assign to customer.
""",
    },

    "reports": {
        "always": False,
        "keywords": ["report", "pnl", "p&l", "profit", "loss", "revenue", "sales report",
                     "daily report", "yesterday", "payment summary", "staff performance",
                     "end of day", "reconciliation", "sales by item", "export"],
        "content": """
## REPORTS MODULE

Daily Dashboard (/sales/reports/daily/)
  Live summary of today: revenue per payment method, top products, cashier breakdown.

Yesterday Summary (/sales/reports/yesterday/)
  Same view scoped to the previous day.

Transaction Report (/sales/reports/transactions/)
  Every order in a date range with CSV/Excel export.

Payment Summary (/sales/reports/payments/)
  Revenue grouped by payment method for any date range.

P&L Report (/sales/reports/pnl/) [plan-gated]
  Revenue, COGS, Gross Profit, Operating Expenses, Net Profit. Filterable by date range.
  How to run: Sales → Reports → P&L Report → select date range.

Sales By Item (/sales/reports/by-item/)
  Total quantity sold and revenue per product for a date range.

Staff Performance (/sales/reports/staff/)
  Each cashier's order count and revenue for the selected period.

End-of-Day (/sales/reports/end-of-day/)
  Closing report + cash reconciliation. Cashier enters physical cash counted;
  system computes variance (actual − expected).
""",
    },

    "inventory": {
        "always": False,
        "keywords": ["product", "inventory", "stock", "sku", "category", "item", "add product",
                     "edit product", "import", "bulk import", "export", "barcode", "barcode center",
                     "variant", "bundle", "restock", "adjustment", "hidden", "hide product",
                     "expiry", "cost price", "selling price", "wholesale price"],
        "content": """
## INVENTORY MODULE

Product List (/inventory/products/)
  Search by name/SKU/barcode. Filter by category or stock status.
  Toggle to show/hide hidden products (hidden = excluded from POS).

Add / Edit Product (/inventory/products/add/)
  Fields: Name, SKU, Barcode, Category, Selling Price, Cost Price,
  Wholesale Price & min qty, Stock Quantity, Minimum Stock, Unit of Measure,
  Image, Expiry Date, Status.
  Stock status auto-calculated: Out of Stock (0), Low Stock (≤ minimum), In Stock (> minimum).
  Notification raised automatically when stock drops to Low Stock.

Product Variants [plan-gated]
  Add size/colour/style variants with their own SKU, price, cost, and stock.
  At POS a picker modal appears for selection.

Product Bundles [plan-gated]
  Kit of multiple products sold at one bundle price. Stock deducted from each component at POS.

Categories (/inventory/categories/)
  Organise products with name, hex colour, and icon. Appear as POS tab filters.

Barcode Center (/inventory/barcodes/)
  Generate and print barcode label PDFs. Choose label size and quantity.

Bulk Import (/inventory/import/) [plan-gated]
  Upload a populated CSV to add/update many products. Download template from the page.

How to add a product:
  Inventory → Products → Add Product → fill in fields → Save.

How to import products in bulk:
  Inventory → Bulk Import → download CSV template → fill in data → upload.

How to hide a product from POS:
  Product Detail page → tick "Hidden" → Save.
""",
    },

    "stock": {
        "always": False,
        "keywords": ["stock adjustment", "adjust stock", "restock", "reduce stock", "damage",
                     "loss", "stock history", "stock transfer", "transfer stock", "branch stock"],
        "content": """
## STOCK ADJUSTMENTS (/inventory/adjustments/)
Types: Restock, Reduce, Manual Adjustment, Damage/Loss, Return to Stock.
Every adjustment is logged with a reason and the user who performed it.
History: /inventory/adjustments/history/ — full audit trail of all movements.

Restock Product (/inventory/products/<id>/restock/)
  Quick form: enter quantity received + optional reference. Updates stock immediately.

Stock Transfers (/inventory/transfers/) [plan-gated: multi-branch]
  Move stock between branches. Flow: Draft → Approved → Completed.
  How to transfer: Inventory → Stock Transfers → Create → select branches → add products → Approve → Complete.
""",
    },

    "suppliers": {
        "always": False,
        "keywords": ["supplier", "vendor", "purchase order", "po", "reorder", "procurement"],
        "content": """
## SUPPLIERS (/inventory/suppliers/)
Each supplier shows: total purchase orders value, total payments made, current balance.

## PURCHASE ORDERS (/inventory/purchase-orders/)
Statuses: Draft → Ordered → Received → Cancelled.
Marking "Received" automatically increases stock and logs inventory transactions.
The AI can draft a Purchase Order autonomously — just ask!

How to create a purchase order:
  Inventory → Purchase Orders → Create → select supplier → add products & quantities → Save.
""",
    },

    "analytics": {
        "always": False,
        "keywords": ["analytics", "insight", "forecast", "notification", "expense", "operating expense",
                     "role permission", "feature usage", "stock forecast", "alert", "bell"],
        "content": """
## ANALYTICS MODULE

Insights (/analytics/insights/)
  AI-generated daily business insights (sales trends, low stock warnings, etc.).
  Priority: Low / Medium / High. Categories: Sales, Inventory, Financial, Customers, Staff.

Notifications (/analytics/notifications/)
  System alerts: low stock, subscription expiry, unusual transactions. Bell icon in top nav.

Stock Forecast (/analytics/stock-forecast/)
  Per-product: avg daily sales, days until stockout, recommended restock qty.
  Health labels: Healthy / Low Stock Risk / Critical / Dead Stock / Overstock.

Operating Expenses (/analytics/expenses/)
  Log costs (Rent, Salaries, Utilities, etc.) with category, date, amount, reference.
  Feeds into the P&L net profit calculation.

Role Permissions (/analytics/role-permissions/)
  Fine-tune per role: delete/reverse orders, change price at POS, view profit/P&L,
  manage products/suppliers, view audit logs, manage expenses, change settings.

Feature Usage (/analytics/feature-usage/)
  Shows usage vs. plan limits: products, categories, daily orders, staff count.
""",
    },

    "staff": {
        "always": False,
        "keywords": ["staff", "user", "add user", "new user", "deactivate", "password reset",
                     "pin", "audit log", "audit trail", "2fa", "two factor", "two-factor"],
        "content": """
## STAFF MANAGEMENT (/accounts/staff/)
Admin-only. Add, edit, or deactivate staff users.
- Set username, email, role (Cashier/Manager/Admin), branch, and optional PIN
- Reset passwords; assign users to branches (multi-branch plans)
- PIN: numeric code for confirming sensitive actions at POS

## AUDIT LOGS (/accounts/audit-log/) [plan-gated]
Immutable log: logins, product edits, order completions, credit clearances, exports, settings changes.
Shows: user, action type, target, IP address, timestamp.
How to view: Admin Hub → Audit Logs → filter by user, action, or date.

## 2FA (Two-Factor Authentication)
How to enforce: Settings → Security → enable "Require 2FA for Admin" and/or "Require 2FA for Manager".
Affected staff are prompted to verify on next login.
""",
    },

    "branches": {
        "always": False,
        "keywords": ["branch", "location", "outlet", "multi branch", "multi-branch"],
        "content": """
## BRANCHES (/branches/) [plan-gated: feature_multi_branch]
Create and manage multiple business locations.
Each branch has its own stock, staff assignments, and sales records.
Branch Detail shows today's revenue, monthly revenue, recent orders, and current stock.
How to create: Admin Hub → Branches → Add Branch → set name and code → Save.
""",
    },

    "promo": {
        "always": False,
        "keywords": ["promo", "promo code", "coupon", "voucher", "discount code"],
        "content": """
## PROMO CODES (/promos/) [plan-gated: feature_promo]
Create discount codes for use at POS.
- Discount type: Percentage (%) or Fixed Amount
- Optional expiry date and maximum usage count
- Optional minimum order amount
Cashiers enter the code in the POS promo field — system validates and applies the discount.
How to create: Admin Hub → Promo Codes → Create → fill in fields → Save.
""",
    },

    "settings": {
        "always": False,
        "keywords": ["setting", "configure", "setup", "currency", "vat", "tax", "logo",
                     "receipt header", "receipt footer", "whatsapp", "sms", "thermal", "printer",
                     "camera", "scanner", "unlimited stock", "interface mode"],
        "content": """
## SETTINGS (/settings/) — Admin only
- Business identity: name, address, phone, email, logo
- Currency symbol and decimal format; VAT rate (auto-applied on every sale)
- POS Interface Mode: Classic V1 or Smart Grid V2
- Receipt: header text, footer text, show/hide logo
- Enable camera barcode scanner
- Enable unlimited stock mode (disables stock deduction — for service businesses)
- WhatsApp: API URL, API key; toggle send-receipt / send-credit-reminder / send-low-stock-alert
- SMS: API key, sender ID
- Thermal printer: printer name (QZ Tray), paper width (58 or 80mm), auto-print on sale
- Security: enforce 2FA for Admin and/or Manager

How to set up WhatsApp receipts:
  Settings → WhatsApp/SMS → enter API URL and key → enable "Send Receipt via WhatsApp" → Save.
""",
    },

    "subscription": {
        "always": False,
        "keywords": ["plan", "subscription", "upgrade", "billing", "renew", "expire", "trial",
                     "monnify", "paystack", "payment gateway", "starter", "standard",
                     "professional", "enterprise", "feature lock", "upgrade plan"],
        "content": """
## SUBSCRIPTIONS & PLANS (/subscriptions/)
Your plan controls which features and usage limits are available.

| Plan         | Key inclusions |
|--------------|---------------|
| Starter      | Basic Classic POS, limited products and daily orders |
| Standard     | Credit sales, discounts, basic reports, more products |
| Professional | P&L, barcode POS, bulk import, analytics, wholesale pricing |
| Enterprise   | Everything: multi-branch, variants, bundles, transfers, price lists, WhatsApp/SMS, 2FA, promo codes, audit logs |

Billing cycles: Monthly, 2-Monthly, 3-Monthly, Yearly (longer = discounted).
Payment: online via Monnify or Paystack, or manual bank transfer.
When your subscription expires, workspace access is locked until renewed.

To upgrade: Dashboard → Subscription card → "Upgrade Plan" → select plan and billing cycle → pay.
""",
    },

    "suspicious": {
        "always": False,
        "keywords": ["suspicious", "unusual", "flagged", "fraud", "anomaly"],
        "content": """
## SUSPICIOUS TRANSACTIONS [plan-gated]
SwiftPOS auto-flags unusual transactions (e.g. abnormally large discounts, orders outside business hours).
Review and resolve flagged orders: Sales → Suspicious Activity.
""",
    },

}

# ---------------------------------------------------------------------------
# CORE CONTEXT — always included (very short)
# ---------------------------------------------------------------------------
CORE_CONTEXT = """
## ABOUT SWIFTPOS
SwiftPOS is a web-based POS and business management platform. Your workspace is fully isolated.
All pages are prefixed by your company slug (e.g. /your-company/dashboard/).
Use the Navigation Hubs in the sidebar to reach any feature.
"""

# ---------------------------------------------------------------------------
# TOOL DESCRIPTIONS — always included (tells AI what tools it has)
# ---------------------------------------------------------------------------
TOOL_CONTEXT = """
## YOUR LIVE DATA TOOLS
1. get_stock_report             — Low stock, out-of-stock items, top 5 products by quantity.
2. get_financial_summary(start, end) — Revenue, COGS, gross profit, expenses, net profit, order count.
3. draft_purchase_order(supplier, items) — Creates a Draft Purchase Order. Confirm with the user first.

Use tools only when asked about live data. For "how do I…" questions, answer from the knowledge above.
"""


def get_relevant_sections(user_message: str) -> str:
    """
    Returns only the knowledge sections relevant to the user's message.
    Falls back to CORE_CONTEXT if no specific section matches.
    """
    message_lower = user_message.lower()
    matched = []

    for section in KNOWLEDGE_SECTIONS.values():
        if section.get("always"):
            matched.append(section["content"])
            continue
        for kw in section.get("keywords", []):
            if kw in message_lower:
                matched.append(section["content"])
                break

    # Always include core + tools
    body = CORE_CONTEXT
    if matched:
        body += "\n".join(matched)
    # If nothing matched, include navigation as a fallback
    else:
        body += KNOWLEDGE_SECTIONS["navigation"]["content"]

    body += TOOL_CONTEXT
    return body
