#!/usr/bin/env bash
#
# ThrillWiki Systemd Service Configuration Diagnosis Script
# Tests and validates systemd service configuration issues
#

set -e

# Script configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# Test configuration
REMOTE_HOST="${1:-192.168.20.65}"
REMOTE_USER="${2:-thrillwiki}"
REMOTE_PORT="${3:-22}"
SSH_OPTIONS="-o IdentitiesOnly=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=30"

echo -e "${BLUE}🔍 ThrillWiki Systemd Service Diagnosis${NC}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "Target: ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_PORT}"
echo ""

# Function to run remote commands
run_remote() {
    local cmd="$1"
    local description="$2"
    echo -e "${YELLOW}Testing: ${description}${NC}"
    
    if ssh $SSH_OPTIONS -p $REMOTE_PORT $REMOTE_USER@$REMOTE_HOST "$cmd" 2>/dev/null; then
        echo -e "${GREEN}✅ PASS: ${description}${NC}"
        return 0
    else
        echo -e "${RED}❌ FAIL: ${description}${NC}"
        return 1
    fi
}

echo "=== Issue #1: Service Script Dependencies ==="
echo ""

# Test 1: Check if smart-deploy.sh exists
run_remote "test -f [AWS-SECRET-REMOVED]t-deploy.sh" \
    "smart-deploy.sh script exists"

# Test 2: Check if smart-deploy.sh is executable
run_remote "test -x [AWS-SECRET-REMOVED]t-deploy.sh" \
    "smart-deploy.sh script is executable"

# Test 3: Check deploy-automation.sh exists
run_remote "test -f [AWS-SECRET-REMOVED]eploy-automation.sh" \
    "deploy-automation.sh script exists"

# Test 4: Check deploy-automation.sh is executable
run_remote "test -x [AWS-SECRET-REMOVED]eploy-automation.sh" \
    "deploy-automation.sh script is executable"

echo ""
echo "=== Issue #2: Systemd Service Installation ==="
echo ""

# Test 5: Check if service files exist in systemd
run_remote "test -f /etc/systemd/system/thrillwiki-deployment.service" \
    "thrillwiki-deployment.service installed in systemd"

run_remote "test -f /etc/systemd/system/thrillwiki-smart-deploy.service" \
    "thrillwiki-smart-deploy.service installed in systemd"

run_remote "test -f /etc/systemd/system/thrillwiki-smart-deploy.timer" \
    "thrillwiki-smart-deploy.timer installed in systemd"

echo ""
echo "=== Issue #3: Service Status and Configuration ==="
echo ""

# Test 6: Check service enablement status
run_remote "sudo systemctl is-enabled thrillwiki-deployment.service" \
    "thrillwiki-deployment.service is enabled"

run_remote "sudo systemctl is-enabled thrillwiki-smart-deploy.timer" \
    "thrillwiki-smart-deploy.timer is enabled"

# Test 7: Check service active status
run_remote "sudo systemctl is-active thrillwiki-deployment.service" \
    "thrillwiki-deployment.service is active"

run_remote "sudo systemctl is-active thrillwiki-smart-deploy.timer" \
    "thrillwiki-smart-deploy.timer is active"

echo ""
echo "=== Issue #4: Environment and Configuration ==="
echo ""

# Test 8: Check environment file exists
run_remote "test -f [AWS-SECRET-REMOVED]emd/thrillwiki-deployment***REMOVED***" \
    "Environment configuration file exists"

# Test 9: Check environment file permissions
run_remote "test -r [AWS-SECRET-REMOVED]emd/thrillwiki-deployment***REMOVED***" \
    "Environment file is readable"

# Test 10: Check GitHub token configuration
run_remote "test -f /home/thrillwiki/thrillwiki/.github-pat" \
    "GitHub token file exists"

echo ""
echo "=== Issue #5: Service Dependencies and Logs ==="
echo ""

# Test 11: Check systemd journal logs
echo -e "${YELLOW}Testing: Service logs availability${NC}"
if ssh $SSH_OPTIONS -p $REMOTE_PORT $REMOTE_USER@$REMOTE_HOST "sudo journalctl -u thrillwiki-deployment --no-pager -n 5" >/dev/null 2>&1; then
    echo -e "${GREEN}✅ PASS: Service logs are available${NC}"
    echo "Last 5 log entries:"
    ssh $SSH_OPTIONS -p $REMOTE_PORT $REMOTE_USER@$REMOTE_HOST "sudo journalctl -u thrillwiki-deployment --no-pager -n 5" | sed 's/^/  /'
else
    echo -e "${RED}❌ FAIL: Service logs not available${NC}"
fi

echo ""
echo "=== Issue #6: Service Configuration Validation ==="
echo ""

# Test 12: Validate service file syntax
echo -e "${YELLOW}Testing: Service file syntax validation${NC}"
if ssh $SSH_OPTIONS -p $REMOTE_PORT $REMOTE_USER@$REMOTE_HOST "sudo systemd-analyze verify /etc/systemd/system/thrillwiki-deployment.service" 2>/dev/null; then
    echo -e "${GREEN}✅ PASS: thrillwiki-deployment.service syntax is valid${NC}"
else
    echo -e "${RED}❌ FAIL: thrillwiki-deployment.service has syntax errors${NC}"
fi

if ssh $SSH_OPTIONS -p $REMOTE_PORT $REMOTE_USER@$REMOTE_HOST "sudo systemd-analyze verify /etc/systemd/system/thrillwiki-smart-deploy.service" 2>/dev/null; then
    echo -e "${GREEN}✅ PASS: thrillwiki-smart-deploy.service syntax is valid${NC}"
else
    echo -e "${RED}❌ FAIL: thrillwiki-smart-deploy.service has syntax errors${NC}"
fi

echo ""
echo "=== Issue #7: Automation Service Existence ==="
echo ""

# Test 13: Check for thrillwiki-automation.service (mentioned in error logs)
run_remote "test -f /etc/systemd/system/thrillwiki-automation.service" \
    "thrillwiki-automation.service exists (mentioned in error logs)"

run_remote "sudo systemctl status thrillwiki-automation.service" \
    "thrillwiki-automation.service status check"

echo ""
echo -e "${BLUE}🔍 Diagnosis Complete${NC}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "This diagnosis will help identify the specific systemd service issues."
echo "Run this script to validate assumptions before implementing fixes."