#!/usr/bin/env bash
# macOS Storage - Decimal View
# GPL 3.0+ License - Free forever, corporate-capture proof
#
# Shows your storage in decimal (what manufacturers advertise)
# macOS already does this correctly — this script shows what
# Windows would display for the same drive, so you can see
# exactly what you're missing if you also run Windows.

set -euo pipefail

# ── Colours ───────────────────────────────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
CYAN='\033[0;36m'; MAGENTA='\033[0;35m'; GRAY='\033[0;37m'
WHITE='\033[1;37m'; RESET='\033[0m'; BOLD='\033[1m'

# ── Helpers ───────────────────────────────────────────────────────────────────
bytes_to_decimal_gb() {
    # Decimal GB (what manufacturers use: 1 GB = 1,000,000,000 bytes)
    echo "scale=2; $1 / 1000000000" | bc
}

bytes_to_binary_gb() {
    # Binary GiB (what Windows uses: 1 GB = 1,073,741,824 bytes)
    echo "scale=2; $1 / 1073741824" | bc
}

bytes_to_decimal_tb() {
    echo "scale=2; $1 / 1000000000000" | bc
}

bytes_to_binary_tb() {
    echo "scale=2; $1 / 1099511627776" | bc
}

format_size() {
    # Auto-selects TB or GB based on size
    local bytes=$1
    local mode=$2  # "decimal" or "binary"
    if (( bytes >= 1000000000000 )); then
        if [[ "$mode" == "decimal" ]]; then
            printf "%.2f TB (%.0f GB)" "$(bytes_to_decimal_tb $bytes)" "$(bytes_to_decimal_gb $bytes)"
        else
            printf "%.2f TB (%.0f GB)" "$(bytes_to_binary_tb $bytes)" "$(bytes_to_binary_gb $bytes)"
        fi
    else
        if [[ "$mode" == "decimal" ]]; then
            printf "%.1f GB" "$(bytes_to_decimal_gb $bytes)"
        else
            printf "%.1f GB" "$(bytes_to_binary_gb $bytes)"
        fi
    fi
}

# ── Get volumes ───────────────────────────────────────────────────────────────
get_volumes() {
    # Returns: mountpoint|total_bytes|used_bytes|free_bytes|name
    df -k / /Volumes/* 2>/dev/null | \
    awk 'NR>1 && $1 !~ /^(devfs|map|ditto)/ && $2 > 0 {
        total = $2 * 1024
        used  = $3 * 1024
        free  = $4 * 1024
        mount = $6
        print mount "|" total "|" used "|" free
    }' | sort -u
}

# ── Show header ───────────────────────────────────────────────────────────────
show_header() {
    clear
    echo -e "${GREEN}╔══════════════════════════════════════════════════════════╗${RESET}"
    echo -e "${GREEN}║${RESET}           ${BOLD}${WHITE}macOS Storage - Decimal View${RESET}              ${GREEN}║${RESET}"
    echo -e "${GREEN}║${RESET}  ${GRAY}What your storage actually is — and what Windows        ${RESET}${GREEN}║${RESET}"
    echo -e "${GREEN}║${RESET}  ${GRAY}would show for the same drive                           ${RESET}${GREEN}║${RESET}"
    echo -e "${GREEN}║${RESET}  ${GRAY}GPL 3.0+ - Free forever, corporate-capture proof        ${RESET}${GREEN}║${RESET}"
    echo -e "${GREEN}╚══════════════════════════════════════════════════════════╝${RESET}"
    echo
}

# ── Show volumes ──────────────────────────────────────────────────────────────
show_volumes() {
    local show_diff="${1:-false}"

    while IFS='|' read -r mount total used free; do
        # Get volume name
        local name
        name=$(diskutil info "$mount" 2>/dev/null | awk -F': +' '/Volume Name/{print $2}' || basename "$mount")
        [[ -z "$name" || "$name" == "/" ]] && name="Macintosh HD"

        echo -e "${GREEN}Volume: ${BOLD}$name${RESET} ${GRAY}($mount)${RESET}"
        echo -e "${CYAN}─────────────────────────────────────────────────────────${RESET}"

        # macOS / correct decimal values
        echo -e "${GREEN}✅ macOS shows (correct decimal):${RESET}"
        echo -e "   Total: ${WHITE}$(format_size $total decimal)${RESET}"
        echo -e "   Used:  ${WHITE}$(format_size $used  decimal)${RESET}"
        echo -e "   Free:  ${WHITE}$(format_size $free  decimal)${RESET}"
        echo

        if [[ "$show_diff" == "true" ]]; then
            # Windows binary values
            echo -e "${RED}❌ Windows would show (binary):${RESET}"
            echo -e "   Total: ${WHITE}$(format_size $total binary)${RESET}"
            echo -e "   Used:  ${WHITE}$(format_size $used  binary)${RESET}"
            echo -e "   Free:  ${WHITE}$(format_size $free  binary)${RESET}"
            echo

            # Difference
            local dec_gb bin_gb diff_gb
            dec_gb=$(bytes_to_decimal_gb $total)
            bin_gb=$(bytes_to_binary_gb  $total)
            diff_gb=$(echo "scale=1; $dec_gb - $bin_gb" | bc)
            local lost_money
            lost_money=$(echo "scale=2; $diff_gb * 0.10" | bc)

            echo -e "${YELLOW}💰 What Windows hides from you:${RESET}"
            echo -e "   Total: ${YELLOW}+${diff_gb} GB${RESET}"
            echo -e "   Worth: ${MAGENTA}£${lost_money} at £0.10/GB${RESET}"
        fi

        echo -e "${CYAN}─────────────────────────────────────────────────────────${RESET}"
        echo
    done < <(get_volumes)
}

# ── Compare common sizes ──────────────────────────────────────────────────────
show_common_drives() {
    echo -e "${CYAN}── Common drive sizes: macOS vs Windows ─────────────────${RESET}"
    echo

    local sizes=("256000000000" "512000000000" "1000000000000" "2000000000000" "4000000000000" "8000000000000")
    local labels=("256 GB" "512 GB" "1 TB" "2 TB" "4 TB" "8 TB")

    for i in "${!sizes[@]}"; do
        local bytes="${sizes[$i]}"
        local label="${labels[$i]}"
        local dec bin diff money
        dec=$(bytes_to_decimal_gb $bytes)
        bin=$(bytes_to_binary_gb  $bytes)
        diff=$(echo "scale=1; $dec - $bin" | bc)
        money=$(echo "scale=2; $diff * 0.10" | bc)

        printf "  ${WHITE}%-8s${RESET}  ${GREEN}macOS: %-10s${RESET}  ${RED}Windows: %-10s${RESET}  ${YELLOW}Hidden: +%s GB  £%s${RESET}\n" \
            "$label" "${dec} GB" "${bin} GB" "$diff" "$money"
    done
    echo
}

# ── Help ──────────────────────────────────────────────────────────────────────
show_help() {
    show_header
    echo -e "${YELLOW}🎯 What this shows:${RESET}"
    echo -e "   macOS already uses decimal storage (correct, like manufacturers)"
    echo -e "   This script shows your actual storage and — if you want — what"
    echo -e "   Windows would report for the same drive so you can see the gap."
    echo
    echo -e "${YELLOW}⚡ Usage:${RESET}"
    echo -e "   ${WHITE}./MacStorageView.sh${RESET}           Show your volumes (decimal)"
    echo -e "   ${WHITE}./MacStorageView.sh --diff${RESET}    Show macOS vs Windows comparison"
    echo -e "   ${WHITE}./MacStorageView.sh --common${RESET}  Compare common drive sizes"
    echo -e "   ${WHITE}./MacStorageView.sh --watch${RESET}   Live monitoring (5s refresh)"
    echo -e "   ${WHITE}./MacStorageView.sh --help${RESET}    This help"
    echo
    echo -e "${YELLOW}💡 Why this exists:${RESET}"
    echo -e "   Drive makers use decimal: 1 GB = 1,000,000,000 bytes"
    echo -e "   ${GREEN}macOS uses decimal  ✅ — matches what you paid for${RESET}"
    echo -e "   ${RED}Windows uses binary ❌ — makes drives look smaller${RESET}"
    echo -e "   A 1 TB drive shows as ${GREEN}1.00 TB on macOS${RESET}, ${RED}0.91 TB on Windows${RESET}"
    echo
}

# ── Watch mode ────────────────────────────────────────────────────────────────
watch_mode() {
    while true; do
        show_header
        show_volumes "true"
        echo -e "${GRAY}🔄 Refreshing every 5s — Ctrl+C to stop${RESET}"
        sleep 5
    done
}

# ── Entry point ───────────────────────────────────────────────────────────────
case "${1:-}" in
    --help|-h) show_help ;;
    --diff|-d) show_header; show_volumes "true" ;;
    --common)  show_header; show_common_drives ;;
    --watch)   watch_mode ;;
    *)         show_header; show_volumes "false" ;;
esac