#!/bin/bash

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

BUNDLES=(
    "ltd.iwt.QuickWhisper"
    "ltd.iwt.quickwhisper.debug"
    "ltd.iwt.quickwspr"
    "ltd.iwt.qwey"
    "ltd.iwt.qwey.debug"
    "ltd.iwt.meetmic"
    "ltd.iwt.meetmic.debug"
)

EXTENSIONS=(
    "ltd.iwt.QuickWhisper.Transcribe"
    "ltd.iwt.quickwhisper.debug.Transcribe"
    "ltd.iwt.quickwspr.Transcribe"
    "let.iwt.Qwey.Transcribe"
    "let.iwt.qwey.debug.Transcribe"
    "let.iwt.meetmic.Transcribe"
    "let.iwt.meetmic.debug.Transcribe"
)

LLM_KEYCHAIN_SERVICE="ltd.iwt.quickwhisper.llm"
LLM_KEYCHAIN_ACCOUNTS=(
    "llm.openai.apiKey"
    "llm.anthropic.apiKey"
    "llm.gemini.apiKey"
    "llm.groq.apiKey"
    "llm.mistral.apiKey"
    "llm.openrouter.apiKey"
    "llm.huggingface.apiKey"
    "llm.xai.apiKey"
)

LICENSE_KEYCHAIN_ACCOUNTS=(
    "license"
    "license.machineId"
    "license.activated"
    "license.saleTimestamp"
)

MODE="full"
INCLUDE_HISTORY=0
INCLUDE_KEYCHAIN=0

usage() {
    cat <<'EOF'
Usage: scripts/reset_qw_state.sh [mode] [options]

Modes:
  permissions   Reset TCC permissions for QuickWhisper bundle IDs only.
  settings      Reset local app settings/files only.
  full          Reset both permissions and settings. This is the default.

Options:
  --include-history   Also delete ~/jobs used by QuickWhisper history/import state.
  --include-keychain  Also delete local license + LLM API keys from Keychain.
  -h, --help          Show this help.

Examples:
  scripts/reset_qw_state.sh permissions
  scripts/reset_qw_state.sh settings --include-history
  scripts/reset_qw_state.sh full --include-history --include-keychain

Notes:
  - The app should be closed before running this script.
  - --include-keychain removes local secrets only; it does not deactivate Gumroad uses remotely.
EOF
}

log() {
    printf '[reset-qw] %s\n' "$*"
}

remove_path() {
    local path="$1"
    if [ -e "$path" ]; then
        log "Removing $path"
        rm -rf "$path"
    fi
}

delete_defaults_domain() {
    local domain="$1"
    if defaults read "$domain" >/dev/null 2>&1; then
        log "Deleting defaults domain $domain"
        defaults delete "$domain" >/dev/null 2>&1 || true
    fi
    remove_path "$HOME/Library/Preferences/${domain}.plist"
    remove_path "$HOME/Library/Saved Application State/${domain}.savedState"
    remove_path "$HOME/Library/Application Support/${domain}"
    remove_path "$HOME/Library/Caches/${domain}"
}

reset_permissions() {
    local bundle
    local output
    for bundle in "${BUNDLES[@]}" "${EXTENSIONS[@]}"; do
        log "Resetting TCC permissions for $bundle"
        if output="$(tccutil reset All "$bundle" 2>&1)"; then
            :
        elif [[ "$output" == *"No such bundle identifier"* ]]; then
            log "Skipping unregistered bundle $bundle"
        else
            printf '%s\n' "$output" >&2
        fi
    done
}

reset_group_containers() {
    local pattern
    for pattern in \
        "$HOME/Library/Group Containers/"*quickwhisper* \
        "$HOME/Library/Group Containers/"*quickwspr*
    do
        [ -e "$pattern" ] || continue
        remove_path "$pattern"
    done
}

reset_settings() {
    local bundle

    for bundle in "${BUNDLES[@]}" "${EXTENSIONS[@]}"; do
        delete_defaults_domain "$bundle"
    done

    reset_group_containers

    if [ "$INCLUDE_HISTORY" -eq 1 ]; then
        remove_path "$HOME/jobs"
    fi
}

delete_keychain_item() {
    local service="$1"
    local account="$2"
    if security delete-generic-password -s "$service" -a "$account" >/dev/null 2>&1; then
        log "Deleted keychain item service=$service account=$account"
    fi
}

reset_keychain() {
    local bundle
    local account

    for bundle in "${BUNDLES[@]}"; do
        for account in "${LICENSE_KEYCHAIN_ACCOUNTS[@]}"; do
            delete_keychain_item "$bundle" "$account"
        done
    done

    for account in "${LLM_KEYCHAIN_ACCOUNTS[@]}"; do
        delete_keychain_item "$LLM_KEYCHAIN_SERVICE" "$account"
    done
}

kill_running_apps() {
    pkill -x "QuickWhisper" >/dev/null 2>&1 || true
    pkill -x "QuickWspr" >/dev/null 2>&1 || true
}

while [ "$#" -gt 0 ]; do
    case "$1" in
        permissions|settings|full)
            MODE="$1"
            ;;
        --include-history)
            INCLUDE_HISTORY=1
            ;;
        --include-keychain)
            INCLUDE_KEYCHAIN=1
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        *)
            printf 'Unknown argument: %s\n\n' "$1" >&2
            usage >&2
            exit 1
            ;;
    esac
    shift
done

cd "$ROOT_DIR"

kill_running_apps

case "$MODE" in
    permissions)
        reset_permissions
        ;;
    settings)
        reset_settings
        ;;
    full)
        reset_permissions
        reset_settings
        ;;
esac

if [ "$INCLUDE_KEYCHAIN" -eq 1 ]; then
    reset_keychain
fi

log "Done."
