#!/usr/bin/env bash
set -euo pipefail

PACKAGE_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
INSTALL_ROOT="$HOME/.orc-local"
PLIST="$HOME/Library/LaunchAgents/com.thanganhai.orc-local.plist"

echo "Installing ORC Local to $INSTALL_ROOT"
mkdir -p "$INSTALL_ROOT"
rm -rf "$INSTALL_ROOT/app" "$INSTALL_ROOT/backend" "$INSTALL_ROOT/scripts" "$INSTALL_ROOT/tools"
cp -R "$PACKAGE_ROOT/app" "$INSTALL_ROOT/app"
cp -R "$PACKAGE_ROOT/backend" "$INSTALL_ROOT/backend"
cp -R "$PACKAGE_ROOT/scripts" "$INSTALL_ROOT/scripts"
cp -R "$PACKAGE_ROOT/tools" "$INSTALL_ROOT/tools"
cp "$PACKAGE_ROOT/README.md" "$INSTALL_ROOT/README.md" 2>/dev/null || true

cd "$INSTALL_ROOT"
python3 -m venv .venv
"$INSTALL_ROOT/.venv/bin/python" -m pip install --upgrade pip
"$INSTALL_ROOT/.venv/bin/python" -m pip install -r "$INSTALL_ROOT/backend/requirements.txt"
"$INSTALL_ROOT/.venv/bin/python" -m pip install -e "$INSTALL_ROOT/backend"

if command -v brew >/dev/null 2>&1; then
  brew list tesseract >/dev/null 2>&1 || brew install tesseract
  brew list tesseract-lang >/dev/null 2>&1 || brew install tesseract-lang
else
  echo "Homebrew was not found. Install Tesseract manually if OCR language data is missing."
fi

mkdir -p "$HOME/Library/LaunchAgents"
cat > "$PLIST" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>com.thanganhai.orc-local</string>
  <key>ProgramArguments</key>
  <array>
    <string>$INSTALL_ROOT/.venv/bin/python</string>
    <string>-m</string>
    <string>pdf_to_md_local.server</string>
    <string>--host</string>
    <string>127.0.0.1</string>
    <string>--port</string>
    <string>8765</string>
  </array>
  <key>WorkingDirectory</key>
  <string>$INSTALL_ROOT</string>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>$INSTALL_ROOT/orc-local.log</string>
  <key>StandardErrorPath</key>
  <string>$INSTALL_ROOT/orc-local.err.log</string>
</dict>
</plist>
PLIST

launchctl unload "$PLIST" >/dev/null 2>&1 || true
launchctl load "$PLIST"
open "http://127.0.0.1:8765/"
echo "ORC Local installed. It will start automatically when you sign in."
