#!/usr/bin/env bash

set -euo pipefail

###############################################################################
# MkDocs site generator for ConcourseGPT
# Handles MkDocs configuration and site generation
###############################################################################

# Source required utilities
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
source "${SCRIPT_DIR}/utils/formatting.sh"

# Install MkDocs dependencies
install_deps() {
    print_progress "Installing dependencies" "..."
    if pip install --upgrade mkdocs mkdocs-material >/dev/null 2>&1; then
        print_progress "Installing dependencies" "success"
    else
        print_progress "Installing dependencies" "error"
        return 1
    fi
}

# Helper: Indent lines for YAML
indent() {
    local num_spaces="$1"
    local prefix=""
    for ((i=0; i<num_spaces; i++)); do
        prefix+=" "
    done
    sed "s/^/${prefix}/"
}

# Build subnav for a pipeline subdirectory
build_subnav() {
    local pipeline_dir="$1"
    local subdir="$2"
    local path="docs/${pipeline_dir}/${subdir}"
    
    # If directory doesn't exist OR is empty, return empty list notation
    if [ ! -d "$path" ] || [ -z "$(ls -A "$path")" ]; then
        echo "    - ${subdir}: []"  # Return empty list notation
        return 0
    fi
    
    echo "    - ${subdir}:"
    
    # First, explicitly check for and add the index.md file
    if [ -f "${path}/index.md" ]; then
        echo "      - index: ${pipeline_dir}/${subdir}/index.md"
        echo
    fi
    
    # Then add all other MD files (excluding index.md)
    while IFS= read -r mdfile; do
        local relpath="${mdfile#docs/}"
        local name="$(basename "$mdfile" .md)"
        if [ "$name" != "index" ]; then  # Skip index.md as we've already added it
            echo "      - ${name}: ${relpath}"
        fi
    done < <(find "$path" -maxdepth 1 -name '*.md' | sort)
}

# Build complete navigation structure
build_nav() {
    local top_dirs=()
    while IFS= read -r dir; do
        top_dirs+=("$(basename "$dir")")
    done < <(find docs -mindepth 1 -maxdepth 1 -type d | sort)
    
    echo "nav:"
    # Add root README as Home
    if [ -f "docs/README.md" ]; then
        echo "  - Home: README.md"
    fi
    
    # Process pipeline directories
    for pipeline_dir in "${top_dirs[@]}"; do
        echo "  - ${pipeline_dir}:"
        
        # First, explicitly check for and add the pipeline's README.md
        if [ -f "docs/${pipeline_dir}/README.md" ]; then
            echo "    - Overview: ${pipeline_dir}/README.md"
        fi
        
        # Then add any other top-level MD files (excluding README.md)
        if [ -n "$(find "docs/${pipeline_dir}" -maxdepth 1 -name '*.md' ! -name 'README.md')" ]; then
            while IFS= read -r mdfile; do
                local relpath="${mdfile#docs/}"
                local base="$(basename "$relpath" .md)"
                echo "    - ${base}: ${relpath}"
            done < <(find "docs/${pipeline_dir}" -maxdepth 1 -name '*.md' ! -name 'README.md' | sort)
        fi
        
        # Handle subfolders - secrets first, then other sections
        build_subnav "$pipeline_dir" "secrets"
        for sdir in groups jobs resources; do
            build_subnav "$pipeline_dir" "$sdir"
        done
    done
}

# Generate MkDocs site
generate_mkdocs_site() {
    print_progress "Building mkdocs.yml" "..."
    
    # Create mkdocs.yml
    cat <<EOF > mkdocs.yml
site_name: "Concourse Pipeline Reference Documentation"
theme:
  name: material
  custom_dir: overrides  # Tell Material to look here for partial overrides
  palette:
    - media: "(prefers-color-scheme: light)"
      scheme: default
      primary: "blue"
      accent: "blue"
      toggle:
        icon: material/weather-night
        name: Switch to dark mode
    - media: "(prefers-color-scheme: dark)"
      scheme: slate
      primary: "blue"
      accent: "blue"
      toggle:
        icon: material/weather-sunny
        name: Switch to light mode
$(build_nav)
plugins:
  - search
markdown_extensions:
  - toc:
      permalink: true
      toc_depth: 3
EOF

    print_progress "Building mkdocs.yml" "success"
    
    # Create footer override
    print_progress "Setting up theme overrides" "..."
    mkdir -p overrides/partials
    cat <<EOF > overrides/partials/footer.html

<footer class="md-footer">
  <div class="md-footer-meta md-typeset">
    <div class="md-footer-meta__inner md-grid">
      <div class="md-copyright">
        This documentation was generated by an AI
      </div>
    </div>
  </div>
</footer>

EOF
    print_progress "Setting up theme overrides" "success"

    # Build the site
    print_progress "Building MkDocs site" "..."
    if mkdocs build --quiet; then
        print_progress "Building MkDocs site" "success"
    else
        print_progress "Building MkDocs site" "error"
        return 1
    fi
}

# Serve MkDocs site
serve_mkdocs_site() {
    if [ ! -f "mkdocs.yml" ]; then
        echo "ERROR: mkdocs.yml not found. Run 'build-site' first."
        exit 1
    fi
    
    echo "Starting local server..."
    echo "View your documentation at: http://127.0.0.1:8000"
    mkdocs serve
}

# Main function
main() {
    local command="${1:-build}"
    
    case "$command" in
        build)
            install_deps
            generate_mkdocs_site
            ;;
        serve)
            serve_mkdocs_site
            ;;
        *)
            echo "Unknown command: $command"
            exit 1
            ;;
    esac
}

# If this script is run directly, show usage
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    echo "This script is meant to be sourced and used as part of ConcourseGPT"
    exit 1
fi
