#!/bin/bash

# Rustelo Post-Setup Hook
# This script runs after any setup operation to finalize the installation

set -e

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

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

# Configuration
SETUP_TYPE="${1:-unknown}"
SKIP_VERIFICATION="${SKIP_VERIFICATION:-false}"
SKIP_REPORT="${SKIP_REPORT:-false}"
QUIET="${QUIET:-false}"

# Function to log messages
log() {
    if [ "$QUIET" != "true" ]; then
        echo -e "${GREEN}[POST-SETUP]${NC} $1"
    fi
}

log_warn() {
    echo -e "${YELLOW}[POST-SETUP WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[POST-SETUP ERROR]${NC} $1"
}

# Function to check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Function to run verification
run_verification() {
    if [ "$SKIP_VERIFICATION" = "true" ]; then
        log "Skipping verification (SKIP_VERIFICATION=true)"
        return 0
    fi

    log "Running post-setup verification..."

    if [ -f "$PROJECT_ROOT/scripts/verify-setup.sh" ]; then
        cd "$PROJECT_ROOT"
        if ./scripts/verify-setup.sh; then
            log "✅ Verification passed"
            return 0
        else
            log_warn "⚠️ Some verification checks failed"
            return 1
        fi
    else
        log_warn "Verification script not found"
        return 1
    fi
}

# Function to generate setup completion report
generate_completion_report() {
    if [ "$SKIP_REPORT" = "true" ]; then
        log "Skipping setup report generation (SKIP_REPORT=true)"
        return 0
    fi

    log "Generating setup completion report..."

    if [ -f "$PROJECT_ROOT/scripts/generate-setup-complete.sh" ]; then
        cd "$PROJECT_ROOT"

        # Set environment variables for the generator
        export PROJECT_NAME="${PROJECT_NAME:-$(basename "$PROJECT_ROOT")}"
        export SETUP_MODE="${SETUP_MODE:-$SETUP_TYPE}"
        export ENVIRONMENT="${ENVIRONMENT:-dev}"
        export INSTALL_DATE="${INSTALL_DATE:-$(date '+%Y-%m-%d %H:%M:%S')}"

        if ./scripts/generate-setup-complete.sh; then
            log "✅ Setup completion report generated: SETUP_COMPLETE.md"
            return 0
        else
            log_warn "⚠️ Failed to generate setup completion report"
            return 1
        fi
    else
        log_warn "Setup completion generator not found"
        return 1
    fi
}

# Function to fix common issues
fix_common_issues() {
    log "Checking for common issues..."

    # Fix script permissions
    if [ -d "$PROJECT_ROOT/scripts" ]; then
        chmod +x "$PROJECT_ROOT/scripts"/*.sh 2>/dev/null || true
        log "Fixed script permissions"
    fi

    # Create necessary directories
    cd "$PROJECT_ROOT"
    mkdir -p book-output logs cache 2>/dev/null || true

    # Initialize git if not already done
    if [ ! -d ".git" ]; then
        log "Initializing git repository..."
        git init --quiet 2>/dev/null || log_warn "Failed to initialize git"
    fi

    # Add .gitignore entries for generated files
    if [ -f ".gitignore" ]; then
        # Add book-output to gitignore if not already there
        if ! grep -q "book-output" .gitignore; then
            echo "# Documentation build output" >> .gitignore
            echo "book-output/" >> .gitignore
            log "Added book-output to .gitignore"
        fi

        # Add SETUP_COMPLETE.md to gitignore if not already there
        if ! grep -q "SETUP_COMPLETE.md" .gitignore; then
            echo "# Generated setup report" >> .gitignore
            echo "SETUP_COMPLETE.md" >> .gitignore
            log "Added SETUP_COMPLETE.md to .gitignore"
        fi
    fi
}

# Function to provide quick start information
show_quick_start() {
    echo ""
    echo -e "${PURPLE}🚀 Quick Start Commands${NC}"
    echo "======================="

    # Check what's available and show relevant commands
    if command_exists "just" && [ -f "$PROJECT_ROOT/justfile" ]; then
        echo -e "${BLUE}Using Just (recommended):${NC}"
        echo "  just verify-setup      # Verify installation"
        echo "  just dev               # Start development server"

        if grep -q "docs-dev" "$PROJECT_ROOT/justfile" 2>/dev/null; then
            echo "  just docs-dev          # Start documentation server"
        fi

        echo "  just help              # Show all available commands"
    fi

    echo ""
    echo -e "${BLUE}Manual commands:${NC}"
    echo "  ./scripts/verify-setup.sh         # Verify setup"

    if [ -f "$PROJECT_ROOT/scripts/docs-dev.sh" ]; then
        echo "  ./scripts/docs-dev.sh             # Start documentation"
    fi

    echo ""
    echo -e "${BLUE}Access URLs:${NC}"
    echo "  Web App: http://localhost:${SERVER_PORT:-3030}"

    if [ -f "$PROJECT_ROOT/book.toml" ]; then
        echo "  Documentation: http://localhost:3000"
    fi

    echo ""
}

# Function to detect and report setup type
detect_setup_type() {
    local detected_type="$SETUP_TYPE"

    # Try to detect based on what's present
    if [ -f "$PROJECT_ROOT/book.toml" ] && [ -d "$PROJECT_ROOT/book" ]; then
        if [ "$detected_type" = "unknown" ]; then
            detected_type="documentation"
        fi
    fi

    if [ -f "$PROJECT_ROOT/.env" ] && [ -f "$PROJECT_ROOT/Cargo.toml" ]; then
        if [ "$detected_type" = "unknown" ] || [ "$detected_type" = "documentation" ]; then
            detected_type="full"
        fi
    fi

    log "Setup type detected: $detected_type"
    export SETUP_TYPE="$detected_type"
}

# Function to show summary
show_summary() {
    echo ""
    echo -e "${GREEN}🎉 Post-Setup Complete!${NC}"
    echo "========================"
    echo ""
    echo -e "${BLUE}Setup Summary:${NC}"
    echo "  • Setup Type: $SETUP_TYPE"
    echo "  • Project: $(basename "$PROJECT_ROOT")"
    echo "  • Location: $PROJECT_ROOT"

    if [ -f "$PROJECT_ROOT/SETUP_COMPLETE.md" ]; then
        echo "  • Setup Report: ✅ Generated"
        echo ""
        echo -e "${CYAN}📋 Check SETUP_COMPLETE.md for detailed setup information${NC}"
    fi

    echo ""
    echo -e "${GREEN}✨ Ready to start developing!${NC}"
}

# Main execution
main() {
    echo -e "${BLUE}🔧 Rustelo Post-Setup Hook${NC}"
    echo "============================"
    echo ""

    cd "$PROJECT_ROOT"

    # Detect setup type if not provided
    detect_setup_type

    # Fix common issues first
    fix_common_issues

    # Run verification
    local verification_result=0
    if ! run_verification; then
        verification_result=1
    fi

    # Generate completion report
    local report_result=0
    if ! generate_completion_report; then
        report_result=1
    fi

    # Show quick start information
    show_quick_start

    # Show summary
    show_summary

    # Exit with appropriate code
    if [ $verification_result -ne 0 ] || [ $report_result -ne 0 ]; then
        echo ""
        echo -e "${YELLOW}⚠️ Some post-setup tasks had issues, but the installation should still work.${NC}"
        echo -e "${CYAN}💡 Run 'just verify-setup' to check for any remaining issues.${NC}"
        exit 1
    fi

    echo ""
    echo -e "${GREEN}🎯 Post-setup completed successfully!${NC}"
    exit 0
}

# Handle command line arguments
case "${1:-}" in
    --help|-h)
        echo "Rustelo Post-Setup Hook"
        echo ""
        echo "Usage: $0 [SETUP_TYPE] [OPTIONS]"
        echo ""
        echo "SETUP_TYPE:"
        echo "  installation  - After main installation"
        echo "  documentation - After documentation setup"
        echo "  features      - After feature configuration"
        echo "  unknown       - Auto-detect setup type"
        echo ""
        echo "Environment Variables:"
        echo "  SKIP_VERIFICATION=true   - Skip verification step"
        echo "  SKIP_REPORT=true         - Skip report generation"
        echo "  QUIET=true               - Suppress non-error output"
        echo ""
        echo "Examples:"
        echo "  $0 installation"
        echo "  $0 documentation"
        echo "  SKIP_VERIFICATION=true $0"
        exit 0
        ;;
    --version|-v)
        echo "Rustelo Post-Setup Hook v1.0.0"
        exit 0
        ;;
esac

# Run main function with all arguments
main "$@"
