# ======================================================================
# Rxiv-Maker Local Testing Dockerfile
# ======================================================================
# This Dockerfile extends the base image with local source code for testing.
# It mirrors the GitHub Actions workflow while optimizing for local development.
# ======================================================================

ARG BASE_IMAGE=henriqueslab/rxiv-maker-base:latest
FROM ${BASE_IMAGE}

# Set up build arguments
ARG BUILD_DATE
ARG VCS_REF
ARG VERSION

# Add metadata
LABEL maintainer="Rxiv-Maker Project"
LABEL description="Local testing image for Rxiv-Maker with source code"
LABEL version="local-test"
LABEL org.opencontainers.image.created="${BUILD_DATE}"
LABEL org.opencontainers.image.revision="${VCS_REF}"
LABEL org.opencontainers.image.version="${VERSION}"
LABEL org.opencontainers.image.source="https://github.com/henriqueslab/rxiv-maker"
LABEL org.opencontainers.image.description="Local testing environment for Rxiv-Maker"

# Ensure we're in the right directory
WORKDIR /workspace

# Copy source code (excluding what's in .dockerignore)
COPY . /workspace/

# Set proper permissions for workspace
RUN chown -R rxivmaker:rxivmaker /workspace \
    && chmod -R 755 /workspace

# Install Python dependencies from local source (stay as root to access uv)
RUN echo "Installing Python dependencies from local source..." \
    && cd /workspace \
    && if [ -f "uv.lock" ]; then \
        echo "Using uv.lock for installation..."; \
        uv sync --no-dev; \
    elif [ -f "pyproject.toml" ]; then \
        echo "Using pyproject.toml for installation..."; \
        uv pip install --system -e .; \
    else \
        echo "No pyproject.toml found, skipping Python dependency installation"; \
    fi

# Make uv available globally by copying it to /usr/local/bin
RUN cp /root/.local/bin/uv /usr/local/bin/uv \
    && chmod +x /usr/local/bin/uv

# Verify installation (as root)
RUN echo "=== Verifying Python installation ===" \
    && python3 --version \
    && python3 -c "import sys; print(f'Python path: {sys.path}')" \
    && if python3 -c "import sys; sys.path.insert(0, '/workspace/src'); import py" 2>/dev/null; then \
        echo "✅ rxiv-maker package is importable"; \
    else \
        echo "⚠️  rxiv-maker package import failed - will try direct execution"; \
    fi

# Create the test script that mirrors GitHub Actions workflow (as root)
RUN cat > /usr/local/bin/test-script.sh << 'EOF'
#!/bin/bash

# ======================================================================
# Test Script (runs inside container)
# ======================================================================
# This script runs inside the Docker container and mirrors the exact
# steps from the GitHub Actions workflow.
# ======================================================================

set -e

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

print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# Function to configure Git (mirrors GitHub Actions)
configure_git() {
    print_step "Configuring Git..."
    git config --global --add safe.directory /workspace
    git config --global user.name "local-test"
    git config --global user.email "test@rxiv-maker.local"
    print_success "Git configured"
}

# Function to check environment (mirrors GitHub Actions)
check_environment() {
    print_step "Checking environment..."
    echo "=================================================="
    echo "📋 Build Configuration:"
    echo "  - Manuscript Path: ${MANUSCRIPT_PATH:-MANUSCRIPT}"
    echo "  - Python Version: $(python3 --version)"
    echo "  - LaTeX Version: $(pdflatex --version | head -1)"
    echo "  - Current Directory: $(pwd)"
    echo "  - User: $(whoami)"
    echo "  - Available Memory: $(free -h | grep '^Mem:' | awk '{print $2}' | tr -d '\n') total, $(free -h | grep '^Mem:' | awk '{print $7}' | tr -d '\n') available"
    echo "  - Available Space: $(df -h . | tail -1 | awk '{print $4}') free"
    echo "=================================================="
}

# Function to install Python dependencies (mirrors GitHub Actions)
install_dependencies() {
    print_step "Installing Python dependencies..."

    # Set up environment
    export TEXMFVAR=/tmp/texmf-var
    export R_LIBS_USER=/home/rxivmaker/.R/library

    # Create necessary directories
    mkdir -p /tmp/texmf-var output

    # Ensure cache directories have proper permissions (in case of volume mounts)
    mkdir -p /home/rxivmaker/.cache /home/rxivmaker/.R/library

    # Install Python dependencies using make setup
    make setup

    print_success "Python dependencies installed"
}

# Function to check manuscript directory (mirrors GitHub Actions)
check_manuscript() {
    local manuscript_path="${MANUSCRIPT_PATH:-MANUSCRIPT}"

    print_step "Checking manuscript directory..."
    if [[ -d "$manuscript_path" ]]; then
        print_success "Manuscript directory exists: $manuscript_path"
        print_info "Contents:"
        ls -la "$manuscript_path" | sed 's/^/  /'
    else
        print_error "Manuscript directory not found: $manuscript_path"
        print_info "Available directories:"
        ls -la . | grep '^d' | sed 's/^/  /'
        exit 1
    fi
}

# Function to check Python dependencies (mirrors GitHub Actions)
check_python_deps() {
    print_step "Checking Python dependencies..."
    python3 -c "import sys; print(f'  - Python executable: {sys.executable}')"
    python3 -c "import numpy; print(f'  - NumPy version: {numpy.__version__}')" || echo "  ❌ NumPy not available"
    python3 -c "import matplotlib; print(f'  - Matplotlib version: {matplotlib.__version__}')" || echo "  ❌ Matplotlib not available"
    python3 -c "import yaml; print(f'  - PyYAML available')" || echo "  ❌ PyYAML not available"
    print_success "Python dependencies check completed"
}

# Function to run PDF generation (mirrors GitHub Actions)
generate_pdf() {
    print_step "Generating PDF..."

    # Set environment variables
    export MANUSCRIPT_PATH="${MANUSCRIPT_PATH:-MANUSCRIPT}"
    export TEXMFVAR=/tmp/texmf-var
    export FORCE_FIGURES="${FORCE_FIGURES:-true}"
    export R_LIBS_USER=/home/rxivmaker/.R/library

    print_info "Environment variables set:"
    echo "  - MANUSCRIPT_PATH: $MANUSCRIPT_PATH"
    echo "  - TEXMFVAR: $TEXMFVAR"
    echo "  - FORCE_FIGURES: $FORCE_FIGURES"
    echo "  - R_LIBS_USER: $R_LIBS_USER"

    # Clean figures first
    print_info "Step 1: Cleaning figures..."
    make clean-figures 2>&1 | sed 's/^/  /' || print_warning "clean-figures failed or not available"

    # Generate PDF
    print_info "Step 2: Generating PDF..."
    echo "  Command: make pdf"
    echo "  Working directory: $(pwd)"
    echo "  Start time: $(date)"

    # Run make pdf with detailed output
    set -o pipefail
    make pdf 2>&1 | tee /tmp/make_pdf_output.log | sed 's/^/  /'
    MAKE_EXIT_CODE=$?

    echo "  End time: $(date)"
    echo "  Exit code: $MAKE_EXIT_CODE"

    if [[ $MAKE_EXIT_CODE -ne 0 ]]; then
        print_error "make pdf failed with exit code $MAKE_EXIT_CODE"
        print_info "Last 50 lines of output:"
        tail -50 /tmp/make_pdf_output.log | sed 's/^/  /'
        return $MAKE_EXIT_CODE
    else
        print_success "make pdf completed successfully"
        return 0
    fi
}

# Function to check PDF generation (mirrors GitHub Actions)
check_pdf() {
    print_step "Checking PDF generation results..."

    local manuscript_path="${MANUSCRIPT_PATH:-MANUSCRIPT}"
    local expected_pdf="output/${manuscript_path}.pdf"

    # Check output directory
    print_info "Output directory contents:"
    if [[ -d "output" ]]; then
        ls -la output/ | sed 's/^/  /'
    else
        print_error "Output directory not found"
        return 1
    fi

    # Check for expected PDF
    print_info "Looking for PDF at: $expected_pdf"

    if [[ -f "$expected_pdf" ]]; then
        print_success "PDF generated successfully!"
        print_info "PDF Details:"
        ls -la "$expected_pdf" | sed 's/^/  /'
        file "$expected_pdf" | sed 's/^/  /'
        print_info "PDF size: $(du -h "$expected_pdf" | cut -f1)"
        return 0
    else
        print_error "PDF not found at expected location"
        print_info "Searching for any PDF files..."
        find . -name "*.pdf" -type f 2>/dev/null | sed 's/^/  /' || echo "  No PDF files found anywhere"

        print_info "All output files:"
        find output/ -type f 2>/dev/null | sed 's/^/  /' || echo "  No files found in output/"

        print_info "LaTeX log files analysis:"
        find output/ -name "*.log" -exec echo "  === {} ===" \; -exec tail -20 {} \; 2>/dev/null || echo "  No log files found"

        return 1
    fi
}

# Function to collect debug information
collect_debug_info() {
    print_step "Collecting debug information..."

    echo "=== System Information ==="
    uname -a
    free -h
    df -h

    echo "=== Python Environment ==="
    python3 --version
    python3 -c "import sys; print('Python path:', sys.path)"

    echo "=== LaTeX Environment ==="
    which pdflatex
    which bibtex || echo "bibtex not found"

    echo "=== Environment Variables ==="
    env | grep -E "^(PATH|MANUSCRIPT_PATH|TEXMF|R_LIBS)" || echo "No relevant environment variables found"

    echo "=== Build Files ==="
    find . -name "*.pdf" -o -name "*.log" -o -name "*.aux" | head -20
}

# Main execution
main() {
    print_info "=================================================="
    print_info "🐳 Running Rxiv-Maker Test Inside Container"
    print_info "=================================================="

    # Execute workflow steps (mirrors GitHub Actions)
    configure_git
    check_environment
    install_dependencies
    check_manuscript
    check_python_deps

    # Generate PDF
    if generate_pdf; then
        # Check results
        if check_pdf; then
            print_success "✅ Test completed successfully!"
            exit 0
        else
            print_error "❌ PDF validation failed"
            collect_debug_info
            exit 1
        fi
    else
        print_error "❌ PDF generation failed"
        collect_debug_info
        exit 1
    fi
}

# Run main function
main "$@"
EOF

# Make the script executable
RUN chmod +x /usr/local/bin/test-script.sh

# Create additional debugging tools
RUN cat > /usr/local/bin/debug-rxiv-maker << 'EOF'
#!/bin/bash
echo "=== Rxiv-Maker Debug Information ==="
echo "Working directory: $(pwd)"
echo "User: $(whoami)"
echo "Python version: $(python3 --version)"
echo "LaTeX version: $(pdflatex --version | head -1)"
echo "Available make targets:"
make help 2>/dev/null || echo "Make help not available"
echo "Directory contents:"
ls -la
echo "Python path:"
python3 -c "import sys; print('\n'.join(sys.path))"
EOF

RUN chmod +x /usr/local/bin/debug-rxiv-maker

# Final permissions setup
RUN chown -R rxivmaker:rxivmaker /workspace \
    && chmod -R 755 /workspace \
    && chown -R rxivmaker:rxivmaker /home/rxivmaker \
    && mkdir -p /home/rxivmaker/.cache /home/rxivmaker/.R/library \
    && chown -R rxivmaker:rxivmaker /home/rxivmaker/.cache /home/rxivmaker/.R/library

# Switch to non-root user for security
USER rxivmaker

# Set default working directory
WORKDIR /workspace

# Default command - run the test script
CMD ["/usr/local/bin/test-script.sh"]
