#!/usr/bin/env python3
"""
knowledgebase.py — Triad Displays AI Knowledge Base
====================================================
Version:      2.0
Last Updated: July 16, 2026
Author:       Airo / GoDaddy Builder
Site:         https://www.triaddisplays.com

PURPOSE
-------
This module provides the complete structured knowledge base for the
Triad Displays AI support system (Gemini 2.5 Flash). It can be used:

  1. As a standalone Python knowledge base / FAQ lookup tool
  2. As a data source to regenerate the AI system prompt
  3. As a reference for training or fine-tuning a custom AI model
  4. As a structured export for integration with other AI platforms

USAGE
-----
  # Basic lookup
  python knowledgebase.py --search "digital menu board"

  # List all categories
  python knowledgebase.py --categories

  # Export system prompt for Gemini
  python knowledgebase.py --export-prompt

  # Export as JSON
  python knowledgebase.py --export-json

  # Interactive Q&A mode
  python knowledgebase.py --interactive

REQUIREMENTS
------------
  Python 3.8+
  No external dependencies required for core functionality.
  Optional: google-generativeai (pip install google-generativeai) for live AI mode.
"""

import json
import sys
import argparse
from typing import Optional

# ─────────────────────────────────────────────────────────────────────────────
# COMPANY PROFILE
# ─────────────────────────────────────────────────────────────────────────────

COMPANY = {
    "name": "Triad Displays",
    "tagline": "America's #1 Source for Restaurant Menu Boards & Point-of-Purchase Displays",
    "website": "https://www.triaddisplays.com",
    "phone": "866-963-7446",
    "email": "support@triaddisplays.com",
    "address": "United States (nationwide shipping)",
    "hours": "Monday–Friday, 9am–5pm EST",
    "founded": "20+ years in business",
    "specialties": [
        "Digital Menu Boards",
        "Magnetic Menu Boards",
        "Drive-Thru Systems",
        "LED Lightboxes",
        "Point-of-Purchase Displays",
        "Graphic Design Services",
    ],
    "customers": [
        "Quick Service Restaurants (QSR)",
        "Fast Casual Dining",
        "Coffee Shops & Cafes",
        "Food Trucks",
        "Delis & Bakeries",
        "Retail Stores",
        "Corporate Cafeterias",
    ],
}

# ─────────────────────────────────────────────────────────────────────────────
# PRODUCT CATALOG
# ─────────────────────────────────────────────────────────────────────────────

PRODUCTS = {
    "digital_menu_boards": {
        "name": "Digital Menu Boards",
        "url": "/digital-menu-boards",
        "description": "Commercial-grade 4K digital displays powered by idigitalmenu.com cloud software.",
        "starting_price": "Contact for quote",
        "lead_time": "7–10 business days after design approval",
        "features": [
            "4K commercial-grade displays",
            "Cloud-based content management via idigitalmenu.com",
            "Real-time updates from any device",
            "Daypart scheduling (breakfast/lunch/dinner menus)",
            "Multi-location management from one dashboard",
            "800+ professional food images included",
            "No technical experience required",
            "Fully assembled and ready to hang",
        ],
        "variants": [
            "Single screen",
            "Double screen",
            "Triple screen",
            "Drive-thru digital",
            "Custom configurations",
        ],
        "troubleshooting": {
            "black_screen": [
                "Check power — ensure display and media player are both on",
                "Restart media player — unplug 30 seconds, plug back in",
                "Check internet connection — player needs internet to load content",
                "Log in to idigitalmenu.com — verify content is published",
                "Check HDMI cable — reseat between player and display",
                "If issue persists: email support@triaddisplays.com with order number",
            ],
            "content_not_updating": [
                "Log in to idigitalmenu.com",
                "Verify content is published (not just saved)",
                "Check internet connection on the media player",
                "Clear browser cache and try again",
            ],
        },
    },

    "magnetic_menu_boards": {
        "name": "Magnetic Menu Boards",
        "url": "/magnetic-menu-boards",
        "description": "Premium magnetic letter boards for restaurants — durable, professional, easy to update.",
        "starting_price": "Contact for quote",
        "lead_time": "7–10 business days after design approval",
        "features": [
            "Magnetic letters and price strips included",
            "Multiple frame styles available",
            "Custom sizes available",
            "Mounting hardware included",
            "Up to 3 design revisions included",
            "Ships fully assembled",
        ],
        "styles": {
            "designer": {
                "name": "Designer",
                "description": "Premium look with decorative frames — ideal for upscale casual dining",
                "url": "/magnetic/designer",
            },
            "wood_trim": {
                "name": "Wood Trim",
                "description": "Warm wood border — perfect for cafes and delis",
                "url": "/magnetic/wood-trim",
            },
            "stainless_steel": {
                "name": "Stainless Steel",
                "description": "Modern sleek finish for contemporary restaurants",
                "url": "/magnetic/stainless-steel",
            },
            "custom": {
                "name": "Custom",
                "description": "Any size, any color, any configuration",
                "url": "/magnetic/custom",
            },
            "value": {
                "name": "Value",
                "description": "Budget-friendly option for smaller operations",
                "url": "/magnetic/value",
            },
        },
        "installation": [
            "Locate studs using a stud finder",
            "Mark mounting points using included template",
            "Drill pilot holes appropriate for wall type",
            "Attach mounting brackets with included hardware",
            "Hang the board on brackets and secure",
            "Level using a standard level",
            "For drywall without studs: use included toggle bolts",
        ],
    },

    "drive_thru_systems": {
        "name": "Drive-Thru Systems",
        "url": "/drive-thru",
        "description": "Complete LED and digital drive-thru package solutions for QSRs.",
        "starting_price": "Contact for quote",
        "lead_time": "7–10 business days after design approval",
        "features": [
            "Complete drive-thru communication systems",
            "LED menu boards",
            "Digital drive-thru displays",
            "Weatherproof construction",
            "High-brightness displays for outdoor visibility",
            "Custom configurations available",
        ],
        "packages": {
            "premium": {
                "name": "Premium Package",
                "description": "Full LED + digital drive-thru solution with communication system",
                "url": "/drive-thru/premium",
            },
            "value": {
                "name": "Value Package",
                "description": "Cost-effective drive-thru solution for smaller operations",
                "url": "/drive-thru/value",
            },
            "digital": {
                "name": "Digital Drive-Thru",
                "description": "Cloud-managed digital displays for drive-thru lanes",
                "url": "/drive-thru/digital",
            },
            "communication": {
                "name": "Communication Systems",
                "description": "Drive-thru headsets, speakers, and ordering systems",
                "url": "/drive-thru/communication",
            },
        },
        "sister_brand": {
            "name": "Drivethru.systems",
            "url": "https://www.drivethru.systems",
            "description": "Dedicated website for complete LED & digital drive-thru package solutions",
        },
    },

    "led_lightboxes": {
        "name": "LED Lightboxes",
        "url": "/light-boxes",
        "description": "Illuminated lightbox displays for restaurants and retail — vibrant, energy-efficient.",
        "starting_price": "Contact for quote",
        "lead_time": "7–10 business days after design approval",
        "features": [
            "Energy-efficient LED backlighting",
            "Vivid, eye-catching illumination",
            "Indoor and outdoor options",
            "Custom sizes available",
            "Graphic printing included",
            "Easy graphic swap system",
        ],
        "types": {
            "led": {
                "name": "LED Lightboxes",
                "description": "Modern LED-backlit displays — energy efficient and long-lasting",
                "url": "/light-boxes/led",
            },
            "fluorescent": {
                "name": "Fluorescent Lightboxes",
                "description": "Traditional fluorescent backlit displays",
                "url": "/light-boxes/fluorescent",
            },
        },
        "sister_brand": {
            "name": "ledlightboxes.net",
            "url": "https://www.ledlightboxes.net",
            "description": "Dedicated website for LED lightbox displays",
        },
    },
}

# ─────────────────────────────────────────────────────────────────────────────
# ORDERING & PROCESS
# ─────────────────────────────────────────────────────────────────────────────

ORDERING = {
    "process": [
        "1. Choose your product — browse Digital, Magnetic, Drive-Thru, or Lightboxes",
        "2. Request a free quote — call 866-963-7446 or fill out the Contact form",
        "3. Design approval — our team creates artwork; you approve (up to 3 revisions)",
        "4. Payment — pay in full to begin production",
        "5. Production & shipping — ships in 7–10 business days, fully assembled",
        "6. Installation — hang it up! Mounting hardware included at no extra cost",
    ],
    "required_info": [
        "Business name and logo (high-res file preferred)",
        "Menu items and prices (Word doc, PDF, or photo of current menu)",
        "Board dimensions (or let us recommend the right size)",
        "Color preferences (or we'll match your brand)",
        "Quantity needed",
        "Shipping address",
    ],
    "lead_times": {
        "standard": "7–10 business days after design approval and full payment",
        "rush": "Available for additional fee — call 866-963-7446",
        "design_proof": "2–3 business days",
        "revisions_included": 3,
    },
    "shipping": {
        "carriers": ["UPS", "FedEx Ground"],
        "expedited": "Available at extra cost",
        "packaging": "Fully assembled, professionally packaged",
    },
    "payment": {
        "policy": "Pay in full to begin production",
        "methods": "Contact for payment options",
    },
    "warranty": {
        "general": "Contact support@triaddisplays.com for warranty information",
        "phone": "866-963-7446",
    },
}

# ─────────────────────────────────────────────────────────────────────────────
# DESIGN SERVICES
# ─────────────────────────────────────────────────────────────────────────────

DESIGN_SERVICES = {
    "included": [
        "Custom artwork creation for your menu board",
        "Up to 3 rounds of revisions",
        "Brand color matching",
        "Logo integration",
        "Professional food photography recommendations",
    ],
    "additional": [
        "Logo design",
        "Brand identity packages",
        "Custom illustration",
        "Photography sourcing",
    ],
    "food_image_library": {
        "total_images": 1413,
        "categories": 24,
        "url": "/food-images",
        "description": "Professional food photography available for use on your menu boards",
        "categories_list": [
            "Asian", "BBQ", "Breakfast", "Burgers", "Chicken",
            "Desserts", "Kids", "Pizza", "Salads", "Seafood",
            "Sides", "Tacos", "Beverages", "Sandwiches", "Wraps",
            "Soups", "Pasta", "Steaks", "Seafood", "Vegetarian",
            "Appetizers", "Combo Meals", "Value Meals", "Specials",
        ],
    },
}

# ─────────────────────────────────────────────────────────────────────────────
# SISTER BRAND ECOSYSTEM
# ─────────────────────────────────────────────────────────────────────────────

ECOSYSTEM = [
    {
        "name": "PikciaOS",
        "url": "https://www.pikciaos.com",
        "tagline": "Enterprise digital signage for multi-location restaurants & corporate chains",
        "category": "signage",
        "status": "live",
    },
    {
        "name": "iDigitalMenus",
        "url": "https://www.idigitalmenus.com",
        "tagline": "Affordable restaurant digital menu SAAS — the smart Yodeck alternative",
        "category": "signage",
        "status": "live",
    },
    {
        "name": "Drivethru.systems",
        "url": "https://www.drivethru.systems",
        "tagline": "Complete LED & digital drive-thru package solutions for restaurants & QSRs",
        "category": "signage",
        "status": "live",
    },
    {
        "name": "PikciaAi",
        "url": None,
        "tagline": "AI-powered design editor for digital menus, signs, stationery & logo creation",
        "category": "design",
        "status": "coming_soon",
    },
    {
        "name": "PikciaPrint",
        "url": "https://www.pikciaprint.com",
        "tagline": "B2B printing for restaurants and retail — menus, signs, banners & more",
        "category": "print",
        "status": "live",
    },
    {
        "name": "JatoliAi",
        "url": None,
        "tagline": "AI-powered CRM, accounting, marketing & social media management for B2B",
        "category": "software",
        "status": "coming_soon",
    },
    {
        "name": "SEORuns",
        "url": "https://www.seoruns.com",
        "tagline": "SEO & social media management optimized for small businesses",
        "category": "marketing",
        "status": "live",
    },
]

# ─────────────────────────────────────────────────────────────────────────────
# FAQ DATABASE
# ─────────────────────────────────────────────────────────────────────────────

FAQ = [
    {
        "question": "How long does it take to receive my order?",
        "answer": "Standard lead time is 7–10 business days after design approval and full payment. Rush orders are available for an additional fee — call 866-963-7446.",
        "category": "ordering",
    },
    {
        "question": "Do you offer free design?",
        "answer": "Yes! Custom artwork creation is included with every order, along with up to 3 rounds of revisions. Our design team will create your menu board artwork based on your logo, menu items, and brand colors.",
        "category": "design",
    },
    {
        "question": "What file formats do you accept for logos?",
        "answer": "We prefer high-resolution files: AI, EPS, PDF, or PNG with transparent background. We can work with JPG files but high-res is preferred for best print quality.",
        "category": "design",
    },
    {
        "question": "Do you ship nationwide?",
        "answer": "Yes, we ship throughout the United States via UPS or FedEx Ground. Expedited shipping is available at extra cost.",
        "category": "shipping",
    },
    {
        "question": "What is your return policy?",
        "answer": "Since all products are custom-made to your specifications, we do not accept returns. However, if there is a manufacturing defect or error on our part, we will remake the product at no charge. Contact support@triaddisplays.com.",
        "category": "ordering",
    },
    {
        "question": "Can I update my digital menu board myself?",
        "answer": "Yes! Digital menu boards are managed through idigitalmenu.com — a simple cloud platform you can access from any device. No technical experience needed. Log in, make changes, click Publish — updates go live in seconds.",
        "category": "digital",
    },
    {
        "question": "What size magnetic menu board do I need?",
        "answer": "Size depends on your space and number of menu items. Our team will help you choose the right configuration. Call 866-963-7446 or send us a photo of your space and we'll recommend the best fit.",
        "category": "magnetic",
    },
    {
        "question": "Do you offer volume discounts?",
        "answer": "Yes, volume discounts are available for multi-location orders. Contact us at 866-963-7446 or support@triaddisplays.com to discuss pricing for your specific needs.",
        "category": "pricing",
    },
    {
        "question": "Is installation included?",
        "answer": "Mounting hardware is included at no extra cost. Products ship fully assembled and ready to hang. Installation instructions are included. For complex installations, we recommend a local handyman.",
        "category": "installation",
    },
    {
        "question": "Can I get a sample or proof before ordering?",
        "answer": "Yes — after you place your order, our design team will send you a digital proof within 2–3 business days. You can request up to 3 rounds of revisions before we go to production.",
        "category": "ordering",
    },
    {
        "question": "Do you work with franchises?",
        "answer": "Yes! We work with franchise systems of all sizes. We can produce consistent branding across multiple locations and offer volume pricing. Call 866-963-7446 to discuss your franchise needs.",
        "category": "ordering",
    },
    {
        "question": "What is the warranty on your products?",
        "answer": "Contact support@triaddisplays.com or call 866-963-7446 for specific warranty information on your product type.",
        "category": "warranty",
    },
]

# ─────────────────────────────────────────────────────────────────────────────
# AI SYSTEM PROMPT GENERATOR
# ─────────────────────────────────────────────────────────────────────────────

def generate_system_prompt() -> str:
    """
    Generate the complete Gemini AI system prompt from the knowledge base.
    Use this to update the system prompt in src/server/api/chat/POST.ts
    """
    product_list = "\n".join(
        f"  - {p['name']}: {p['description']}"
        for p in PRODUCTS.values()
    )

    faq_text = "\n".join(
        f"Q: {item['question']}\nA: {item['answer']}"
        for item in FAQ
    )

    ecosystem_text = "\n".join(
        f"  - {b['name']} ({b['status']}): {b['tagline']}"
        + (f" — {b['url']}" if b['url'] else "")
        for b in ECOSYSTEM
    )

    prompt = f"""You are the AI support assistant for {COMPANY['name']}.

COMPANY OVERVIEW
{COMPANY['name']} — {COMPANY['tagline']}
Phone: {COMPANY['phone']}
Email: {COMPANY['email']}
Hours: {COMPANY['hours']}
Website: {COMPANY['website']}

YOUR ROLE
- Help customers find the right product for their restaurant or business
- Answer questions about products, ordering, design, and shipping
- Identify food images by number from our 1,413-image library
- Upsell complementary products when appropriate
- Always be friendly, professional, and solution-focused
- For complex requests, direct customers to call {COMPANY['phone']}

PRODUCTS WE SELL
{product_list}

ORDERING PROCESS
{chr(10).join(ORDERING['process'])}

LEAD TIMES
- Standard: {ORDERING['lead_times']['standard']}
- Rush orders: {ORDERING['lead_times']['rush']}
- Design proof: {ORDERING['lead_times']['design_proof']}
- Revisions included: {ORDERING['lead_times']['revisions_included']}

FOOD IMAGE LIBRARY
We have {DESIGN_SERVICES['food_image_library']['total_images']} professional food images across {DESIGN_SERVICES['food_image_library']['categories']} categories.
If a customer mentions an image number, help them identify it and suggest using it on their menu board.
Direct them to: {DESIGN_SERVICES['food_image_library']['url']}

SISTER BRANDS (mention when relevant)
{ecosystem_text}

FREQUENTLY ASKED QUESTIONS
{faq_text}

RESPONSE GUIDELINES
- Keep responses concise and helpful
- Use bullet points for lists
- Bold important information with **text**
- Always include contact info when relevant: {COMPANY['phone']} or {COMPANY['email']}
- If you don't know something specific, say so and offer to connect them with our team
- Never make up prices — always say "Contact us for a quote"
- Upsell naturally: if someone asks about digital boards, mention the food image library; if they ask about drive-thru, mention Drivethru.systems
"""
    return prompt.strip()


# ─────────────────────────────────────────────────────────────────────────────
# SEARCH FUNCTION
# ─────────────────────────────────────────────────────────────────────────────

def search_knowledge_base(query: str) -> list[dict]:
    """
    Simple keyword search across all knowledge base content.
    Returns list of matching items with source and relevance.
    """
    query_lower = query.lower()
    results = []

    # Search FAQ
    for item in FAQ:
        score = 0
        text = f"{item['question']} {item['answer']}".lower()
        for word in query_lower.split():
            if word in text:
                score += text.count(word)
        if score > 0:
            results.append({
                "source": "FAQ",
                "title": item["question"],
                "content": item["answer"],
                "score": score,
            })

    # Search products
    for key, product in PRODUCTS.items():
        score = 0
        text = f"{product['name']} {product['description']}".lower()
        for word in query_lower.split():
            if word in text:
                score += text.count(word)
        if score > 0:
            results.append({
                "source": "Product",
                "title": product["name"],
                "content": product["description"],
                "score": score,
                "url": product.get("url", ""),
            })

    # Search ecosystem
    for brand in ECOSYSTEM:
        score = 0
        text = f"{brand['name']} {brand['tagline']}".lower()
        for word in query_lower.split():
            if word in text:
                score += text.count(word)
        if score > 0:
            results.append({
                "source": "Ecosystem",
                "title": brand["name"],
                "content": brand["tagline"],
                "score": score,
                "url": brand.get("url") or "Coming Soon",
            })

    # Sort by relevance
    results.sort(key=lambda x: x["score"], reverse=True)
    return results[:10]  # Top 10 results


# ─────────────────────────────────────────────────────────────────────────────
# INTERACTIVE MODE
# ─────────────────────────────────────────────────────────────────────────────

def interactive_mode():
    """Simple interactive Q&A using local knowledge base (no API key needed)."""
    print("\n" + "="*60)
    print("  TRIAD DISPLAYS — AI Knowledge Base (Local Mode)")
    print("  Type 'quit' to exit, 'help' for commands")
    print("="*60 + "\n")

    while True:
        try:
            query = input("Your question: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nGoodbye!")
            break

        if not query:
            continue
        if query.lower() in ("quit", "exit", "q"):
            print("Goodbye!")
            break
        if query.lower() == "help":
            print("\nCommands:")
            print("  quit       — Exit")
            print("  categories — List all product categories")
            print("  faq        — Show all FAQs")
            print("  contact    — Show contact info")
            print("  Or type any question to search the knowledge base\n")
            continue
        if query.lower() == "categories":
            print("\nProduct Categories:")
            for p in PRODUCTS.values():
                print(f"  • {p['name']}: {p['description']}")
            print()
            continue
        if query.lower() == "faq":
            print("\nFrequently Asked Questions:")
            for item in FAQ:
                print(f"\nQ: {item['question']}")
                print(f"A: {item['answer']}")
            print()
            continue
        if query.lower() == "contact":
            print(f"\nContact Triad Displays:")
            print(f"  Phone: {COMPANY['phone']}")
            print(f"  Email: {COMPANY['email']}")
            print(f"  Hours: {COMPANY['hours']}\n")
            continue

        # Search
        results = search_knowledge_base(query)
        if results:
            print(f"\nFound {len(results)} result(s):\n")
            for i, r in enumerate(results[:3], 1):
                print(f"{i}. [{r['source']}] {r['title']}")
                print(f"   {r['content'][:200]}{'...' if len(r['content']) > 200 else ''}")
                if r.get("url"):
                    print(f"   URL: {r['url']}")
                print()
        else:
            print(f"\nNo results found for '{query}'.")
            print(f"Try calling {COMPANY['phone']} or emailing {COMPANY['email']}\n")


# ─────────────────────────────────────────────────────────────────────────────
# LIVE AI MODE (requires google-generativeai)
# ─────────────────────────────────────────────────────────────────────────────

def live_ai_mode(api_key: str):
    """
    Interactive mode using live Gemini API.
    Requires: pip install google-generativeai
    """
    try:
        import google.generativeai as genai
    except ImportError:
        print("ERROR: google-generativeai not installed.")
        print("Run: pip install google-generativeai")
        sys.exit(1)

    genai.configure(api_key=api_key)
    model = genai.GenerativeModel(
        model_name="gemini-2.5-flash",
        system_instruction=generate_system_prompt(),
    )
    chat = model.start_chat(history=[])

    print("\n" + "="*60)
    print("  TRIAD DISPLAYS — AI Support (Live Gemini Mode)")
    print("  Type 'quit' to exit")
    print("="*60 + "\n")

    while True:
        try:
            query = input("You: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nGoodbye!")
            break

        if not query:
            continue
        if query.lower() in ("quit", "exit", "q"):
            print("Goodbye!")
            break

        try:
            response = chat.send_message(query)
            print(f"\nAssistant: {response.text}\n")
        except Exception as e:
            print(f"\nError: {e}\n")


# ─────────────────────────────────────────────────────────────────────────────
# CLI ENTRY POINT
# ─────────────────────────────────────────────────────────────────────────────

def main():
    parser = argparse.ArgumentParser(
        description="Triad Displays AI Knowledge Base",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python knowledgebase.py --search "digital menu board"
  python knowledgebase.py --categories
  python knowledgebase.py --faq
  python knowledgebase.py --export-prompt
  python knowledgebase.py --export-json > knowledge.json
  python knowledgebase.py --interactive
  python knowledgebase.py --live-ai --api-key YOUR_GEMINI_KEY
        """,
    )
    parser.add_argument("--search", metavar="QUERY", help="Search the knowledge base")
    parser.add_argument("--categories", action="store_true", help="List all product categories")
    parser.add_argument("--faq", action="store_true", help="Show all FAQs")
    parser.add_argument("--ecosystem", action="store_true", help="Show sister brand ecosystem")
    parser.add_argument("--export-prompt", action="store_true", help="Export Gemini system prompt")
    parser.add_argument("--export-json", action="store_true", help="Export full knowledge base as JSON")
    parser.add_argument("--interactive", action="store_true", help="Interactive Q&A mode (local)")
    parser.add_argument("--live-ai", action="store_true", help="Interactive mode with live Gemini API")
    parser.add_argument("--api-key", metavar="KEY", help="Gemini API key for --live-ai mode")

    args = parser.parse_args()

    if args.search:
        results = search_knowledge_base(args.search)
        if results:
            print(f"\nSearch results for '{args.search}':\n")
            for r in results:
                print(f"[{r['source']}] {r['title']}")
                print(f"  {r['content'][:300]}{'...' if len(r['content']) > 300 else ''}")
                if r.get("url"):
                    print(f"  → {r['url']}")
                print()
        else:
            print(f"No results found for '{args.search}'")

    elif args.categories:
        print("\nTriad Displays — Product Categories:\n")
        for p in PRODUCTS.values():
            print(f"  • {p['name']}")
            print(f"    {p['description']}")
            print(f"    Lead time: {p['lead_time']}")
            print()

    elif args.faq:
        print("\nTriad Displays — FAQ:\n")
        for item in FAQ:
            print(f"Q: {item['question']}")
            print(f"A: {item['answer']}")
            print()

    elif args.ecosystem:
        print("\nTriad Displays — Sister Brand Ecosystem:\n")
        for brand in ECOSYSTEM:
            status = "✅ Live" if brand["status"] == "live" else "🔜 Coming Soon"
            print(f"  {status} {brand['name']}")
            print(f"    {brand['tagline']}")
            if brand["url"]:
                print(f"    {brand['url']}")
            print()

    elif args.export_prompt:
        print(generate_system_prompt())

    elif args.export_json:
        data = {
            "company": COMPANY,
            "products": PRODUCTS,
            "ordering": ORDERING,
            "design_services": DESIGN_SERVICES,
            "ecosystem": ECOSYSTEM,
            "faq": FAQ,
            "generated_at": "2026-07-16T00:00:00Z",
            "version": "2.0",
        }
        print(json.dumps(data, indent=2))

    elif args.live_ai:
        key = args.api_key or input("Enter Gemini API key: ").strip()
        if not key:
            print("ERROR: API key required for live AI mode")
            sys.exit(1)
        live_ai_mode(key)

    elif args.interactive:
        interactive_mode()

    else:
        parser.print_help()
        print(f"\nTriad Displays Knowledge Base v2.0")
        print(f"  Products: {len(PRODUCTS)}")
        print(f"  FAQs: {len(FAQ)}")
        print(f"  Ecosystem brands: {len(ECOSYSTEM)}")
        print(f"  Food images: {DESIGN_SERVICES['food_image_library']['total_images']}")
        print(f"\nContact: {COMPANY['phone']} | {COMPANY['email']}")


if __name__ == "__main__":
    main()
