#!/usr/bin/env bash
set -euo pipefail
# POS: network ip — Show interfaces, routes, public IP + location

source "$(dirname "$0")/../lib/common.sh" 2>/dev/null || source "$(dirname "$0")/common.sh"

usage() {
    cat <<EOF
Usage: pos network ip

Display network interfaces, default route, and public IP.
EOF
    exit 0
}

case "${1:-}" in
    -h|--help) usage ;;
esac

section "Network Interfaces"

ip -o -4 addr show | while read -r _ ifname _ ipaddr _; do
    printf "%-20s %s\n" "$ifname" "${ipaddr%%/*}"
done

echo

section "Default Route"

gateway=$(ip route | awk '/default/ {print $3; exit}')
iface=$(ip route | awk '/default/ {print $5; exit}')

printf "%-20s %s\n" "Interface" "${iface:-N/A}"
printf "%-20s %s\n" "Gateway" "${gateway:-N/A}"

echo

section "Public IP"

PUBLIC_IP=$(curl -4 -s --max-time 5 https://ifconfig.me 2>/dev/null) || true

if [ -n "${PUBLIC_IP:-}" ]; then
    echo "$PUBLIC_IP"
    GEO=$(curl -4 -s --max-time 5 "http://ip-api.com/json/${PUBLIC_IP}?fields=status,country,regionName,city,isp" 2>/dev/null) || true
    if [ -n "${GEO:-}" ]; then
        location=$(echo "$GEO" | python3 -c "
import sys, json
d = json.load(sys.stdin)
if d.get('status') == 'success':
    print(f\"{d['city']}, {d['regionName']}, {d['country']} ({d['isp']})\")
" 2>/dev/null) || true
        if [ -n "${location:-}" ]; then
            printf "%-20s %s\n" "Location" "$location"
        else
            echo "Location: Unavailable"
        fi
    else
        echo "Location: Unavailable"
    fi
else
    echo "Unavailable"
fi
echo
