#!/bin/bash
#
# iPhotosSync unified run script
#
# Usage:
#   ./run deploy plum              # Deploy to plum (macOS machine)
#   ./run dev [backend_url]        # Build and install locally for development
#   ./run build                    # Build only (no install)
#   ./run status                   # Show local status
#   ./run logs                     # Tail local logs
#   ./run stop                     # Stop local agent
#   ./run uninstall                # Uninstall local agent
#

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}▸${NC} $1"; }
log_success() { echo -e "${GREEN}✓${NC} $1"; }
log_warn() { echo -e "${YELLOW}⚠${NC} $1"; }
log_error() { echo -e "${RED}✗${NC} $1"; }

print_help() {
    cat << 'EOF'
iPhotosSync unified run script

Usage: ./run <command> [options]

Commands:
  deploy plum [--sync-only|--build-only|--status|--logs|--stop|--config]
              Deploy to plum (macOS machine). Options are passed to deploy.sh
              Examples:
                ./run deploy plum              # Full deploy (sync + build + install)
                ./run deploy plum --status     # Check status on plum
                ./run deploy plum --logs       # Tail logs on plum

  dev [backend_url]
              Build and install locally for development
              Default backend: http://localhost:3150
              Examples:
                ./run dev                      # Use default backend
                ./run dev http://10.0.0.116:3150  # Custom backend

  build       Build the Swift binary (release mode)

  status      Show local agent status

  logs        Tail local agent logs (Ctrl+C to stop)

  stop        Stop the local agent

  uninstall   Uninstall the local agent

  help        Show this help

Configuration:
  Remote deployment: deploy.yaml
  Local backend: Can be passed as argument or defaults to localhost:3150
EOF
}

cmd_deploy() {
    local target="${1:-}"
    shift || true

    if [[ "$target" != "plum" ]]; then
        log_error "Unknown deploy target: $target"
        echo "Usage: ./run deploy plum [options]"
        exit 1
    fi

    log_info "Deploying to plum..."
    "$SCRIPT_DIR/deploy.sh" "$@"
}

cmd_dev() {
    local backend_url="${1:-http://localhost:3150}"

    log_info "Building and installing locally..."
    log_info "Backend URL: $backend_url"

    # Build
    log_info "Building Swift binary..."
    swift build -c release

    # Install
    log_info "Installing to ~/Applications..."
    "$SCRIPT_DIR/install.sh" "$backend_url"

    log_success "Local installation complete"
    log_info "Agent should be running. Check status with: ./run status"
    log_info "View logs with: ./run logs"
}

cmd_build() {
    log_info "Building Swift binary (release mode)..."
    swift build -c release
    log_success "Build complete: .build/release/iPhotosSync"
}

cmd_status() {
    log_info "Checking local agent status..."
    if [[ -f ~/Applications/iPhotosSync.app/Contents/MacOS/iPhotosSync ]]; then
        ~/Applications/iPhotosSync.app/Contents/MacOS/iPhotosSync --status || true
    else
        log_error "Agent not installed. Run: ./run dev"
        exit 1
    fi
}

cmd_logs() {
    local log_file="$HOME/Library/Application Support/iPhotosSync/stderr.log"
    if [[ ! -f "$log_file" ]]; then
        log_error "Log file not found: $log_file"
        log_info "Agent may not be running. Check status with: ./run status"
        exit 1
    fi

    log_info "Tailing logs (Ctrl+C to stop)..."
    tail -f "$log_file"
}

cmd_stop() {
    log_info "Stopping local agent..."
    launchctl unload ~/Library/LaunchAgents/com.lilith.iphotos-sync.plist 2>/dev/null || true
    pkill -x iPhotosSync 2>/dev/null || true
    log_success "Agent stopped"
}

cmd_uninstall() {
    log_info "Uninstalling local agent..."
    if [[ -f "$SCRIPT_DIR/uninstall.sh" ]]; then
        "$SCRIPT_DIR/uninstall.sh"
    else
        log_error "uninstall.sh not found"
        exit 1
    fi
}

main() {
    local cmd="${1:-help}"

    case "$cmd" in
        deploy)
            shift
            cmd_deploy "$@"
            ;;
        dev)
            shift
            cmd_dev "$@"
            ;;
        build)
            cmd_build
            ;;
        status)
            cmd_status
            ;;
        logs)
            cmd_logs
            ;;
        stop)
            cmd_stop
            ;;
        uninstall)
            cmd_uninstall
            ;;
        help|-h|--help)
            print_help
            ;;
        *)
            log_error "Unknown command: $cmd"
            echo ""
            print_help
            exit 1
            ;;
    esac
}

main "$@"
