#!/usr/bin/env bash

# Start the AuditWhizz AutoExtract app on Windows (Git Bash / WSL-compatible)
# - Designed to be launched by Windows Task Scheduler using Git Bash
# - Works from any location; resolves repo root relative to this script
# - Logs are appended to logs/app_debug.log

set -euo pipefail

# Resolve repository root (this file is expected in repo_root/scripts/)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
cd "${REPO_ROOT}"

# Optional: update repo on start (default: disabled on Windows)
# Set UPDATE_ON_START=1 in the Task Scheduler action (Arguments) to enable
UPDATE_ON_START="${UPDATE_ON_START:-0}"
if [[ "${UPDATE_ON_START}" == "1" ]] && command -v git >/dev/null 2>&1; then
  echo "[start_windows] Updating repository..."
  git fetch --prune || true
  # Prefer origin/main if it exists; otherwise skip hard reset
  if git rev-parse --verify origin/main >/dev/null 2>&1; then
    git reset --hard origin/main || true
  fi
fi

# Ensure logs directory exists
mkdir -p logs

# Activate Python virtual environment (Windows layout first, then POSIX fallback)
if [[ -f "venv/Scripts/activate" ]]; then
  # shellcheck disable=SC1091
  source "venv/Scripts/activate"
elif [[ -f "venv/bin/activate" ]]; then
  # shellcheck disable=SC1091
  source "venv/bin/activate"
fi

# Choose Python from venv when available
PYTHON_BIN="${PYTHON_BIN:-python}"
if [[ -x "venv/Scripts/python.exe" ]]; then
  PYTHON_BIN="venv/Scripts/python.exe"
elif command -v python3 >/dev/null 2>&1; then
  PYTHON_BIN="python3"
fi

echo "[start_windows] Using Python: ${PYTHON_BIN}"
echo "[start_windows] Repo root: ${REPO_ROOT}"

# Run the app (GUI). Append logs; keep process attached for Task Scheduler.
exec "${PYTHON_BIN}" main.py >> "logs/app_debug.log" 2>&1


