#!/bin/bash

# deployment-env-integration.sh - Integrate deployment manager with existing env backup system
# Author: Shell Repository
# Description: Bridge between docker-deployment-manager and backup-env-files system

set -e

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

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEPLOYMENT_MANAGER="$SCRIPT_DIR/docker-deployment-manager.sh"
ENV_BACKUP_SCRIPT="$SCRIPT_DIR/backup-env-files.sh"
STACK_HELPER="$SCRIPT_DIR/stack-assignment-helper.sh"

echo -e "${BLUE}=== Docker Deployment & Environment Backup Integration ===${NC}"
echo ""

# Check if required scripts exist
check_dependencies() {
    local missing=()

    [ ! -f "$DEPLOYMENT_MANAGER" ] && missing+=("docker-deployment-manager.sh")
    [ ! -f "$ENV_BACKUP_SCRIPT" ] && missing+=("backup-env-files.sh")
    [ ! -f "$STACK_HELPER" ] && missing+=("stack-assignment-helper.sh")

    if [ ${#missing[@]} -gt 0 ]; then
        echo -e "${RED}Missing required scripts:${NC}"
        printf '  - %s\n' "${missing[@]}"
        exit 1
    fi
}

# Setup integration
setup_integration() {
    echo -e "${YELLOW}Setting up deployment and backup integration...${NC}"

    # Initialize deployment configuration
    if [ ! -d "$HOME/.docker-deployment" ]; then
        echo "1. Initializing deployment configuration..."
        "$DEPLOYMENT_MANAGER" init
    else
        echo -e "${GREEN}✓ Deployment configuration already exists${NC}"
    fi

    # Initialize environment backup if not already done
    if [ ! -d "$HOME/.env-backup" ]; then
        echo ""
        echo "2. Environment backup system needs initialization."
        echo "   Run: $ENV_BACKUP_SCRIPT --init"
        echo "   This will set up secure backup of your .env files to Gitea."
    else
        echo -e "${GREEN}✓ Environment backup already configured${NC}"
    fi

    # Analyze current stacks
    echo ""
    echo "3. Analyzing current Docker stacks..."
    "$STACK_HELPER" analyze

    echo ""
    echo -e "${GREEN}✓ Integration setup completed!${NC}"
}

# Show workflow suggestions
show_workflow() {
    echo -e "${BLUE}=== Recommended Workflow ===${NC}"
    echo ""

    echo -e "${YELLOW}📋 Daily Operations:${NC}"
    echo "1. Make changes to Docker stacks in your monorepo"
    echo "2. Test locally before deployment"
    echo "3. Backup environment files: $ENV_BACKUP_SCRIPT"
    echo "4. Deploy to specific server: $DEPLOYMENT_MANAGER deploy <server>"
    echo "5. Verify deployment: $DEPLOYMENT_MANAGER status <server>"
    echo ""

    echo -e "${YELLOW}🔄 Bulk Operations:${NC}"
    echo "1. Deploy all stacks: $DEPLOYMENT_MANAGER deploy-all --dry-run"
    echo "2. Check what goes where: $DEPLOYMENT_MANAGER map"
    echo "3. Sync just environments: $DEPLOYMENT_MANAGER sync-env <server>"
    echo ""

    echo -e "${YELLOW}📊 Analysis & Planning:${NC}"
    echo "1. Analyze stack assignments: $STACK_HELPER analyze"
    echo "2. Check resource usage: $STACK_HELPER resources"
    echo "3. Get optimization tips: $STACK_HELPER optimize"
    echo "4. Generate new configs: $STACK_HELPER generate"
    echo ""

    echo -e "${YELLOW}🔧 Automation Integration:${NC}"
    echo "These commands can be integrated into your existing crontab system:"
    echo ""
    echo "# Daily environment backup (already in crontab)"
    echo "0 3 * * * $ENV_BACKUP_SCRIPT"
    echo ""
    echo "# Weekly deployment validation"
    echo "0 4 * * 0 $DEPLOYMENT_MANAGER deploy-all --dry-run"
    echo ""
    echo "# Monthly stack analysis"
    echo "0 5 1 * * $STACK_HELPER all > /home/acedanger/shell/logs/stack-analysis.log"
}

# Show current status
show_status() {
    echo -e "${BLUE}=== Current System Status ===${NC}"
    echo ""

    # Check deployment config
    if [ -d "$HOME/.docker-deployment" ]; then
        echo -e "${GREEN}✅ Deployment configuration: Ready${NC}"
        local servers=$(ls "$HOME/.docker-deployment/servers/"*.yml 2>/dev/null | wc -l)
        echo "   Configured servers: $servers"
    else
        echo -e "${RED}❌ Deployment configuration: Not initialized${NC}"
    fi

    # Check environment backup
    if [ -d "$HOME/.env-backup" ]; then
        echo -e "${GREEN}✅ Environment backup: Ready${NC}"
        local last_backup=$(stat -c %y "$HOME/.env-backup/.git/HEAD" 2>/dev/null | cut -d' ' -f1 || echo "Never")
        echo "   Last backup: $last_backup"
    else
        echo -e "${YELLOW}⚠️  Environment backup: Not initialized${NC}"
    fi

    # Check Docker stacks
    if [ -d "$HOME/docker" ]; then
        local stack_count=$(find "$HOME/docker" -maxdepth 1 -type d | wc -l)
        stack_count=$((stack_count - 1)) # Exclude the docker directory itself
        echo -e "${GREEN}✅ Docker stacks: $stack_count found${NC}"
    else
        echo -e "${RED}❌ Docker directory: Not found${NC}"
    fi

    # Check crontab integration
    if crontab -l 2>/dev/null | grep -q "backup-env-files.sh"; then
        echo -e "${GREEN}✅ Crontab integration: Environment backup scheduled${NC}"
    else
        echo -e "${YELLOW}⚠️  Crontab integration: No env backup scheduled${NC}"
    fi
}

# Test the integration
test_integration() {
    echo -e "${BLUE}=== Testing Integration ===${NC}"
    echo ""

    echo "1. Testing deployment manager..."
    if "$DEPLOYMENT_MANAGER" map >/dev/null 2>&1; then
        echo -e "${GREEN}✅ Deployment manager: Working${NC}"
    else
        echo -e "${RED}❌ Deployment manager: Error${NC}"
    fi

    echo "2. Testing environment backup..."
    if "$ENV_BACKUP_SCRIPT" --list >/dev/null 2>&1; then
        echo -e "${GREEN}✅ Environment backup: Working${NC}"
    else
        echo -e "${YELLOW}⚠️  Environment backup: Needs initialization${NC}"
    fi

    echo "3. Testing stack analysis..."
    if "$STACK_HELPER" analyze >/dev/null 2>&1; then
        echo -e "${GREEN}✅ Stack analysis: Working${NC}"
    else
        echo -e "${RED}❌ Stack analysis: Error${NC}"
    fi

    echo ""
    echo -e "${BLUE}Integration test completed.${NC}"
}

# Main function
main() {
    check_dependencies

    case "${1:-status}" in
        setup|--setup|-s)
            setup_integration
            ;;
        workflow|--workflow|-w)
            show_workflow
            ;;
        status|--status)
            show_status
            ;;
        test|--test|-t)
            test_integration
            ;;
        all|--all|-a)
            show_status
            echo ""
            setup_integration
            echo ""
            show_workflow
            ;;
        help|--help|-h)
            echo "Usage: $0 [COMMAND]"
            echo ""
            echo "Commands:"
            echo "  setup     Initialize deployment and backup integration"
            echo "  workflow  Show recommended workflow"
            echo "  status    Show current system status (default)"
            echo "  test      Test integration components"
            echo "  all       Run status, setup, and show workflow"
            echo "  help      Show this help message"
            ;;
        *)
            echo -e "${RED}Unknown command: $1${NC}"
            echo "Use '$0 help' for usage information"
            exit 1
            ;;
    esac
}

# Run main function
main "$@"
