#!/usr/bin/env bash
# Z13 Memory Profiles — GUI picker for unified RAM (GZ302 / Nobara)

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
INSTALL_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
export INSTALL_ROOT CONFIG_FILE="${INSTALL_ROOT}/config/profiles.conf"

# shellcheck source=../lib/memory-profiles.sh
source "${INSTALL_ROOT}/lib/memory-profiles.sh"

SELF="${INSTALL_ROOT}/bin/$(basename "$0")"

die_gui() {
    zenity --error --width=420 --title="Z13 Memory Profiles" --text="$1" 2>/dev/null || {
        echo "ERROR: $1" >&2
        exit 1
    }
    exit 1
}

need_zenity() {
    command -v zenity >/dev/null 2>&1 || die_gui "zenity is required.\n\nInstall: sudo dnf install zenity"
}

run_privileged() {
    if [[ "${EUID}" -eq 0 ]]; then
        "$@"
    elif command -v pkexec >/dev/null 2>&1; then
        pkexec "$@"
    else
        die_gui "pkexec not found.\n\nInstall: sudo dnf install polkit\nOr run: sudo ${SELF} --apply <profile>"
    fi
}

profile_summary() {
    local profile="$1"
    local label desc carveout ttm_action ttm_gb
    label="$(read_profile_value "${profile}" label)"
    desc="$(read_profile_value "${profile}" description)"
    carveout="$(read_profile_value "${profile}" carveout_target_mb)"
    ttm_action="$(read_profile_value "${profile}" ttm_action)"
    ttm_gb="$(read_profile_value "${profile}" ttm_gb)"

    local ttm_text
    if [[ "${ttm_action}" == "clear" ]]; then
        ttm_text="default (clear custom TTM)"
    else
        ttm_text="${ttm_gb} GB dynamic"
    fi

    printf '%s\n\n%s\n\nFixed VRAM target: %s MB\nDynamic GPU pool: %s\n\nRequires reboot.' \
        "${label}" "${desc}" "${carveout}" "${ttm_text}"
}

gui_main() {
    need_zenity

    local total_gb uma_note
    total_gb="$(total_ram_gb)"
    if find_uma_base >/dev/null 2>&1; then
        uma_note="UMA sysfs: available"
    else
        uma_note="UMA sysfs: not found — fixed VRAM may need Windows Armoury Crate"
    fi

    local choice
    choice="$(zenity --list --title="Z13 Memory Profiles" --width=520 --height=360 \
        --text="ROG Flow Z13 unified memory (~${total_gb} GB RAM)\n${uma_note}\n\nPick a profile (reboot required):" \
        --column="Profile" --column="Use case" \
        "gaming" "Gaming — 8 GB fixed VRAM, default dynamic pool" \
        "llm" "LLM / AI — min fixed VRAM, 48 GB dynamic pool" \
        "reset" "Reset — 4 GB fixed VRAM, default dynamic pool" \
        "status" "Show current settings (no changes)" \
        "discover" "Print full status to terminal" \
        2>/dev/null)" || exit 0

    case "${choice}" in
        status)
            local info
            info="$(show_status 2>&1)"
            zenity --text-info --title="Z13 Memory Status" --width=620 --height=480 --font=monospace <<<"${info}"
            gui_main
            ;;
        discover)
            xterm -e "bash -lc '${SELF} --status; echo; read -p \"Press Enter...\"'" 2>/dev/null \
                || konsole -e bash -lc "${SELF} --status; read -p 'Press Enter...'" 2>/dev/null \
                || {
                    show_status
                    read -r -p "Press Enter..."
                }
            gui_main
            ;;
        gaming|llm|reset)
            local summary confirm
            summary="$(profile_summary "${choice}")"
            if ! validate_msg="$(validate_profile "${choice}" 2>&1)"; then
                die_gui "${validate_msg}\n\nEdit ${CONFIG_FILE} if your RAM size differs."
            fi
            confirm="$(zenity --question --title="Confirm reboot" --width=480 \
                --text="${summary}\n\nApply this profile and reboot now?" \
                --ok-label="Apply & Reboot" --cancel-label="Cancel" 2>/dev/null && echo yes || echo no)"
            [[ "${confirm}" == "yes" ]] || exit 0

            local tmpout
            tmpout="$(mktemp)"
            if ! run_privileged "${SELF}" --apply "${choice}" >"${tmpout}" 2>&1; then
                die_gui "Failed to apply profile:\n\n$(cat "${tmpout}")"
            fi

            zenity --info --title="Rebooting" --width=420 \
                --text="Profile applied.\n\n$(cat "${tmpout}")\n\nRebooting in 5 seconds..." 2>/dev/null || true
            sleep 5
            run_privileged systemctl reboot
            ;;
    esac
}

usage() {
    cat <<EOF
Usage: $(basename "$0") [OPTIONS]

  (no args)          Open zenity profile picker
  --gui              Same as no args
  --status           Print current memory settings
  --discover         Alias for --status
  --apply PROFILE    Apply gaming|llm|reset (root/pkexec)
  --validate PROFILE Check profile fits this machine
  -h, --help         Show help

Install: ${INSTALL_ROOT}/install.sh
EOF
}

main() {
    case "${1:-}" in
        ""|--gui)
            gui_main
            ;;
        --status|--discover)
            show_status
            ;;
        --apply)
            [[ -n "${2:-}" ]] || { echo "Missing profile name" >&2; exit 1; }
            apply_profile "$2"
            ;;
        --validate)
            [[ -n "${2:-}" ]] || { echo "Missing profile name" >&2; exit 1; }
            validate_profile "$2"
            ;;
        -h|--help)
            usage
            ;;
        *)
            echo "Unknown option: $1" >&2
            usage
            exit 1
            ;;
    esac
}

main "$@"
