#!/bin/bash

# lowercase Permission Reset Script
# This removes ALL traces of old builds and resets permissions

echo "================================================"
echo "  lowercase Permission Reset"
echo "================================================"
echo ""

# 1. Kill any running instances
echo "🛑 Stopping any running instances..."
pkill -9 -i lowercase 2>/dev/null || true
pkill -9 -i dictation 2>/dev/null || true
sleep 1

# 2. Remove from Launch Services (makes macOS forget the apps)
echo "🗑️  Removing from Launch Services database..."
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user
sleep 1

# 3. Remove TCC (privacy) database entries
echo "🔐 Resetting privacy permissions..."
tccutil reset All com.redxam.dictation 2>/dev/null || true
tccutil reset All com.redxam.lowercase.mac 2>/dev/null || true
sleep 1

# 4. Clean up old apps
echo "🧹 Cleaning up old builds..."
rm -rf /Applications/lowercase.app 2>/dev/null || true
rm -rf /Applications/Dictation.app 2>/dev/null || true
rm -rf ~/Applications/lowercase.app 2>/dev/null || true
rm -rf ~/Applications/Dictation.app 2>/dev/null || true

# 5. Clear derived data
echo "🧹 Clearing Xcode derived data..."
rm -rf ~/Library/Developer/Xcode/DerivedData/lowercase-* 2>/dev/null || true
rm -rf ~/Library/Developer/Xcode/DerivedData/Dictation-* 2>/dev/null || true

# 6. Clear local builds
echo "🧹 Clearing local builds..."
rm -rf /Users/promax/GitHub/redxamapp/experimental/maxawad/macOS/speech-to-text/build 2>/dev/null || true

echo ""
echo "✅ Cleanup complete!"
echo ""
echo "📋 Next steps:"
echo "1. Go to System Settings → Privacy & Security → Accessibility"
echo "2. Remove any entries for 'lowercase' or 'Dictation'"
echo "3. Go to Input Monitoring and do the same"
echo "4. Go to Microphone and do the same"
echo "5. Then run: ./build-and-deploy.sh"
echo "6. Install the NEW signed app from build/lowercase.app"
echo ""
echo "⚠️  IMPORTANT: The new app has bundle ID: com.redxam.lowercase.mac"
echo ""
