#!/bin/bash

echo "🔧 Fixing AI Dictation Service (Corrected Method)..."

# Step 1: Copy service file with sudo (for system-wide installation)
echo "📋 Copying service file to user systemd directory..."
mkdir -p ~/.config/systemd/user/
cp dictation.service ~/.config/systemd/user/
echo "✅ Service file copied to ~/.config/systemd/user/"

# Step 2: Reload systemd daemon (user session, no sudo needed)
echo "🔄 Reloading systemd user daemon..."
systemctl --user daemon-reload
echo "✅ User systemd daemon reloaded"

# Step 3: Start the service (user session, no sudo needed)
echo "🚀 Starting AI dictation service..."
systemctl --user start dictation.service
echo "✅ Service start command sent"

# Step 4: Enable the service (user session, no sudo needed)
echo "🔧 Enabling AI dictation service..."
systemctl --user enable dictation.service
echo "✅ Service enabled for auto-start"

# Step 5: Check status (user session, no sudo needed)
echo "📊 Checking service status..."
sleep 2
systemctl --user status dictation.service
echo ""

# Step 6: Check if service is actually running
if systemctl --user is-active --quiet dictation.service; then
    echo "✅ SUCCESS: AI Dictation Service is running!"
    echo "🎤 Press Alt+D for dictation"
    echo "🤖 Press Super+Alt+D for AI conversation"
else
    echo "❌ FAILED: Service did not start properly"
    echo "🔍 Checking logs:"
    journalctl --user -u dictation.service -n 10 --no-pager
fi

echo ""
echo "🎯 Service setup complete!"
echo ""
echo "To manually manage the service:"
echo "  Start:   systemctl --user start dictation.service"
echo "  Stop:    systemctl --user stop dictation.service"
echo "  Status:  systemctl --user status dictation.service"
echo "  Logs:    journalctl --user -u dictation.service -f"