#!/usr/bin/env bash
################################################################################
# Claude Code Customizations - Master Control Script
# Provides an interactive menu for all setup operations
################################################################################

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

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# Script paths
INSTALL_SCRIPT="$SCRIPT_DIR/install-claude-customizations.sh"
EXPORT_SCRIPT="$SCRIPT_DIR/export-claude-customizations.sh"
PACKAGE_SCRIPT="$SCRIPT_DIR/create-complete-package.sh"
VERIFY_SCRIPT="$SCRIPT_DIR/verify-claude-setup.sh"

# Helper functions
print_header() {
    clear
    echo -e "${CYAN}╔══════════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${CYAN}║${NC} ${BOLD}Claude Code Customizations - Setup Manager${NC}                    ${CYAN}║${NC}"
    echo -e "${CYAN}╚══════════════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

print_menu() {
    print_header
    echo -e "${BOLD}Main Menu:${NC}"
    echo ""
    echo -e "  ${GREEN}1${NC}) 📦  Create Complete Package (recommended for distribution)"
    echo -e "  ${GREEN}2${NC}) 📥  Install Customizations (on new machine)"
    echo -e "  ${GREEN}3${NC}) 📤  Export Customizations (backup/transfer)"
    echo -e "  ${GREEN}4${NC}) ✅  Verify Installation"
    echo -e "  ${GREEN}5${NC}) 📋  Show Package Contents"
    echo -e "  ${GREEN}6${NC}) 📖  View Documentation"
    echo -e "  ${GREEN}7${NC}) 🧹  Clean Backup Files"
    echo ""
    echo -e "  ${YELLOW}0${NC}) 🚪 Exit"
    echo ""
    echo -ne "${CYAN}Select an option: ${NC}"
}

check_script() {
    local script="$1"
    local name="$2"

    if [ ! -f "$script" ]; then
        echo -e "${RED}✗ Error: $name not found at $script${NC}"
        return 1
    fi

    if [ ! -x "$script" ]; then
        echo -e "${YELLOW}⚠ Making $name executable...${NC}"
        chmod +x "$script"
    fi

    return 0
}

create_package() {
    print_header
    echo -e "${BOLD}Create Complete Package${NC}"
    echo "═══════════════════════════════════════════════════════════"
    echo ""
    echo "This will create a complete package with all agents, plugins,"
    echo "and configurations ready for distribution."
    echo ""
    read -p "Continue? (y/N): " confirm

    if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
        return
    fi

    if check_script "$PACKAGE_SCRIPT" "Package Script"; then
        echo ""
        bash "$PACKAGE_SCRIPT"
    fi

    echo ""
    read -p "Press Enter to continue..."
}

install_customizations() {
    print_header
    echo -e "${BOLD}Install Customizations${NC}"
    echo "═══════════════════════════════════════════════════════════"
    echo ""
    echo "This will install Claude Code customizations on this machine."
    echo ""
    echo "Note: If you're creating a complete package, use option 1 instead."
    echo ""

    if check_script "$INSTALL_SCRIPT" "Install Script"; then
        echo ""
        bash "$INSTALL_SCRIPT"
    fi

    echo ""
    read -p "Press Enter to continue..."
}

export_customizations() {
    print_header
    echo -e "${BOLD}Export Customizations${NC}"
    echo "═══════════════════════════════════════════════════════════"
    echo ""
    echo "This will export your current customizations to a package"
    echo "for backup or transfer to another machine."
    echo ""
    read -p "Continue? (y/N): " confirm

    if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
        return
    fi

    if check_script "$EXPORT_SCRIPT" "Export Script"; then
        echo ""
        bash "$EXPORT_SCRIPT"
    fi

    echo ""
    read -p "Press Enter to continue..."
}

verify_installation() {
    print_header

    if check_script "$VERIFY_SCRIPT" "Verify Script"; then
        bash "$VERIFY_SCRIPT"
    fi

    echo ""
    read -p "Press Enter to continue..."
}

show_contents() {
    print_header
    echo -e "${BOLD}Package Contents${NC}"
    echo "═══════════════════════════════════════════════════════════"
    echo ""

    CLAUDE_DIR="$HOME/.claude"

    if [ ! -d "$CLAUDE_DIR" ]; then
        echo -e "${RED}No Claude Code directory found at $CLAUDE_DIR${NC}"
        echo ""
        read -p "Press Enter to continue..."
        return
    fi

    echo -e "${CYAN}Agent Categories:${NC}"
    for category in engineering marketing product studio-operations project-management testing design bonus; do
        if [ -d "$CLAUDE_DIR/agents/$category" ]; then
            count=$(ls -1 "$CLAUDE_DIR/agents/$category"/*.md 2>/dev/null | wc -l)
            if [ $count -gt 0 ]; then
                printf "  %-25s %2d agents\n" "$category" "$count"
            fi
        fi
    done

    echo ""
    echo -e "${CYAN}Configuration Files:${NC}"
    echo "  settings.json"
    echo "  settings.local.json"
    echo "  plugins/installed_plugins.json"

    echo ""
    echo -e "${CYAN}MCP Tools:${NC}"
    echo "  • zai-mcp-server (vision analysis)"
    echo "  • web-search-prime"
    echo "  • web-reader"
    echo "  • zread (GitHub)"

    echo ""
    echo -e "${CYAN}Skills:${NC}"
    echo "  • glm-plan-bug:case-feedback"
    echo "  • glm-plan-usage:usage-query"

    echo ""
    read -p "Press Enter to continue..."
}

view_documentation() {
    print_header
    echo -e "${BOLD}Documentation${NC}"
    echo "═══════════════════════════════════════════════════════════"
    echo ""

    DOCS=(
        "SCRIPTS-GUIDE.md:Script usage guide"
        "CLAUDE-CUSTOMIZATIONS-README.md:Complete feature documentation"
    )

    echo "Available documentation:"
    echo ""

    for doc in "${DOCS[@]}"; do
        file="${doc%%:*}"
        desc="${doc##*:}"
        if [ -f "$SCRIPT_DIR/$file" ]; then
            echo -e "  ${GREEN}✓${NC} $file"
            echo "     $desc"
        else
            echo -e "  ${RED}✗${NC} $file (not found)"
        fi
    done

    echo ""
    echo "Would you like to view a document?"
    echo "  1) SCRIPTS-GUIDE.md"
    echo "  2) CLAUDE-CUSTOMIZATIONS-README.md"
    echo "  0) Back"
    echo ""
    read -p "Select: " doc_choice

    case $doc_choice in
        1)
            if [ -f "$SCRIPT_DIR/SCRIPTS-GUIDE.md" ]; then
                less "$SCRIPT_DIR/SCRIPTS-GUIDE.md"
            fi
            ;;
        2)
            if [ -f "$SCRIPT_DIR/CLAUDE-CUSTOMIZATIONS-README.md" ]; then
                less "$SCRIPT_DIR/CLAUDE-CUSTOMIZATIONS-README.md"
            fi
            ;;
    esac
}

clean_backups() {
    print_header
    echo -e "${BOLD}Clean Backup Files${NC}"
    echo "═══════════════════════════════════════════════════════════"
    echo ""

    # Find backup directories
    BACKUPS=$(find "$HOME" -maxdepth 1 -name ".claude-backup-*" -type d 2>/dev/null)
    PACKAGES=$(find "$HOME" -maxdepth 1 -name "claude-customizations-*.tar.gz" -type f 2>/dev/null)
    EXPORT_DIRS=$(find "$HOME" -maxdepth 1 -name "claude-*-export" -type d 2>/dev/null)

    BACKUP_COUNT=$(echo "$BACKUPS" | grep -c "^" || echo 0)
    PACKAGE_COUNT=$(echo "$PACKAGES" | grep -c "^" || echo 0)
    EXPORT_COUNT=$(echo "$EXPORT_DIRS" | grep -c "^" || echo 0)

    echo "Found:"
    echo "  • $BACKUP_COUNT backup directories"
    echo "  • $PACKAGE_COUNT package archives"
    echo "  • $EXPORT_COUNT export directories"
    echo ""

    if [ $((BACKUP_COUNT + PACKAGE_COUNT + EXPORT_COUNT)) -eq 0 ]; then
        echo -e "${GREEN}No backup files to clean${NC}"
        echo ""
        read -p "Press Enter to continue..."
        return
    fi

    read -p "Clean all backup files? (y/N): " confirm

    if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
        return
    fi

    echo ""
    echo "Cleaning..."

    if [ -n "$BACKUPS" ]; then
        echo "$BACKUPS" | while read -r backup; do
            echo "  Removing: $backup"
            rm -rf "$backup"
        done
    fi

    if [ -n "$PACKAGES" ]; then
        echo "$PACKAGES" | while read -r package; do
            echo "  Removing: $package"
            rm -f "$package"
        done
    fi

    if [ -n "$EXPORT_DIRS" ]; then
        echo "$EXPORT_DIRS" | while read -r export_dir; do
            echo "  Removing: $export_dir"
            rm -rf "$export_dir"
        done
    fi

    echo ""
    echo -e "${GREEN}✓ Cleanup complete${NC}"
    echo ""
    read -p "Press Enter to continue..."
}

# Main loop
main() {
    while true; do
        print_menu
        read -r choice
        echo ""

        case $choice in
            1) create_package ;;
            2) install_customizations ;;
            3) export_customizations ;;
            4) verify_installation ;;
            5) show_contents ;;
            6) view_documentation ;;
            7) clean_backups ;;
            0)
                echo "Goodbye!"
                exit 0
                ;;
            *)
                echo -e "${RED}Invalid option. Please try again.${NC}"
                sleep 1
                ;;
        esac
    done
}

# Run main function
main
