#!/bin/bash
# Production installation script for HVAC Know It All Content Aggregator

set -e

echo "==================================="
echo "HVAC Content Aggregator Installation"
echo "==================================="

# Check if running as root for systemd installation
if [[ $EUID -eq 0 ]]; then
   echo "This script should not be run as root for safety."
   echo "It will use sudo when needed."
   exit 1
fi

# Create directories
echo "Creating production directories..."
sudo mkdir -p /opt/hvac-kia-content/{data,logs,state}
sudo mkdir -p /var/log/hvac-content
sudo chown -R $USER:$USER /opt/hvac-kia-content
sudo chown -R $USER:$USER /var/log/hvac-content

# Check for .env file
if [ ! -f .env ]; then
    echo "ERROR: .env file not found!"
    echo "Please create .env with all required API keys and settings"
    exit 1
fi

# Install Python dependencies
echo "Installing Python dependencies..."
if command -v uv &> /dev/null; then
    uv pip install -r requirements.txt
else
    pip install -r requirements.txt
fi

# Copy application to production location
echo "Copying application to /opt/hvac-kia-content..."
sudo mkdir -p /opt/hvac-kia-content
sudo cp -r src config *.py requirements.txt .env /opt/hvac-kia-content/
sudo chown -R $USER:$USER /opt/hvac-kia-content

# Copy systemd service files (using template for current user)
echo "Installing systemd services..."
sudo cp systemd/hvac-content-aggregator@.service /etc/systemd/system/
sudo cp systemd/hvac-content-aggregator.timer /etc/systemd/system/
sudo cp systemd/hvac-tiktok-captions.service /etc/systemd/system/
sudo cp systemd/hvac-tiktok-captions.timer /etc/systemd/system/

# Enable service for current user
sudo systemctl enable hvac-content-aggregator@$USER.service

# Reload systemd
sudo systemctl daemon-reload

# Enable services
echo "Enabling services..."
sudo systemctl enable hvac-content-aggregator.timer
# TikTok captions timer is optional - uncomment if needed
# sudo systemctl enable hvac-tiktok-captions.timer

# Test run
echo "Running test scrape..."
uv run python run_production.py --job regular --dry-run

if [ $? -eq 0 ]; then
    echo "✅ Test successful!"
    echo ""
    echo "To start the services:"
    echo "  sudo systemctl start hvac-content-aggregator.timer"
    echo ""
    echo "To check status:"
    echo "  sudo systemctl status hvac-content-aggregator.timer"
    echo "  sudo systemctl list-timers"
    echo ""
    echo "To view logs:"
    echo "  tail -f /var/log/hvac-content/aggregator.log"
    echo ""
    echo "To enable TikTok caption fetching (optional):"
    echo "  sudo systemctl enable --now hvac-tiktok-captions.timer"
else
    echo "❌ Test failed. Please check the configuration."
    exit 1
fi

echo "Installation complete!"