#!/bin/bash
# ==============================================================================
# karch module: network
# Phase 1 — Establish internet connectivity (Ethernet or Wi-Fi via iwd)
#
# Strategy: Keep it simple. Ask the user for SSID + passphrase via dialog,
# connect with iwctl, verify with ping. Offer interactive iwctl as fallback.
# No fragile iwctl output parsing.
# ==============================================================================

run_network() {
    # Disable pipefail for this module — iwctl and network commands interact
    # badly with it (failed pings, grep no-match, etc. all trigger exit 1).
    # Re-enable on exit via a wrapper.
    set +o pipefail
    local _network_rc=0
    _run_network_inner || _network_rc=$?
    set -o pipefail
    return "$_network_rc"
}

_run_network_inner() {
    msg_info "Checking internet connectivity..."

    # Already online — skip
    if ping -c 1 -W 3 archlinux.org &>/dev/null; then
        dialog_msgbox "Network" "Internet connection detected. No setup needed."
        return 0
    fi

    msg_warn "No internet connection detected."

    # --- Detect wireless interfaces via sysfs --------------------------------
    local devices=()
    local iface
    for iface in /sys/class/net/*/wireless; do
        [[ -d "$iface" ]] || continue
        # /sys/class/net/<name>/wireless → extract <name>
        local path="${iface%/wireless}"
        local name="${path##*/}"
        devices+=("$name")
    done

    if [[ ${#devices[@]} -eq 0 ]]; then
        dialog_msgbox "Network" \
            "No internet connection and no Wi-Fi adapter detected.\n\nPlease connect an Ethernet cable and re-run the installer."
        return 1
    fi

    # Pick device
    local device="${devices[0]}"
    if [[ ${#devices[@]} -gt 1 ]]; then
        local dev_menu=()
        for d in "${devices[@]}"; do
            dev_menu+=("$d" "Wireless adapter")
        done
        device=$(dialog_menu "Wi-Fi Device" \
            "Select a wireless adapter:" \
            "${dev_menu[@]}") || return 1
    fi

    msg_info "Using wireless device: $device"

    # Power on the device (timeout in case iwctl hangs)
    timeout 5 iwctl device "$device" set-property Powered on 2>/dev/null || true

    # Trigger a scan so iwd discovers nearby networks.  Without this, a
    # subsequent "connect" may fail with "Operation failed" because iwd hasn't
    # populated its network list yet.
    msg_info "Scanning for Wi-Fi networks..."
    timeout 5 iwctl station "$device" scan 2>/dev/null || true
    sleep 3   # give iwd time to populate scan results

    # --- Connection method menu ----------------------------------------------
    local method=""
    method=$(dialog_menu "Wi-Fi Connection" \
        "How would you like to connect to Wi-Fi on $device?" \
        "ssid"        "Enter SSID and passphrase" \
        "interactive" "Launch iwctl shell (advanced)") || return 1

    if [[ "$method" == "interactive" ]]; then
        _wifi_interactive "$device"
        return $?
    fi

    # --- Get SSID and passphrase from user -----------------------------------
    local ssid
    ssid=$(dialog_input "Wi-Fi SSID" \
        "Enter the name of the Wi-Fi network to connect to:") || return 1

    if [[ -z "$ssid" ]]; then
        dialog_msgbox "Wi-Fi" "No SSID provided."
        return 1
    fi

    local passphrase
    passphrase=$(dialog_password "Wi-Fi Passphrase" \
        "Enter the passphrase for '$ssid':") || return 1

    # --- Connect via iwctl ---------------------------------------------------
    msg_info "Connecting to '$ssid'..."

    local attempt
    for attempt in 1 2; do
        iwctl --passphrase "$passphrase" station "$device" connect "$ssid" 2>/dev/null || true

        # Wait for DHCP
        msg_info "Waiting for connection (attempt $attempt)..."
        sleep 5

        if ping -c 1 -W 5 archlinux.org &>/dev/null; then
            dialog_msgbox "Wi-Fi" "Successfully connected to '$ssid'!"
            return 0
        fi

        # On first failure, re-scan and retry — iwd may not have had the
        # SSID in its list yet.
        if [[ $attempt -eq 1 ]]; then
            msg_warn "Connection not established yet — rescanning and retrying..."
            timeout 5 iwctl station "$device" scan 2>/dev/null || true
            sleep 3
        fi
    done

    # Final longer wait in case DHCP was just slow
    msg_warn "Still no connection, giving DHCP more time..."
    sleep 5

    if ping -c 1 -W 5 archlinux.org &>/dev/null; then
        dialog_msgbox "Wi-Fi" "Successfully connected to '$ssid'!"
        return 0
    fi

    dialog_msgbox "Wi-Fi" \
        "Failed to connect to '$ssid'.\n\nPossible causes:\n  • Wrong passphrase\n  • Out of range\n  • Network issue\n\nYou can retry this module or try the interactive iwctl option."
    return 1
}

# --- Interactive iwctl -------------------------------------------------------

_wifi_interactive() {
    local device="$1"

    dialog_msgbox "Interactive iwctl" \
        "You will be dropped into the iwctl shell.\n\nUseful commands:\n  station $device scan\n  station $device get-networks\n  station $device connect <SSID>\n\nType 'exit' or press Ctrl-D when done."

    iwctl </dev/tty >/dev/tty 2>&1 || true

    # Check if we're connected now
    sleep 3
    if ping -c 1 -W 5 archlinux.org &>/dev/null; then
        dialog_msgbox "Wi-Fi" "Internet connection established!"
        return 0
    else
        dialog_msgbox "Wi-Fi" "Still no internet connection detected."
        return 1
    fi
}
