#!/bin/bash
set -e

# Auto-provision Lychee Rust Binary if missing
if [ ! -f ./lychee ]; then
  echo "📥 Downloading Lychee Link Checker (v0.15.1)..."

  OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
  ARCH="$(uname -m)"
  VERSION="lychee-v0.23.0"

  if [ "$ARCH" = "x86_64" ] || [ "$ARCH" = "amd64" ]; then
    ARCH_MAPPED="x86_64"
  elif [ "$ARCH" = "aarch64" ] || [ "$ARCH" = "arm64" ]; then
    ARCH_MAPPED="aarch64"
  else
    echo "❌ Unsupported architecture: $ARCH"
    exit 1
  fi

  if [ "$OS" = "darwin" ]; then
    TARGET="arm64-macos"
  elif [ "$OS" = "linux" ]; then
    TARGET="${ARCH_MAPPED}-unknown-linux-gnu"
  else
    echo "❌ Unsupported OS: $OS"
    exit 1
  fi

  DOWNLOAD_URL="https://github.com/lycheeverse/lychee/releases/download/${VERSION}/lychee-${TARGET}.tar.gz"
  echo "Downloading from $DOWNLOAD_URL"

  curl -sSLo lychee.tar.gz "$DOWNLOAD_URL"
  tar -xzf lychee.tar.gz lychee
  rm lychee.tar.gz
  chmod +x ./lychee
fi

echo "🚀 Starting Deep Link Assessment (Lychee)..."

# Exclude localhost, mintel.me (internal infrastructure), and common placeholder domains
# Scan markdown files and component files for hardcoded dead links
./lychee \
  --exclude "localhost" \
  --exclude "127.0.0.1" \
  --exclude "mintel\.me" \
  --exclude "example\.com" \
  --exclude "linkedin\.com" \
  --exclude "fonts\." \
  --base-url "http://127.0.0.1" \
  --accept 200,204,308,401,403,999 \
  "./app/**/*.tsx" "./components/**/*.tsx"

echo "✅ All project source links are alive and healthy!"
