#!/bin/bash

# Rustelo Setup Completion Report Generator
# This script generates a personalized SETUP_COMPLETE.md file based on the actual 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 variables (can be set from environment or .env)
PROJECT_NAME="${PROJECT_NAME:-$(basename "$PROJECT_ROOT")}"
SETUP_MODE="${SETUP_MODE:-dev}"
ENVIRONMENT="${ENVIRONMENT:-dev}"
INSTALL_DATE="${INSTALL_DATE:-$(date '+%Y-%m-%d %H:%M:%S')}"

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

# Function to get version
get_version() {
    local tool="$1"
    case "$tool" in
        "rustc")
            rustc --version 2>/dev/null | cut -d' ' -f2 || echo "unknown"
            ;;
        "cargo")
            cargo --version 2>/dev/null | cut -d' ' -f2 || echo "unknown"
            ;;
        "node")
            node --version 2>/dev/null | sed 's/v//' || echo "unknown"
            ;;
        "npm")
            npm --version 2>/dev/null || echo "unknown"
            ;;
        "pnpm")
            pnpm --version 2>/dev/null || echo "unknown"
            ;;
        "mdbook")
            mdbook --version 2>/dev/null | cut -d' ' -f2 || echo "unknown"
            ;;
        "just")
            just --version 2>/dev/null | cut -d' ' -f2 || echo "unknown"
            ;;
        "cargo-leptos")
            cargo leptos --version 2>/dev/null | grep -o 'v[0-9\.]*' | sed 's/v//' || echo "unknown"
            ;;
        *)
            echo "unknown"
            ;;
    esac
}

# Function to check features from Cargo.toml
get_enabled_features() {
    if [ -f "$PROJECT_ROOT/Cargo.toml" ]; then
        # Check default features
        grep -E "^default\s*=" "$PROJECT_ROOT/Cargo.toml" | sed 's/.*=\s*\[\(.*\)\]/\1/' | tr -d '"' | tr ',' '\n' | tr -d ' ' | sort
    fi
}

# Function to check environment variables
check_env_vars() {
    local env_file="$PROJECT_ROOT/.env"
    if [ -f "$env_file" ]; then
        # Load .env file
        while IFS='=' read -r key value; do
            # Skip comments and empty lines
            [[ $key =~ ^#.*$ ]] && continue
            [[ -z $key ]] && continue
            # Export the variable
            export "$key=$value"
        done < "$env_file"
    fi
}

# Function to get database configuration
get_database_config() {
    if [ -n "$DATABASE_URL" ]; then
        if [[ "$DATABASE_URL" == sqlite:* ]]; then
            echo "SQLite"
        elif [[ "$DATABASE_URL" == postgresql:* || "$DATABASE_URL" == postgres:* ]]; then
            echo "PostgreSQL"
        else
            echo "Custom"
        fi
    else
        echo "Not configured"
    fi
}

# Function to detect deployment platforms
detect_deployment_platforms() {
    local platforms=()

    # Check for GitHub Actions
    if [ -d "$PROJECT_ROOT/.github/workflows" ]; then
        platforms+=("GitHub Actions")
    fi

    # Check for Netlify
    if [ -f "$PROJECT_ROOT/netlify.toml" ]; then
        platforms+=("Netlify")
    fi

    # Check for Vercel
    if [ -f "$PROJECT_ROOT/vercel.json" ]; then
        platforms+=("Vercel")
    fi

    # Check for Docker
    if [ -f "$PROJECT_ROOT/Dockerfile.docs" ]; then
        platforms+=("Docker")
    fi

    if [ ${#platforms[@]} -eq 0 ]; then
        echo "Manual deployment only"
    else
        printf "%s, " "${platforms[@]}" | sed 's/, $//'
    fi
}

# Function to count documentation pages
count_doc_pages() {
    if [ -d "$PROJECT_ROOT/book" ]; then
        find "$PROJECT_ROOT/book" -name "*.md" | wc -l | tr -d ' '
    else
        echo "0"
    fi
}

# Function to get available commands
get_just_commands() {
    if command_exists "just" && [ -f "$PROJECT_ROOT/justfile" ]; then
        cd "$PROJECT_ROOT"
        just --list 2>/dev/null | grep -E "^\s*[a-zA-Z]" | wc -l | tr -d ' '
    else
        echo "0"
    fi
}

# Function to generate the setup complete document
generate_setup_complete() {
    local output_file="$PROJECT_ROOT/SETUP_COMPLETE.md"

    echo -e "${BLUE}📝 Generating setup completion report...${NC}"

    # Load environment variables
    check_env_vars

    # Get current status
    local rust_version=$(get_version "rustc")
    local cargo_version=$(get_version "cargo")
    local node_version=$(get_version "node")
    local npm_version=$(get_version "npm")
    local mdbook_version=$(get_version "mdbook")
    local just_version=$(get_version "just")
    local leptos_version=$(get_version "cargo-leptos")
    local pnpm_version=$(get_version "pnpm")

    local database_type=$(get_database_config)
    local deployment_platforms=$(detect_deployment_platforms)
    local doc_pages=$(count_doc_pages)
    local just_commands=$(get_just_commands)
    local enabled_features=$(get_enabled_features)

    # Generate the markdown file
    cat > "$output_file" << EOF
# 🎉 ${PROJECT_NAME} Setup Complete!

**Installation completed successfully on:** ${INSTALL_DATE}

Your Rustelo project has been set up with a comprehensive development environment and documentation system. This report summarizes what was installed and configured specifically for your setup.

## ✅ Installation Summary

### 🎯 Project Configuration
- **Project Name**: ${PROJECT_NAME}
- **Setup Mode**: ${SETUP_MODE}
- **Environment**: ${ENVIRONMENT}
- **Installation Date**: ${INSTALL_DATE}
- **Project Location**: \`${PROJECT_ROOT}\`

### 🛠️ Core Tools Installed

| Tool | Version | Status |
|------|---------|--------|
EOF

    # Add tool status
    if command_exists "rustc"; then
        echo "| Rust Compiler | ${rust_version} | ✅ Installed |" >> "$output_file"
    else
        echo "| Rust Compiler | - | ❌ Not Found |" >> "$output_file"
    fi

    if command_exists "cargo"; then
        echo "| Cargo | ${cargo_version} | ✅ Installed |" >> "$output_file"
    else
        echo "| Cargo | - | ❌ Not Found |" >> "$output_file"
    fi

    if command_exists "node"; then
        echo "| Node.js | ${node_version} | ✅ Installed |" >> "$output_file"
    else
        echo "| Node.js | - | ❌ Not Found |" >> "$output_file"
    fi

    if command_exists "npm"; then
        echo "| npm | ${npm_version} | ✅ Installed |" >> "$output_file"
    else
        echo "| npm | - | ❌ Not Found |" >> "$output_file"
    fi

    if command_exists "mdbook"; then
        echo "| mdBook | ${mdbook_version} | ✅ Installed |" >> "$output_file"
    else
        echo "| mdBook | - | ❌ Not Found |" >> "$output_file"
    fi

    if command_exists "just"; then
        echo "| Just | ${just_version} | ✅ Installed |" >> "$output_file"
    else
        echo "| Just | - | ❌ Not Found |" >> "$output_file"
    fi

    if command_exists "cargo-leptos"; then
        echo "| cargo-leptos | ${leptos_version} | ✅ Installed |" >> "$output_file"
    else
        echo "| cargo-leptos | - | ❌ Not Found |" >> "$output_file"
    fi

    if command_exists "pnpm"; then
        echo "| pnpm | ${pnpm_version} | ✅ Installed |" >> "$output_file"
    else
        echo "| pnpm | - | ⚠️ Optional |" >> "$output_file"
    fi

    cat >> "$output_file" << EOF

### 📚 Documentation System

| Component | Status | Details |
|-----------|--------|---------|
| mdBook Configuration | $([ -f "$PROJECT_ROOT/book.toml" ] && echo "✅ Configured" || echo "❌ Missing") | Interactive documentation system |
| Documentation Pages | ✅ ${doc_pages} pages | Comprehensive guides and references |
| Auto-Generated Content | $([ -f "$PROJECT_ROOT/book/appendices/feature-matrix.md" ] && echo "✅ Generated" || echo "❌ Missing") | Feature matrices, env vars, CLI refs |
| Custom Styling | $([ -f "$PROJECT_ROOT/book/theme/custom.css" ] && echo "✅ Configured" || echo "❌ Default") | Branded documentation theme |
| Deployment Ready | ${deployment_platforms} | Multiple deployment options |

### ⚡ Task Runner (Just)

| Component | Status | Details |
|-----------|--------|---------|
| Just Commands | ✅ ${just_commands} commands | Development workflow automation |
| Documentation Commands | $(grep -q "docs-dev" "$PROJECT_ROOT/justfile" 2>/dev/null && echo "✅ Available" || echo "❌ Missing") | Complete docs workflow |
| Development Commands | $(grep -q "dev" "$PROJECT_ROOT/justfile" 2>/dev/null && echo "✅ Available" || echo "❌ Missing") | Build, test, run commands |
| Verification Commands | $(grep -q "verify-setup" "$PROJECT_ROOT/justfile" 2>/dev/null && echo "✅ Available" || echo "❌ Missing") | Setup verification |

### 🗄️ Database Configuration

| Setting | Value |
|---------|-------|
| Database Type | ${database_type} |
| Connection URL | $([ -n "$DATABASE_URL" ] && echo "✅ Configured" || echo "❌ Not set") |
| Migrations | $([ -d "$PROJECT_ROOT/migrations" ] && echo "✅ Available" || echo "❌ Not found") |

### 🎛️ Feature Configuration

EOF

    if [ -n "$enabled_features" ]; then
        echo "**Enabled Features:**" >> "$output_file"
        echo "$enabled_features" | while read -r feature; do
            [ -n "$feature" ] && echo "- ✅ \`${feature}\`" >> "$output_file"
        done
    else
        echo "**Features:** Default configuration" >> "$output_file"
    fi

    cat >> "$output_file" << EOF

**Environment Variables:**
- Authentication: $([ "$ENABLE_AUTH" = "true" ] && echo "✅ Enabled" || echo "❌ Disabled")
- Content Database: $([ "$ENABLE_CONTENT_DB" = "true" ] && echo "✅ Enabled" || echo "❌ Disabled")
- TLS/HTTPS: $([ "$ENABLE_TLS" = "true" ] && echo "✅ Enabled" || echo "❌ Disabled")
- Email System: $([ "$ENABLE_EMAIL" = "true" ] && echo "✅ Enabled" || echo "❌ Disabled")

## 🚀 Quick Start Commands

### Verify Installation
\`\`\`bash
# Verify everything is working correctly
just verify-setup
\`\`\`

### Start Development
\`\`\`bash
# Start web application (main terminal)
just dev

# Start documentation server (new terminal)
just docs-dev
\`\`\`

### Access Your Applications
- **Web Application**: http://localhost:${SERVER_PORT:-3030}
- **Documentation**: http://localhost:3000
- **API Health Check**: http://localhost:${SERVER_PORT:-3030}/api/health

### Build & Deploy Documentation
\`\`\`bash
# Build documentation
just docs-build

# Deploy to GitHub Pages
just docs-deploy-github

# Show all documentation commands
just help-docs
\`\`\`

## 📖 Documentation Features

### 🎯 What's Available
- **📚 ${doc_pages} Documentation Pages** - Comprehensive guides covering all aspects
- **🔍 Full-Text Search** - Instant search across all documentation
- **📱 Mobile-Responsive** - Perfect experience on all devices
- **🎨 Custom Branding** - Styled with Rustelo theme
- **🔗 Cross-References** - Automatic linking between sections
- **📋 Auto-Generated Content** - Feature matrices and references

### 📂 Content Structure
\`\`\`
book/
├── getting-started/     # Installation and setup guides
├── features/           # Feature documentation
├── database/          # Database configuration
├── development/       # Development workflow
├── deployment/        # Production deployment
├── api/              # API reference
├── security/         # Security best practices
├── troubleshooting/  # Common issues
└── appendices/       # References and matrices
\`\`\`

### 🌐 Deployment Options
$([ -d "$PROJECT_ROOT/.github/workflows" ] && echo "- **✅ GitHub Pages** - Automated CI/CD configured" || echo "- **📋 GitHub Pages** - Run \`./scripts/setup-docs.sh --ci\` to configure")
$([ -f "$PROJECT_ROOT/netlify.toml" ] && echo "- **✅ Netlify** - Configuration ready" || echo "- **📋 Netlify** - Run \`just docs-deploy-netlify\` to deploy")
$([ -f "$PROJECT_ROOT/vercel.json" ] && echo "- **✅ Vercel** - Configuration ready" || echo "- **📋 Vercel** - Run \`just docs-deploy-vercel\` to deploy")
$([ -f "$PROJECT_ROOT/Dockerfile.docs" ] && echo "- **✅ Docker** - Container configuration ready" || echo "- **📋 Docker** - Run \`just docs-docker\` to build container")
- **📋 AWS S3** - Run \`just docs-deploy-aws-s3\` with configured bucket

## ⚡ Available Commands

### Documentation Commands
\`\`\`bash
just docs-dev              # Start documentation dev server
just docs-build            # Build documentation
just docs-build-sync       # Build with content sync
just docs-deploy-github    # Deploy to GitHub Pages
just docs-deploy-netlify   # Deploy to Netlify
just docs-deploy-vercel    # Deploy to Vercel
just docs-docker           # Build Docker container
just docs-generate         # Generate dynamic content
just docs-clean            # Clean build files
just help-docs             # Show all documentation commands
\`\`\`

### Development Commands
\`\`\`bash
just dev                   # Start development server
just build                 # Build project
just build-prod           # Build for production
just test                  # Run tests
just check                 # Check code quality
just verify-setup          # Verify installation
just help                  # Show all commands
\`\`\`

## 🎨 Customization

### Documentation Branding
Edit \`book/theme/custom.css\` to customize:
\`\`\`css
:root {
    --rustelo-primary: #e53e3e;
    --rustelo-secondary: #3182ce;
    --rustelo-accent: #38a169;
}
\`\`\`

### Content Organization
Edit \`book/SUMMARY.md\` to add your own sections:
\`\`\`markdown
# Summary

[Introduction](./introduction.md)

# Your Custom Section
- [Your Page](./your-section/your-page.md)
\`\`\`

### Environment Configuration
Edit \`.env\` to configure your application:
\`\`\`bash
# Server Configuration
SERVER_HOST=${SERVER_HOST:-127.0.0.1}
SERVER_PORT=${SERVER_PORT:-3030}
ENVIRONMENT=${ENVIRONMENT:-dev}

# Database
DATABASE_URL=${DATABASE_URL:-sqlite:database.db}

# Features
ENABLE_AUTH=${ENABLE_AUTH:-true}
ENABLE_CONTENT_DB=${ENABLE_CONTENT_DB:-true}
\`\`\`

## 🔍 Next Steps

### Immediate (Next 15 minutes)
1. **✅ Verify Setup** - Run \`just verify-setup\`
2. **🚀 Start Servers** - Run \`just dev\` and \`just docs-dev\`
3. **📖 Explore Documentation** - Visit http://localhost:3000

### Short-term (Next hour)
1. **🎨 Customize Branding** - Update colors and styling
2. **📝 Add Your Content** - Edit documentation in \`book/\` directory
3. **🌐 Deploy Documentation** - Choose a deployment platform

### Long-term (Next week)
1. **🔧 Configure Features** - Enable authentication, database, email
2. **📊 Set Up Monitoring** - Add analytics and performance tracking
3. **🤝 Team Collaboration** - Set up CI/CD for team contributions

## 📚 Learning Resources

### Documentation System
- **[mdBook Guide](https://rust-lang.github.io/mdBook/)** - Complete documentation
- **[Just Manual](https://github.com/casey/just)** - Task runner guide
- **[Markdown Guide](https://www.markdownguide.org/)** - Syntax reference

### Rustelo Framework
- **[Leptos Book](https://book.leptos.dev/)** - Frontend framework
- **[Axum Documentation](https://docs.rs/axum/)** - Web server framework

### Your Project Documentation
- **[Getting Started](book/getting-started/quick-start.md)** - Start here
- **[Features Guide](book/features/overview.md)** - Explore features
- **[Development Guide](book/development/setup.md)** - Development workflow

## 🆘 Troubleshooting

### Common Issues
\`\`\`bash
# Port already in use
SERVER_PORT=3031 just dev

# Documentation won't build
just docs-clean && just docs-build

# Permission errors
chmod +x scripts/*.sh

# Update everything
just update
\`\`\`

### Getting Help
- **📖 Documentation** - Check the complete guide at http://localhost:3000
- **🔍 Verification** - Run \`just verify-setup\` for diagnostics
- **💬 Community** - GitHub discussions and issues
- **📧 Support** - Contact project maintainers

## 📊 Installation Statistics

- **Total Files Created**: $(find "$PROJECT_ROOT" -name "*.md" -o -name "*.toml" -o -name "*.sh" | wc -l | tr -d ' ')
- **Documentation Pages**: ${doc_pages}
- **Available Commands**: ${just_commands}
- **Setup Time**: Completed at ${INSTALL_DATE}
- **Project Size**: $(du -sh "$PROJECT_ROOT" 2>/dev/null | cut -f1 || echo "Unknown")

## 🎉 Congratulations!

Your ${PROJECT_NAME} project is now fully configured with:

- **✅ Professional Documentation System** - Ready for production
- **✅ Modern Development Workflow** - Automated and efficient
- **✅ Multiple Deployment Options** - Choose what works best
- **✅ Mobile-First Experience** - Works on all devices
- **✅ Comprehensive Verification** - Ensures everything functions

### Ready to Build!
\`\`\`bash
# Start developing immediately
just dev & just docs-dev

# Show all available commands
just help
\`\`\`

**Happy coding with Rustelo!** 🦀📚✨

---

*This setup provides everything needed for professional web application development with world-class documentation. The system grows with your project from initial development to production deployment.*

**Need help?** Run \`just verify-setup\` or check the [troubleshooting guide](book/troubleshooting/common-issues.md).

---

**Generated on:** ${INSTALL_DATE}
**Setup Script Version:** $(grep "VERSION=" "$SCRIPT_DIR/setup-docs.sh" 2>/dev/null | cut -d'=' -f2 || echo "1.0.0")
EOF

    echo -e "${GREEN}✅ Setup completion report generated: ${output_file}${NC}"

    # Display summary
    echo ""
    echo -e "${BLUE}📊 Setup Summary:${NC}"
    echo "  • Project: ${PROJECT_NAME}"
    echo "  • Documentation Pages: ${doc_pages}"
    echo "  • Just Commands: ${just_commands}"
    echo "  • Database: ${database_type}"
    echo "  • Deployment: ${deployment_platforms}"
    echo ""
    echo -e "${GREEN}🎉 Setup complete! Check SETUP_COMPLETE.md for full details.${NC}"
}

# Main execution
main() {
    cd "$PROJECT_ROOT"

    echo -e "${BLUE}📝 Generating Setup Completion Report${NC}"
    echo "======================================"

    generate_setup_complete

    echo ""
    echo -e "${CYAN}Quick commands to get started:${NC}"
    echo "  just verify-setup    # Verify installation"
    echo "  just dev             # Start development"
    echo "  just docs-dev        # Start documentation"
    echo ""
}

# Run main function
main "$@"
