#!/bin/bash
# Maritime Charts - Comprehensive Ocean Chart Viewer
# Alias: maritime
#
# Usage: maritime -o P -t sst          # Pacific SST
#        maritime -o A -t current      # Atlantic currents
#        maritime --list               # List all chart types

export DISPLAY=:0

# ══════════════════════════════════════════════════════════════════
# URL DEFINITIONS BY OCEAN BASIN AND CHART TYPE
# ══════════════════════════════════════════════════════════════════

# SST Anomaly Charts (NOAA Coral Reef Watch v3.1)
declare -A sst_urls=(
    [global]="https://coralreefwatch.noaa.gov/data_current/5km/v3.1_op/daily/png/ct5km_ssta_v3.1_global_current.png"
    [pacific]="https://coralreefwatch.noaa.gov/data_current/5km/v3.1_op/daily/png/ct5km_ssta_v3.1_pacific_current.png"
    [atlantic]="https://coralreefwatch.noaa.gov/data_current/5km/v3.1_op/daily/png/ct5km_ssta_v3.1_satlantic_current.png"
    [indian]="https://coralreefwatch.noaa.gov/data_current/5km/v3.1_op/daily/png/ct5km_ssta_v3.1_indian_current.png"
    [southern]="https://coralreefwatch.noaa.gov/data_current/5km/v3.1_op/daily/png/ct5km_ssta_v3.1_global_current.png"
    [arctic]="https://coralreefwatch.noaa.gov/data_current/5km/v3.1_op/daily/png/ct5km_ssta_v3.1_global_current.png"
)

# Ocean Current Charts (NOAA Ocean Prediction Center)
declare -A current_urls=(
    [global]="https://ocean.weather.gov/sfc_analysis/ghcur.gif"
    [pacific]="https://ocean.weather.gov/P_current72hr.gif"
    [atlantic]="https://ocean.weather.gov/A_current72hr.gif"
    [gulfstream]="https://ocean.weather.gov/gulf_stream_tab.php"
    [indian]="https://ocean.weather.gov/sfc_analysis/ghcur.gif"
    [southern]="https://ocean.weather.gov/sfc_analysis/ghcur.gif"
    [arctic]="https://ocean.weather.gov/sfc_analysis/ghcur.gif"
)

# Wave Height Charts (NOAA WaveWatch III)
declare -A wave_urls=(
    [global]="https://polar.ncep.noaa.gov/waves/viewer.shtml?-gfswave-global-htsgw-"
    [pacific]="https://polar.ncep.noaa.gov/waves/WEB/multi_1.latest_run/plots/pac_hs.png"
    [atlantic]="https://polar.ncep.noaa.gov/waves/WEB/multi_1.latest_run/plots/atl_hs.png"
    [indian]="https://polar.ncep.noaa.gov/waves/WEB/multi_1.latest_run/plots/glo_30m_hs.png"
    [southern]="https://polar.ncep.noaa.gov/waves/WEB/multi_1.latest_run/plots/glo_30m_hs.png"
    [arctic]="https://polar.ncep.noaa.gov/waves/WEB/multi_1.latest_run/plots/arc_hs.png"
)

# Sea Ice Charts (NOAA/NWS)
declare -A ice_urls=(
    [arctic]="https://www.natice.noaa.gov/pub/daily/arctic/arctic.png"
    [antarctic]="https://www.natice.noaa.gov/pub/daily/antarctic/antarctic.png"
    [global]="https://www.natice.noaa.gov/pub/daily/global/global.png"
)

# Chlorophyll/Ocean Color (NASA)
declare -A chlorophyll_urls=(
    [global]="https://oceancolor.gsfc.nasa.gov/gallery/images/MODIS-Aqua/AQUA_MODIS.20240101_20240131.L3m.MO.CHL.chlor_a.4km.nc.png"
    [pacific]="https://oceancolor.gsfc.nasa.gov/gallery/images/global/WORLD.20240101.L3m.DAY.CHL.chlor_a.4km.png"
)

# Surface Analysis Charts
declare -A analysis_urls=(
    [pacific]="https://ocean.weather.gov/P_sfc_full_ocean_color.png"
    [atlantic]="https://ocean.weather.gov/A_sfc_full_ocean_color.png"
    [global]="https://ocean.weather.gov/sfc_analysis/full_ocean_color.gif"
)

# ══════════════════════════════════════════════════════════════════
# CACHE SETUP
# ══════════════════════════════════════════════════════════════════

cache_dir="$HOME/.cache/maritime/charts"
mkdir -p "$cache_dir"

# ══════════════════════════════════════════════════════════════════
# HELPER FUNCTIONS
# ══════════════════════════════════════════════════════════════════

# Convert short ocean code to full name
expand_ocean() {
    case "${1^^}" in
        P|PAC*) echo "pacific" ;;
        A|ATL*) echo "atlantic" ;;
        I|IND*) echo "indian" ;;
        S|SOU*) echo "southern" ;;
        AR|ARC*) echo "arctic" ;;
        G|GLO*) echo "global" ;;
        *) echo "global" ;;
    esac
}

# Fetch and display chart
fetch_chart() {
    local chart_type="$1"
    local ocean="$2"
    local url=""
    local cache_file="$cache_dir/${chart_type}_${ocean}.png"
    local title="${chart_type^^} - ${ocean^^}"

    # Get URL based on chart type
    case "$chart_type" in
        sst) url="${sst_urls[$ocean]:-${sst_urls[global]}}" ;;
        current|currents) url="${current_urls[$ocean]:-${current_urls[global]}}" ;;
        wave|waves) url="${wave_urls[$ocean]:-${wave_urls[global]}}" ;;
        ice) url="${ice_urls[$ocean]:-${ice_urls[arctic]}}" ;;
        chlorophyll|chl) url="${chlorophyll_urls[$ocean]:-${chlorophyll_urls[global]}}" ;;
        analysis|sfc) url="${analysis_urls[$ocean]:-${analysis_urls[global]}}" ;;
        *)
            echo "Unknown chart type: $chart_type"
            list_types
            return 1
            ;;
    esac

    if [ -z "$url" ]; then
        echo "No chart available for $chart_type in $ocean"
        return 1
    fi

    echo "Fetching $title..."
    curl -sLo "$cache_file" "$url"

    if [ -f "$cache_file" ]; then
        setsid -f mpv --title="$title" --autofit=70% "$cache_file"
    else
        echo "Failed to fetch chart"
        return 1
    fi
}

# List available chart types
list_types() {
    cat << EOF
Available Chart Types:
  sst          Sea Surface Temperature Anomaly
  current      Ocean Currents (72hr forecast)
  wave         Significant Wave Height
  ice          Sea Ice Concentration
  chlorophyll  Chlorophyll/Ocean Color
  analysis     Surface Analysis

Ocean Basins:
  P, pacific   Pacific Ocean
  A, atlantic  Atlantic Ocean
  I, indian    Indian Ocean
  S, southern  Southern Ocean
  AR, arctic   Arctic Ocean
  G, global    Global/All Oceans
EOF
}

# Update all charts for an ocean
update_ocean() {
    local ocean="$1"
    echo "Updating all charts for $ocean..."

    for type in sst current wave analysis; do
        fetch_chart "$type" "$ocean" &
    done
    wait

    notify-send "Maritime Charts Updated" "$ocean basin charts refreshed"
}

# Display comprehensive help
help() {
    cat << EOF
Maritime Charts - Ocean Chart Viewer
════════════════════════════════════

Usage: maritime [OPTIONS]

Options:
  -o, --ocean BASIN    Select ocean basin (P/A/I/S/AR/G)
  -t, --type TYPE      Select chart type (sst/current/wave/ice/chlorophyll/analysis)
  -l, --list           List all available chart types
  -u, --update BASIN   Update all charts for basin
  -a, --all            Show all chart types for selected ocean
  -h, --help           Show this help

Ocean Basin Codes:
  P   Pacific Ocean       A   Atlantic Ocean
  I   Indian Ocean        S   Southern Ocean
  AR  Arctic Ocean        G   Global

Chart Types:
  sst          Sea Surface Temperature Anomaly
  current      Ocean Current Forecasts (72hr)
  wave         Significant Wave Height
  ice          Sea Ice Concentration (Arctic/Antarctic)
  chlorophyll  Ocean Color / Phytoplankton
  analysis     Surface Analysis Charts

Examples:
  maritime -o P -t sst       # Pacific SST anomaly
  maritime -o A -t current   # Atlantic currents
  maritime -o AR -t ice      # Arctic sea ice
  maritime --update P        # Update all Pacific charts
  maritime -o G -a           # All global charts

Data Sources:
  NOAA OSPO, Ocean Prediction Center, Coral Reef Watch
  NOAA WaveWatch III, National Ice Center
  NASA Ocean Color

═══════════════════════════════════════════════════════════════
EOF
}

# ══════════════════════════════════════════════════════════════════
# MAIN ARGUMENT PARSING
# ══════════════════════════════════════════════════════════════════

ocean="global"
chart_type=""
show_all=false

while [[ $# -gt 0 ]]; do
    case "$1" in
        -o|--ocean)
            ocean=$(expand_ocean "$2")
            shift 2
            ;;
        -t|--type)
            chart_type="$2"
            shift 2
            ;;
        -l|--list)
            list_types
            exit 0
            ;;
        -u|--update)
            update_ocean "$(expand_ocean "$2")"
            exit 0
            ;;
        -a|--all)
            show_all=true
            shift
            ;;
        -h|--help)
            help
            exit 0
            ;;
        *)
            # Try to interpret as chart type if no flag
            if [ -z "$chart_type" ]; then
                chart_type="$1"
            fi
            shift
            ;;
    esac
done

# Execute based on parsed options
if $show_all; then
    echo "Fetching all charts for $ocean..."
    for type in sst current wave analysis; do
        fetch_chart "$type" "$ocean"
        sleep 0.5
    done
elif [ -n "$chart_type" ]; then
    fetch_chart "$chart_type" "$ocean"
else
    help
fi
