#!/bin/bash

# Rustelo Documentation Setup Script
# This script sets up the complete documentation system for Rustelo

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"))"

echo -e "${BLUE}📚 Rustelo Documentation Setup${NC}"
echo "================================="
echo ""
echo "This script will set up a comprehensive documentation system including:"
echo "• mdBook configuration and structure"
echo "• Automated content generation"
echo "• Build and deployment scripts"
echo "• CI/CD integration"
echo "• Local development environment"
echo ""

# Function to show usage
show_usage() {
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  --full          Complete setup with all features"
    echo "  --minimal       Minimal setup (just mdBook)"
    echo "  --sync          Sync existing documentation"
    echo "  --interactive   Interactive setup (default)"
    echo "  --ci            Setup CI/CD integration"
    echo "  --no-install    Skip package installation"
    echo "  --help          Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0                    # Interactive setup"
    echo "  $0 --full            # Complete automated setup"
    echo "  $0 --minimal         # Minimal setup"
    echo "  $0 --sync --full     # Sync existing docs and full setup"
}

# Parse command line arguments
SETUP_MODE="interactive"
SYNC_EXISTING=false
SETUP_CI=false
INSTALL_PACKAGES=true

while [[ $# -gt 0 ]]; do
    case $1 in
        --full)
            SETUP_MODE="full"
            shift
            ;;
        --minimal)
            SETUP_MODE="minimal"
            shift
            ;;
        --sync)
            SYNC_EXISTING=true
            shift
            ;;
        --interactive)
            SETUP_MODE="interactive"
            shift
            ;;
        --ci)
            SETUP_CI=true
            shift
            ;;
        --no-install)
            INSTALL_PACKAGES=false
            shift
            ;;
        --help)
            show_usage
            exit 0
            ;;
        *)
            echo -e "${RED}❌ Unknown option: $1${NC}"
            show_usage
            exit 1
            ;;
    esac
done

# Check if running interactively
if [ "$SETUP_MODE" = "interactive" ] && [ -t 0 ]; then
    echo -e "${CYAN}🤔 What type of documentation setup would you like?${NC}"
    echo "1) Full setup (recommended) - Complete documentation system"
    echo "2) Minimal setup - Basic mdBook only"
    echo "3) Custom setup - Choose specific components"
    echo ""
    read -p "Enter your choice (1-3): " choice

    case $choice in
        1)
            SETUP_MODE="full"
            ;;
        2)
            SETUP_MODE="minimal"
            ;;
        3)
            SETUP_MODE="custom"
            ;;
        *)
            echo -e "${YELLOW}Using full setup (default)${NC}"
            SETUP_MODE="full"
            ;;
    esac
fi

# Custom setup questions
if [ "$SETUP_MODE" = "custom" ]; then
    echo ""
    echo -e "${CYAN}🔧 Custom Setup Configuration${NC}"

    read -p "Sync existing documentation? (y/n): " sync_answer
    case $sync_answer in
        [Yy]*)
            SYNC_EXISTING=true
            ;;
    esac

    read -p "Setup CI/CD integration? (y/n): " ci_answer
    case $ci_answer in
        [Yy]*)
            SETUP_CI=true
            ;;
    esac

    read -p "Install required packages? (y/n): " install_answer
    case $install_answer in
        [Nn]*)
            INSTALL_PACKAGES=false
            ;;
    esac
fi

# Change to project root
cd "$PROJECT_ROOT"

echo ""
echo -e "${BLUE}🔍 Checking current environment...${NC}"

# Check if we're in a git repository
if [ ! -d ".git" ]; then
    echo -e "${YELLOW}⚠️  Not in a git repository. Some features may be limited.${NC}"
    read -p "Continue anyway? (y/n): " continue_answer
    case $continue_answer in
        [Nn]*)
            echo "Exiting..."
            exit 0
            ;;
    esac
fi

# Check for existing documentation
EXISTING_DOCS=false
if [ -d "docs" ] || [ -d "info" ] || [ -f "README.md" ]; then
    EXISTING_DOCS=true
    echo -e "${GREEN}✅ Found existing documentation${NC}"
fi

# Check for existing mdBook setup
EXISTING_MDBOOK=false
if [ -f "book.toml" ]; then
    EXISTING_MDBOOK=true
    echo -e "${YELLOW}⚠️  Found existing mdBook setup${NC}"
    read -p "Overwrite existing mdBook configuration? (y/n): " overwrite_answer
    case $overwrite_answer in
        [Nn]*)
            echo "Keeping existing mdBook configuration"
            ;;
        *)
            echo "Will overwrite existing configuration"
            ;;
    esac
fi

# Install required packages
install_packages() {
    echo ""
    echo -e "${BLUE}📦 Installing required packages...${NC}"

    # Check if Rust is installed
    if ! command -v cargo &> /dev/null; then
        echo -e "${RED}❌ Rust is not installed${NC}"
        echo "Please install Rust from https://rustup.rs/"
        echo "After installation, restart your terminal and run this script again."
        exit 1
    fi

    # Check Rust version
    local rust_version=$(rustc --version 2>/dev/null | cut -d' ' -f2)
    echo -e "${GREEN}✅ Rust version: $rust_version${NC}"

    # Install mdBook
    if ! command -v mdbook &> /dev/null; then
        echo -e "${YELLOW}📚 Installing mdBook...${NC}"
        cargo install mdbook
        echo -e "${GREEN}✅ mdBook installed${NC}"
    else
        echo -e "${GREEN}✅ mdBook already installed${NC}"
    fi

    # Install Just task runner
    if ! command -v just &> /dev/null; then
        echo -e "${YELLOW}⚡ Installing Just task runner...${NC}"
        cargo install just
        echo -e "${GREEN}✅ Just installed${NC}"
    else
        echo -e "${GREEN}✅ Just already installed${NC}"
    fi

    # Install optional mdBook plugins
    if [ "$SETUP_MODE" = "full" ] || [ "$SETUP_MODE" = "custom" ]; then
        echo -e "${YELLOW}🔧 Installing mdBook plugins...${NC}"

        # mdbook-linkcheck for broken link detection
        if ! command -v mdbook-linkcheck &> /dev/null; then
            echo "Installing mdbook-linkcheck..."
            cargo install mdbook-linkcheck || echo -e "${YELLOW}⚠️ Failed to install mdbook-linkcheck (optional)${NC}"
        fi

        # mdbook-toc for table of contents
        if ! command -v mdbook-toc &> /dev/null; then
            echo "Installing mdbook-toc..."
            cargo install mdbook-toc || echo -e "${YELLOW}⚠️ Failed to install mdbook-toc (optional)${NC}"
        fi

        # mdbook-mermaid for diagrams
        if ! command -v mdbook-mermaid &> /dev/null; then
            echo "Installing mdbook-mermaid..."
            cargo install mdbook-mermaid || echo -e "${YELLOW}⚠️ Failed to install mdbook-mermaid (optional)${NC}"
        fi

        echo -e "${GREEN}✅ mdBook plugins installation complete${NC}"
    fi
}

# Create directory structure
create_structure() {
    echo ""
    echo -e "${BLUE}📁 Creating documentation structure...${NC}"

    # Create main directories
    mkdir -p book/{getting-started,features,database,development,configuration,deployment,api,security,performance,troubleshooting,advanced,contributing,appendices}
    mkdir -p book/features/{auth,content,email}
    mkdir -p book/theme
    mkdir -p book-output

    # Create placeholder files for main sections
    touch book/getting-started/{installation.md,configuration.md,first-app.md}
    touch book/features/{authentication.md,content-management.md,tls.md,email.md,combinations.md}
    touch book/features/auth/{jwt.md,oauth2.md,2fa.md,sessions.md}
    touch book/features/content/{markdown.md,database.md,static.md}
    touch book/database/{overview.md,postgresql.md,sqlite.md,configuration.md,migrations.md,abstraction.md}
    touch book/development/{setup.md,structure.md,workflow.md,testing.md,debugging.md,hot-reloading.md}
    touch book/configuration/{environment.md,files.md,features.md,security.md}
    touch book/deployment/{overview.md,docker.md,production.md,environments.md,monitoring.md}
    touch book/api/{overview.md,auth.md,content.md,errors.md,rate-limiting.md}
    touch book/security/{overview.md,auth.md,data-protection.md,csrf.md,tls.md,best-practices.md}
    touch book/performance/{overview.md,optimization.md,caching.md,database.md,monitoring.md}
    touch book/troubleshooting/{common-issues.md,database.md,auth.md,build.md,runtime.md}
    touch book/advanced/{custom-features.md,extending-auth.md,custom-content.md,integrations.md,performance-tuning.md}
    touch book/contributing/{guide.md,setup.md,standards.md,testing.md,docs.md}
    touch book/appendices/{feature-matrix.md,env-variables.md,cli-commands.md,migration-guide.md,faq.md}
    touch book/glossary.md

    echo -e "${GREEN}✅ Directory structure created${NC}"
}

# Sync existing documentation
sync_existing_docs() {
    if [ "$SYNC_EXISTING" = true ] && [ "$EXISTING_DOCS" = true ]; then
        echo ""
        echo -e "${BLUE}🔄 Syncing existing documentation...${NC}"

        # Sync from docs directory
        if [ -d "docs" ]; then
            echo "Syncing from docs/ directory..."

            # Map existing files to new structure
            [ -f "docs/database_configuration.md" ] && cp "docs/database_configuration.md" "book/database/configuration.md"
            [ -f "docs/2fa_implementation.md" ] && cp "docs/2fa_implementation.md" "book/features/auth/2fa.md"
            [ -f "docs/email.md" ] && cp "docs/email.md" "book/features/email.md"
            [ -f "docs/database_migration_guide.md" ] && cp "docs/database_migration_guide.md" "book/database/migrations.md"
            [ -f "docs/quick_database_setup.md" ] && cp "docs/quick_database_setup.md" "book/database/overview.md"
            [ -f "docs/encryption.md" ] && cp "docs/encryption.md" "book/security/data-protection.md"
            [ -f "docs/leptos_serve.md" ] && cp "docs/leptos_serve.md" "book/development/hot-reloading.md"
        fi

        # Sync from info directory
        if [ -d "info" ]; then
            echo "Syncing from info/ directory..."

            # Map info files to appropriate sections
            [ -f "info/features.md" ] && cp "info/features.md" "book/features/detailed-features.md"
            [ -f "info/deployment.md" ] && cp "info/deployment.md" "book/deployment/overview.md"
            [ -f "info/config.md" ] && cp "info/config.md" "book/configuration/overview.md"
            [ -f "info/auth_readme.md" ] && cp "info/auth_readme.md" "book/features/authentication.md"
            [ -f "info/database_abstraction.md" ] && cp "info/database_abstraction.md" "book/database/abstraction.md"
            [ -f "info/testing_performance.md" ] && cp "info/testing_performance.md" "book/performance/overview.md"
            [ -f "info/migration_guide.md" ] && cp "info/migration_guide.md" "book/appendices/migration-guide.md"
        fi

        # Process README.md
        if [ -f "README.md" ]; then
            echo "Processing README.md..."
            # Extract sections from README and create appropriate files
            # This is a simplified approach - in practice, you'd want more sophisticated parsing
            head -n 50 "README.md" > "book/overview-from-readme.md"
        fi

        echo -e "${GREEN}✅ Existing documentation synced${NC}"
    fi
}

# Setup CI/CD integration
setup_ci_cd() {
    if [ "$SETUP_CI" = true ]; then
        echo ""
        echo -e "${BLUE}🔄 Setting up CI/CD integration...${NC}"

        # Create GitHub Actions workflow
        mkdir -p .github/workflows

        cat > .github/workflows/docs.yml << 'EOF'
name: Build and Deploy Documentation

on:
  push:
    branches: [ main, master ]
    paths:
      - 'book/**'
      - 'book.toml'
      - 'docs/**'
      - 'info/**'
      - 'README.md'
      - '.github/workflows/docs.yml'
  pull_request:
    branches: [ main, master ]
    paths:
      - 'book/**'
      - 'book.toml'
      - 'docs/**'
      - 'info/**'
      - 'README.md'

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v4

    - name: Setup Rust
      uses: actions-rs/toolchain@v1
      with:
        toolchain: stable
        override: true

    - name: Install mdBook
      run: cargo install mdbook

    - name: Install mdBook plugins
      run: |
        cargo install mdbook-linkcheck
        cargo install mdbook-toc
        cargo install mdbook-mermaid

    - name: Build documentation
      run: mdbook build

    - name: Check for broken links
      run: mdbook-linkcheck

    - name: Upload build artifacts
      uses: actions/upload-artifact@v3
      with:
        name: documentation
        path: book-output/html

    - name: Deploy to GitHub Pages
      if: github.ref == 'refs/heads/main' && github.event_name == 'push'
      uses: peaceiris/actions-gh-pages@v3
      with:
        github_token: ${{ secrets.GITHUB_TOKEN }}
        publish_dir: ./book-output/html
        cname: your-custom-domain.com  # Optional: replace with your domain
EOF

        echo -e "${GREEN}✅ CI/CD configuration created${NC}"
        echo "  • GitHub Actions workflow created"
        echo "  • Automatic deployment to GitHub Pages configured"
        echo "  • Link checking enabled"
    fi
}

# Create helper scripts
create_scripts() {
    echo ""
    echo -e "${BLUE}📜 Creating helper scripts...${NC}"

    # Make sure scripts directory exists
    mkdir -p scripts

    # Create quick development script
    cat > scripts/docs-dev.sh << 'EOF'
#!/bin/bash
# Quick development script for documentation

set -e

echo "🚀 Starting documentation development server..."
echo "Documentation will be available at: http://localhost:3000"
echo "Press Ctrl+C to stop"

# Change to project root
cd "$(dirname "$0")/.."

# Start mdBook serve with live reload
mdbook serve --open --port 3000
EOF

    chmod +x scripts/docs-dev.sh

    # Create content generation script
    cat > scripts/generate-content.sh << 'EOF'
#!/bin/bash
# Generate dynamic content for documentation

set -e

PROJECT_ROOT="$(dirname "$0")/.."
cd "$PROJECT_ROOT"

echo "📝 Generating dynamic documentation content..."

# Generate feature matrix
echo "Generating feature matrix..."
cat > book/appendices/feature-matrix.md << 'MATRIX_EOF'
# Feature Matrix

This matrix shows which features are available in different configurations.

| Feature | Minimal | Auth | Content | Email | TLS | Full |
|---------|---------|------|---------|-------|-----|------|
| Static Files | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Routing | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Security Headers | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| JWT Auth | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ |
| OAuth2 | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ |
| 2FA/TOTP | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ |
| Database Content | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ |
| Markdown Rendering | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ |
| Email System | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ |
| HTTPS/TLS | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ |

## Build Commands

```bash
# Minimal
cargo build --no-default-features

# Authentication only
cargo build --no-default-features --features "auth"

# Content management only
cargo build --no-default-features --features "content-db"

# Email only
cargo build --no-default-features --features "email"

# TLS only
cargo build --no-default-features --features "tls"

# Full featured
cargo build --features "auth,content-db,email,tls"
```
MATRIX_EOF

# Generate environment variables reference
echo "Generating environment variables reference..."
cat > book/appendices/env-variables.md << 'ENV_EOF'
# Environment Variables Reference

This document lists all environment variables used by Rustelo.

## Core Variables

| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| `SERVER_HOST` | Server bind address | `127.0.0.1` | No |
| `SERVER_PORT` | Server port | `3030` | No |
| `SERVER_PROTOCOL` | Protocol (http/https) | `http` | No |
| `ENVIRONMENT` | Environment (DEV/PROD) | `DEV` | No |
| `LOG_LEVEL` | Log level | `info` | No |

## Database Variables (auth, content-db features)

| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| `DATABASE_URL` | Database connection URL | - | Yes |
| `DATABASE_MAX_CONNECTIONS` | Maximum connections | `10` | No |
| `DATABASE_MIN_CONNECTIONS` | Minimum connections | `1` | No |

## Authentication Variables (auth feature)

| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| `JWT_SECRET` | JWT signing secret | - | Yes |
| `JWT_EXPIRATION_HOURS` | JWT expiration | `24` | No |
| `GOOGLE_CLIENT_ID` | Google OAuth client ID | - | No |
| `GOOGLE_CLIENT_SECRET` | Google OAuth secret | - | No |
| `GITHUB_CLIENT_ID` | GitHub OAuth client ID | - | No |
| `GITHUB_CLIENT_SECRET` | GitHub OAuth secret | - | No |

## TLS Variables (tls feature)

| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| `TLS_CERT_PATH` | TLS certificate path | - | Yes |
| `TLS_KEY_PATH` | TLS private key path | - | Yes |

## Email Variables (email feature)

| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| `EMAIL_PROVIDER` | Email provider | `console` | No |
| `EMAIL_FROM_ADDRESS` | Default from address | - | Yes |
| `EMAIL_FROM_NAME` | Default from name | - | No |
| `SMTP_HOST` | SMTP server host | - | Conditional |
| `SMTP_PORT` | SMTP server port | `587` | Conditional |
| `SMTP_USERNAME` | SMTP username | - | Conditional |
| `SMTP_PASSWORD` | SMTP password | - | Conditional |
ENV_EOF

echo "✅ Dynamic content generated"
EOF

    chmod +x scripts/generate-content.sh

    echo -e "${GREEN}✅ Helper scripts created${NC}"
    echo "  • docs-dev.sh - Development server"
    echo "  • generate-content.sh - Dynamic content generation"
}

# Create example content
create_example_content() {
    echo ""
    echo -e "${BLUE}📝 Creating example content...${NC}"

    # Create a sample getting started page
    cat > book/getting-started/installation.md << 'EOF'
# Installation

This guide will help you install and set up Rustelo on your development machine.

## Prerequisites

Before installing Rustelo, ensure you have the following:

- **Rust 1.75+** - [Install Rust](https://rustup.rs/)
- **Node.js 18+** - [Install Node.js](https://nodejs.org/)
- **Git** - [Install Git](https://git-scm.com/)

## Installation Methods

### Method 1: Clone the Repository

```bash
git clone https://github.com/yourusername/rustelo.git
cd rustelo
```

### Method 2: Use as Template

1. Click "Use this template" on GitHub
2. Create your new repository
3. Clone your repository

```bash
git clone https://github.com/yourusername/your-app.git
cd your-app
```

## Verification

Verify your installation:

```bash
# Check Rust version
rustc --version

# Check Cargo version
cargo --version

# Check Node.js version
node --version

# Check npm version
npm --version
```

## Next Steps

Continue with [Configuration](./configuration.md) to set up your application.
EOF

    # Create a sample database overview
    cat > book/database/overview.md << 'EOF'
# Database Overview

Rustelo supports multiple database backends through its unified database abstraction layer.

## Supported Databases

### PostgreSQL
- **Recommended for**: Production deployments
- **Features**: Full ACID compliance, advanced features, network access
- **Connection**: `postgresql://user:password@host:port/database`

### SQLite
- **Recommended for**: Development and testing
- **Features**: Zero configuration, file-based, perfect for local development
- **Connection**: `sqlite:database.db`

## Database Features

| Feature | PostgreSQL | SQLite |
|---------|------------|---------|
| ACID Transactions | ✅ | ✅ |
| Concurrent Reads | ✅ | ✅ |
| Concurrent Writes | ✅ | ⚠️ Limited |
| Network Access | ✅ | ❌ |
| JSON Support | ✅ (JSONB) | ✅ (TEXT) |
| Full-text Search | ✅ | ✅ (FTS) |

## Quick Setup

### SQLite (Development)
```bash
# Set in .env
DATABASE_URL=sqlite:database.db
```

### PostgreSQL (Production)
```bash
# Start with Docker
docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=password postgres

# Set in .env
DATABASE_URL=postgresql://postgres:password@localhost:5432/rustelo
```

## Next Steps

- [PostgreSQL Setup](./postgresql.md)
- [SQLite Setup](./sqlite.md)
- [Configuration](./configuration.md)
- [Migrations](./migrations.md)
EOF

    echo -e "${GREEN}✅ Example content created${NC}"
}

# Generate final summary
generate_summary() {
    echo ""
    echo -e "${PURPLE}📋 Documentation Setup Summary${NC}"
    echo "=================================="
    echo ""
    echo -e "${GREEN}✅ Setup completed successfully!${NC}"
    echo ""
    echo "📁 Created structure:"
    echo "  • book/ - Documentation source files"
    echo "  • book-output/ - Built documentation"
    echo "  • scripts/ - Helper scripts"
    echo "  • .github/workflows/ - CI/CD configuration (if enabled)"
    echo ""
    echo "📜 Available scripts:"
    echo "  • ./scripts/build-docs.sh - Build documentation"
    echo "  • ./scripts/deploy-docs.sh - Deploy documentation"
    echo "  • ./scripts/docs-dev.sh - Development server"
    echo "  • ./scripts/generate-content.sh - Generate dynamic content"
    echo ""
    echo "🚀 Quick commands:"
    echo "  • Start development server: ./scripts/docs-dev.sh"
    echo "  • Build documentation: ./scripts/build-docs.sh"
    echo "  • Deploy to GitHub Pages: ./scripts/deploy-docs.sh github-pages"
    echo "  • Generate content: ./scripts/generate-content.sh"
    echo ""
    echo "⚡ Just commands (task runner):"
    echo "  • just docs-dev - Start development server"
    echo "  • just docs-build - Build documentation"
    echo "  • just docs-deploy-github - Deploy to GitHub Pages"
    echo "  • just help-docs - Show all documentation commands"
    echo ""
    echo "📚 Next steps:"
    echo "  1. Start the development server: ./scripts/docs-dev.sh"
    echo "  2. Edit content in the book/ directory"
    echo "  3. Build and deploy when ready"
    echo ""
    echo "🌐 Documentation will be available at:"
    echo "  • Local: http://localhost:3000"
    echo "  • GitHub Pages: https://yourusername.github.io/rustelo"
    echo ""
    echo -e "${CYAN}Happy documenting! 📖✨${NC}"

    # Run post-setup hook for documentation setup
    echo ""
    echo -e "${BLUE}🔧 Running post-setup finalization...${NC}"
    if [ -f "$PROJECT_ROOT/scripts/post-setup-hook.sh" ]; then
        export PROJECT_NAME="${PROJECT_NAME:-$(basename "$PROJECT_ROOT")}"
        export SETUP_MODE="${SETUP_MODE:-documentation}"
        export ENVIRONMENT="${ENVIRONMENT:-dev}"
        export INSTALL_DATE="$(date '+%Y-%m-%d %H:%M:%S')"

        if ./scripts/post-setup-hook.sh "documentation"; then
            echo -e "${GREEN}✅ Post-setup finalization completed${NC}"
        else
            echo -e "${YELLOW}⚠️ Some post-setup tasks had issues${NC}"
        fi
    else
        # Fallback to generating report directly if hook not available
        if [ ! -f "$PROJECT_ROOT/SETUP_COMPLETE.md" ] && [ -f "$PROJECT_ROOT/scripts/generate-setup-complete.sh" ]; then
            echo -e "${BLUE}📝 Generating setup completion report...${NC}"
            if ./scripts/generate-setup-complete.sh; then
                echo -e "${GREEN}✅ Setup report generated: SETUP_COMPLETE.md${NC}"
            fi
        fi
    fi
}

# Main execution
main() {
    # Install packages if requested
    if [ "$INSTALL_PACKAGES" = true ]; then
        install_packages
    fi

    # Create directory structure
    create_structure

    # Sync existing documentation
    sync_existing_docs

    # Setup CI/CD if requested
    setup_ci_cd

    # Create helper scripts
    create_scripts

    # Create example content
    if [ "$SETUP_MODE" = "full" ] || [ "$SETUP_MODE" = "custom" ]; then
        create_example_content
    fi

    # Generate dynamic content
    if [ -f "scripts/generate-content.sh" ]; then
        ./scripts/generate-content.sh
    fi

    # Generate summary
    generate_summary
}

# Run main function
main

echo ""
echo -e "${GREEN}🎉 Documentation setup complete!${NC}"
