#!/bin/bash
# ==============================================================================
# SciSpell.app - Native macOS Application Launcher
# Developed & Engineered by OMnyte
# ==============================================================================

RESOURCES_DIR="$(cd "$(dirname "$0")/../Resources" && pwd)"
SPELLING_DIR="$HOME/Library/Spelling"
TARGET_DICT="$SPELLING_DIR/it"
BACKUP_DIR="$SPELLING_DIR/SciSpell_Backups"
SOURCE_DICT="$RESOURCES_DIR/scispell_it.txt"

# Native AppleScript Dialog
CHOICE=$(osascript <<EOF
set dialogResult to display dialog "Benvenuto in SciSpell per macOS!\\n\\nSviluppato da OMnyte.\\n\\nSciSpell integra oltre 38.000 termini scientifici validati (biologia, chimica, medicina, fisica, matematica...) direttamente nel correttore ortografico di Apple Pages, Word e TextEdit, eliminando le fastidiose sottolineature rosse." with title "SciSpell — Installatore Scientifico macOS" buttons {"Esci", "Verifica Stato", "Installa SciSpell"} default button "Installa SciSpell" with icon note
return button returned of dialogResult
EOF
)

if [ "$CHOICE" = "Installa SciSpell" ]; then
    mkdir -p "$SPELLING_DIR"
    mkdir -p "$BACKUP_DIR"

    # 1. Backup timestamped
    TIMESTAMP=$(date +%Y%m%d_%H%M%S)
    if [ -f "$TARGET_DICT" ]; then
        cp "$TARGET_DICT" "$BACKUP_DIR/it_backup_$TIMESTAMP.txt"
    else
        touch "$TARGET_DICT"
    fi

    # 2. Atomic merge
    TMP_MERGE=$(mktemp /tmp/scispell_app_merge.XXXXXX)
    cat "$TARGET_DICT" "$SOURCE_DICT" | sed '/^[[:space:]]*$/d' | sort -u > "$TMP_MERGE"
    mv "$TMP_MERGE" "$TARGET_DICT"
    chmod 644 "$TARGET_DICT"

    # 3. Reload AppleSpell cache
    killall AppleSpell 2>/dev/null || true

    TOTAL_TERMS=$(wc -l < "$TARGET_DICT" | tr -d ' ')

    osascript <<EOF
display dialog "SciSpell installato con successo!\\n\\nTermini scientifici attivi sul tuo Mac: $TOTAL_TERMS\\n\\nPuoi aprire Apple Pages o Word e iniziare subito a scrivere. Nessun termine specialistico verra' piu' sottolineato in rosso.\\n\\nAutore: OMnyte • Licenza: MIT / Free Distribution" with title "SciSpell — Operazione Completata" buttons {"OK"} default button "OK" with icon note
EOF

elif [ "$CHOICE" = "Verifica Stato" ]; then
    if [ -f "$TARGET_DICT" ]; then
        TERMS_COUNT=$(wc -l < "$TARGET_DICT" | tr -d ' ')
        STATUS_MSG="Il dizionario e' ATTIVO ($TERMS_COUNT termini totali installati)."
    else
        STATUS_MSG="Il dizionario non e' ancora installato."
    fi

    osascript <<EOF
display dialog "$STATUS_MSG\\n\\nPercorso: $TARGET_DICT\\n\\nSviluppato da OMnyte" with title "SciSpell — Stato Sistema" buttons {"OK"} default button "OK" with icon note
EOF
fi
