#!/bin/bash
# Noba Command Center Launcher (v1.6.1)

set -euo pipefail

# Determine paths (installed via ~/.local)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PREFIX="$(dirname "$SCRIPT_DIR")"
LIBEXEC_DIR="$PREFIX/libexec/noba"
LIB_DIR="$LIBEXEC_DIR/lib"
WEB_DIR="$LIBEXEC_DIR/web"

# Source shared functions
source "$LIB_DIR/noba-lib.sh"

# Defaults
PORT=8080
HOST="0.0.0.0"
HTML_DIR="$WEB_DIR" # Now permanently points to the deployed ~/.../web directory
SERVER_PID_FILE="${SERVER_PID_FILE:-/tmp/noba-web-server.pid}"
SERVER_URL_FILE="${SERVER_URL_FILE:-/tmp/noba-web-server.url}"
LOG_FILE="${LOG_FILE:-/tmp/noba-web.log}"
KILL_ONLY=false
RESTART=false
VERBOSE=false
SET_PASSWORD=false
SHOW_STATUS=false
GEN_SYSTEMD=false
NOBA_YAML="${NOBA_CONFIG:-$HOME/.config/noba/config.yaml}"

# User management flags
ADD_USER=false
LIST_USERS=false
REMOVE_USER=false
CHANGE_PASS=false
USERNAME=""
PASSWORD=""
ROLE="viewer"

# Source optional config
CONFIG_FILE="${HOME}/.config/noba-web.conf"
# shellcheck source=/dev/null
if [[ -f "$CONFIG_FILE" ]]; then
    source "$CONFIG_FILE"
fi

# Parse arguments
PARSED_ARGS=$(getopt -o kv -l host:,kill,verbose,help,version,set-password,restart,status,generate-systemd,add-user,list-users,remove-user:,change-password -- "$@" 2>/dev/null) || {
    log_error "Invalid argument. Run with --help for usage."
    exit 1
}
eval set -- "$PARSED_ARGS"

while true; do
    case "$1" in
        --host)
            HOST="$2"
            shift 2
            ;;
        -k|--kill)
            KILL_ONLY=true
            shift
            ;;
        -v|--verbose)
            VERBOSE=true
            shift
            ;;
        --set-password)
            SET_PASSWORD=true
            shift
            ;;
        --restart)
            KILL_ONLY=true
            RESTART=true
            shift
            ;;
        --status)
            SHOW_STATUS=true
            shift
            ;;
        --generate-systemd)
            GEN_SYSTEMD=true
            shift
            ;;
        --add-user)
            ADD_USER=true
            shift
            ;;
        --list-users)
            LIST_USERS=true
            shift
            ;;
        --remove-user)
            REMOVE_USER=true
            USERNAME="$2"
            shift 2
            ;;
        --change-password)
            CHANGE_PASS=true
            shift
            ;;
        --help)
            show_help
            exit 0
            ;;
        --version)
            echo "noba-web version 1.6.1"
            exit 0
            ;;
        --)
            shift
            break
            ;;
        *)
            log_error "Unknown argument: $1"
            exit 1
            ;;
    esac
done

# Handle user management commands (interactive)
if [[ "$ADD_USER" == true ]]; then
    read -rp "Username: " username
    read -rs -p "Password: " password
    echo
    read -rs -p "Confirm password: " password2
    echo
    if [[ "$password" != "$password2" ]]; then
        log_error "Passwords do not match."
        exit 1
    fi
    read -rp "Role (admin/viewer) [viewer]: " role
    role=${role:-viewer}
    add_user "$username" "$password" "$role"
    exit 0
fi

if [[ "$LIST_USERS" == true ]]; then
    list_users
    exit 0
fi

if [[ "$REMOVE_USER" == true ]]; then
    remove_user "$USERNAME"
    exit 0
fi

if [[ "$CHANGE_PASS" == true ]]; then
    read -rp "Username: " username
    read -rs -p "New password: " password
    echo
    read -rs -p "Confirm new password: " password2
    echo
    if [[ "$password" != "$password2" ]]; then
        log_error "Passwords do not match."
        exit 1
    fi
    change_password "$username" "$password"
    exit 0
fi

# Handle special commands (non-server)
if [[ "$SHOW_STATUS" == true ]]; then
    show_status "$SERVER_PID_FILE" "$SERVER_URL_FILE" "$LOG_FILE"
    exit 0
fi

if [[ "$GEN_SYSTEMD" == true ]]; then
    generate_systemd "$0" "$HOST"
    exit 0
fi

if [[ "$SET_PASSWORD" == true ]]; then
    set_password "$NOBA_YAML"
    exit 0
fi

if [[ "$KILL_ONLY" == true ]]; then
    kill_server "$SERVER_PID_FILE" "$SERVER_URL_FILE" "$HTML_DIR"
    if [[ "$RESTART" != true ]]; then
        exit 0
    fi
fi

# Check dependencies
check_deps python3 yq

# Verify yq is the Go version
if ! yq --version 2>/dev/null | grep -q "mikefarah"; then
    log_error "'yq' must be the Go version (mikefarah/yq). Install from https://github.com/mikefarah/yq"
    exit 1
fi

# Python version check
PYTHON_VERSION=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")' 2>/dev/null || echo "0.0")
if ! awk -v ver="$PYTHON_VERSION" 'BEGIN { split(ver,v,"."); exit !(v[1]>3||(v[1]==3&&v[2]>=7)); }'; then
    log_error "Python 3.7+ required (found $PYTHON_VERSION)."
    exit 1
fi

# Prepare runtime directory from installed files
if [[ ! -d "$WEB_DIR" ]]; then
    log_error "Web components not found at $WEB_DIR. Please run install.sh first."
    exit 1
fi

# Ensure YAML config exists
create_default_yaml "$NOBA_YAML"

# Kill any existing server (if restarting)
if [[ "$RESTART" == true ]]; then
    kill_server "$SERVER_PID_FILE" "$SERVER_URL_FILE" "$HTML_DIR"

    log_info "Waiting for port $PORT to be released..."
    for i in {1..10}; do
        if ! ss -ltn 2>/dev/null | grep -q ":$PORT " && ! lsof -i ":$PORT" -t &>/dev/null; then
            break
        fi
        sleep 1
    done
fi

# Launch server directly from the persistent path
export PORT HOST PID_FILE="$SERVER_PID_FILE" NOBA_SCRIPT_DIR="$HOME/.local/bin" NOBA_CONFIG="$NOBA_YAML"
cd "$HTML_DIR"
: > "$LOG_FILE"

nohup python3 server.py >> "$LOG_FILE" 2>&1 &
SERVER_PID=$!
echo "$SERVER_PID" > "$SERVER_PID_FILE"

DISPLAY_IP=$(local_ip)
echo "http://${DISPLAY_IP}:${PORT}" > "$SERVER_URL_FILE"

# Wait for server to be healthy
MAX_WAIT=10
WAITED=0
while true; do
    if command -v curl &>/dev/null; then
        CODE=$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:${PORT}/api/health" 2>/dev/null || true)
    elif command -v wget &>/dev/null; then
        CODE=$(wget -qO- "http://127.0.0.1:${PORT}/api/health" 2>/dev/null \
               | python3 -c "import sys,json; print(200 if json.load(sys.stdin).get('status')=='ok' else 0)" 2>/dev/null || true)
    else
        log_error "Neither curl nor wget found."
        exit 1
    fi

    if [[ "$CODE" == "200" ]]; then
        break
    fi

    sleep 1
    WAITED=$((WAITED+1))

    if [[ $WAITED -ge $MAX_WAIT ]]; then
        log_error "Server did not respond within ${MAX_WAIT}s. Last 20 lines of log:"
        tail -20 "$LOG_FILE" | sed 's/^/  /' >&2
        kill "$SERVER_PID" 2>/dev/null || true
        exit 1
    fi
done

log_success "Dashboard live → http://${DISPLAY_IP}:${PORT}"

# If verbose, tail log
if [[ "$VERBOSE" == true ]]; then
    log_info "Tailing log (Ctrl+C to stop)…"
    tail -f "$LOG_FILE" &
    TAIL_PID=$!
fi

wait "$SERVER_PID"
if [[ -n "${TAIL_PID:-}" ]]; then
    kill "$TAIL_PID" 2>/dev/null || true
fi
