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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
START_SCRIPT="$ROOT_DIR/scripts/autostart/startup-all.sh"
LABEL="com.online-clinic.startup"
LEGACY_LABEL="com.online-clinic.api"
SERVICE_NAME="online-clinic-startup.service"
LEGACY_SERVICE_NAME="online-clinic-api.service"

if [[ ! -x "$START_SCRIPT" ]] && [[ -f "$START_SCRIPT" ]]; then
  chmod +x "$START_SCRIPT"
fi

[[ -f "$START_SCRIPT" ]] || { echo "Missing $START_SCRIPT"; exit 1; }

case "$(uname -s)" in
  Darwin)
    for old_label in "$LEGACY_LABEL" "$LABEL"; do
      launchctl bootout "gui/$(id -u)/${old_label}" 2>/dev/null || true
      rm -f "$HOME/Library/LaunchAgents/${old_label}.plist"
    done

    PLIST="$HOME/Library/LaunchAgents/${LABEL}.plist"
    mkdir -p "$HOME/Library/LaunchAgents"

    cat >"$PLIST" <<EOF
<?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>${LABEL}</string>
  <key>ProgramArguments</key>
  <array>
    <string>/bin/bash</string>
    <string>${START_SCRIPT}</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <false/>
  <key>StandardOutPath</key>
  <string>${ROOT_DIR}/backend/storage/logs/clinic-startup.log</string>
  <key>StandardErrorPath</key>
  <string>${ROOT_DIR}/backend/storage/logs/clinic-startup.log</string>
  <key>WorkingDirectory</key>
  <string>${ROOT_DIR}</string>
</dict>
</plist>
EOF

    launchctl bootstrap "gui/$(id -u)" "$PLIST"
    launchctl enable "gui/$(id -u)/${LABEL}"
    launchctl kickstart -k "gui/$(id -u)/${LABEL}" 2>/dev/null || bash "$START_SCRIPT"

    echo "macOS LaunchAgent installed: $PLIST"
    echo "On login: composer update, npm update, npm run build, php artisan serve, npm run dev"
    echo "Remove: bash scripts/uninstall.sh"
    ;;

  Linux)
    for old_service in "$LEGACY_SERVICE_NAME" "$SERVICE_NAME"; do
      systemctl --user disable "$old_service" 2>/dev/null || true
      systemctl --user stop "$old_service" 2>/dev/null || true
      rm -f "${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/$old_service"
    done

    UNIT_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"
    UNIT_FILE="$UNIT_DIR/$SERVICE_NAME"
    mkdir -p "$UNIT_DIR"

    cat >"$UNIT_FILE" <<EOF
[Unit]
Description=Online Clinic startup (deps, build, API, Vite dev)
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=${ROOT_DIR}
ExecStart=/bin/bash ${START_SCRIPT}
ExecStop=/bin/bash -c '${ROOT_DIR}/scripts/stop-api.sh; ${ROOT_DIR}/scripts/stop-dev.sh'

[Install]
WantedBy=default.target
EOF

    systemctl --user daemon-reload
    systemctl --user enable "$SERVICE_NAME"
    systemctl --user start "$SERVICE_NAME" || bash "$START_SCRIPT"

    echo "systemd user service installed: $UNIT_FILE"
    echo "On login: composer update, npm update, npm run build, php artisan serve, npm run dev"
    echo "Status: systemctl --user status $SERVICE_NAME"
    echo "Boot without login: sudo loginctl enable-linger \$USER"
    echo "Remove: bash scripts/uninstall.sh"
    ;;

  *)
    echo "Unsupported OS. Run manually: bash scripts/autostart/startup-all.sh"
    echo "Or add scripts/autostart/startup-all.sh to your desktop session autostart."
    exit 1
    ;;
esac
