#!/bin/bash

set -euo pipefail

# Always operate from the script directory (project root)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo "Preparing environment..."

# Ensure .env exists, copy from user's specified location if missing
if [ ! -f .env ]; then
  if [ -f "$HOME/dev/boxone-technical/.env" ]; then
    echo "Copying .env from $HOME/dev/boxone-technical/.env"
    cp "$HOME/dev/boxone-technical/.env" ./.env
  else
    echo "Warning: .env not found and $HOME/dev/boxone-technical/.env is missing"
  fi
fi

echo "Activating virtual environment..."
if [ ! -d venv ]; then
  python3 -m venv venv
fi
source venv/bin/activate

# Install dependencies (non-interactive)
if [ -f requirements.txt ]; then
  python -m pip install -q --upgrade pip
  pip install -q -r requirements.txt
fi

# Determine input PDF: use first arg if provided; otherwise auto-discover under ~/Deleteme
INPUT_PDF="${1:-}"
if [ -z "$INPUT_PDF" ]; then
  echo "No input file provided. Searching for an Uber deck under $HOME/Deleteme..."
  INPUT_PDF=$(find "$HOME/Deleteme" -type f -iname '*uber*deck*.pdf' -print -quit || true)
  if [ -z "$INPUT_PDF" ]; then
    INPUT_PDF=$(find "$HOME/Deleteme" -type f -iname '*uber*.pdf' -print -quit || true)
  fi
  if [ -z "$INPUT_PDF" ]; then
    echo "No Uber deck found. Searching for any PDF under $HOME/Deleteme..."
    INPUT_PDF=$(find "$HOME/Deleteme" -type f -iname '*.pdf' -print -quit || true)
  fi
fi

if [ -z "$INPUT_PDF" ]; then
  echo "Usage: $0 <pdf_file>"
  echo "Or place a PDF under $HOME/Deleteme to auto-detect"
  exit 1
fi

echo "Starting pitch deck parser..."
echo "Processing file: $INPUT_PDF"
echo "----------------------------------------"

python3 app.py "$INPUT_PDF"
