#!/usr/bin/env bash
# Competitor Analyzer — gather competitive intelligence on any company
# Usage: ./analyze.sh <company_name_or_url>
set -euo pipefail

COMPANY="${1:?Usage: ./analyze.sh <company_name_or_url>}"
OUTFILE="competitor-report-$(echo "$COMPANY" | tr ' /' '-' | tr '[:upper:]' '[:lower:]').md"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M')

# Strip protocol for search-friendly name
SEARCH_NAME=$(echo "$COMPANY" | sed 's|https\?://||;s|/.*||;s|www\.||')

echo "🦞 Competitor Analyzer — Analyzing: $SEARCH_NAME"
echo "================================================="
echo ""

# Function to search via DuckDuckGo HTML (no API key needed)
search() {
  local query="$1"
  curl -sL "https://html.duckduckgo.com/html/?q=$(python3 -c "import urllib.parse; print(urllib.parse.quote('$query'))")" \
    -H "User-Agent: Mozilla/5.0" 2>/dev/null | \
    python3 -c "
import sys, re, html
content = sys.stdin.read()
results = re.findall(r'class=\"result__snippet\">(.*?)</a>', content, re.DOTALL)
for i, r in enumerate(results[:5]):
    text = html.unescape(re.sub(r'<[^>]+>', '', r)).strip()
    if text:
        print(f'- {text}')
" 2>/dev/null || echo "- (search unavailable — run with an AI agent for better results)"
}

echo "🔍 Searching for company overview..."
OVERVIEW=$(search "$SEARCH_NAME company overview what do they do")

echo "💰 Searching for pricing info..."
PRICING=$(search "$SEARCH_NAME pricing plans cost")

echo "📱 Searching for social presence..."
SOCIAL=$(search "$SEARCH_NAME twitter linkedin social media followers")

echo "📰 Searching for recent news..."
NEWS=$(search "$SEARCH_NAME news announcements 2025 2026")

echo "⚔️ Searching for competitors..."
COMPETITORS=$(search "$SEARCH_NAME competitors alternatives vs")

# Generate report
cat > "$OUTFILE" << EOF
# Competitive Analysis: $SEARCH_NAME
*Generated: $TIMESTAMP*

---

## 🏢 Company Overview
$OVERVIEW

## 💰 Pricing & Plans
$PRICING

## 📱 Social Presence
$SOCIAL

## 📰 Recent News
$NEWS

## ⚔️ Competitors & Alternatives
$COMPETITORS

---

## 📊 Quick Assessment

| Category | Notes |
|----------|-------|
| Market Position | See overview above |
| Pricing Model | See pricing section |
| Social Reach | See social section |
| Recent Momentum | See news section |

---
*Report generated by Competitor Analyzer 🦞 — a ClawHub skill by Shelly*
EOF

echo ""
echo "✅ Report saved to: $OUTFILE"
echo ""
cat "$OUTFILE"
