#!/bin/bash
#
# Company Lookup Script using mcpc + Apify RAG Web Browser
#
# This is an example of an AI-generated "code mode" script that uses mcpc
# to call MCP tools programmatically. It was generated by Claude Code + Opus 4.5.
#
# Prerequisites:
#   1. Install mcpc: npm install -g @apify/mcpc
#   2. Login to Apify MCP server: mcpc login mcp.apify.com
#   3. Create a session: mcpc connect mcp.apify.com @apify
#
# Usage:
#   ./company-lookup.sh "Company Name"
#
# Example:
#   ./company-lookup.sh "Stripe"
#   ./company-lookup.sh "Anthropic"
#

set -e

# Configuration
SESSION="${MCPC_SESSION:-@apify}"
REQUIRED_TOOL="apify-slash-rag-web-browser"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Helper functions
error() { echo -e "${RED}❌ Error: $1${NC}" >&2; exit 1; }
info() { echo -e "${BLUE}$1${NC}"; }
success() { echo -e "${GREEN}$1${NC}"; }
warn() { echo -e "${YELLOW}$1${NC}"; }

# Check if mcpc is installed
if ! command -v mcpc &> /dev/null; then
    error "mcpc is not installed. Install it with: npm install -g @apify/mcpc"
fi

# Parse arguments
COMPANY="${1:-}"
if [ -z "$COMPANY" ]; then
    echo "Usage: $0 \"Company Name\""
    echo ""
    echo "Examples:"
    echo "  $0 \"Stripe\""
    echo "  $0 \"Anthropic\""
    echo ""
    echo "Environment variables:"
    echo "  MCPC_SESSION  Session to use (default: @apify)"
    exit 1
fi

# Check if the session exists and is live
info "🔌 Checking session ${SESSION}..."

SESSION_STATUS=$(mcpc --json 2>/dev/null | jq -r ".sessions[] | select(.name == \"${SESSION}\") | .status" 2>/dev/null || echo "")

if [ -z "$SESSION_STATUS" ]; then
    echo ""
    error "Session ${SESSION} not found.

To set up the required session:
  1. Login to Apify: mcpc login mcp.apify.com
  2. Create session: mcpc connect mcp.apify.com ${SESSION}

Or use a different session by setting MCPC_SESSION environment variable."
fi

if [ "$SESSION_STATUS" = "expired" ]; then
    error "Session ${SESSION} has expired. Please recreate it:
  mcpc close ${SESSION}
  mcpc connect mcp.apify.com ${SESSION}"
fi

if [ "$SESSION_STATUS" = "crashed" ]; then
    warn "⚠️  Session ${SESSION} has crashed, will attempt to restart..."
fi

# Verify the required tool is available
info "🔧 Checking for required tool..."

TOOL_EXISTS=$(mcpc --json "${SESSION}" tools-list 2>/dev/null | jq -r ".[] | select(.name == \"${REQUIRED_TOOL}\") | .name" 2>/dev/null || echo "")

if [ -z "$TOOL_EXISTS" ]; then
    error "Required tool '${REQUIRED_TOOL}' not found on server.
Make sure you're connected to the correct MCP server (mcp.apify.com)."
fi

# All checks passed, proceed with the lookup
echo ""
info "🔍 Looking up: $COMPANY"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
info "⏳ Searching the web..."
echo ""

# Build the query - company name + search terms
QUERY="${COMPANY} company headquarters address"

# Use mcpc with the RAG web browser to fetch results as JSON
RESULT=$(mcpc "${SESSION}" tools-call "${REQUIRED_TOOL}" \
    query:="$QUERY" \
    maxResults:=1 \
    outputFormats:='["markdown"]' \
    --json 2>/dev/null) || error "Failed to call tool. Check your session and try again."

# Parse the markdown from the result
MARKDOWN=$(echo "$RESULT" \
    | jq -r '.content[0].text // empty' 2>/dev/null \
    | jq -r '.[0].markdown // empty' 2>/dev/null)

# Check if we got results
if [ -z "$MARKDOWN" ]; then
    warn "⚠️  No results found for '$COMPANY'"
    echo ""
    echo "Raw response:"
    echo "$RESULT" | jq '.' 2>/dev/null || echo "$RESULT"
    exit 1
fi

echo "📄 Company Information:"
echo "────────────────────────────────────────────────────"
# Show first 50 lines of markdown
echo "$MARKDOWN" | head -50

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
success "✅ Done"
