#!/bin/bash
set -euo pipefail

# ============================================================================
# PR Issue Collator - Automated Priority-Based Issue Aggregation
# ============================================================================
# Fetches, parses, categorizes, and prioritizes all PR review issues
# in a single automated command.
#
# This is a thin bash wrapper that delegates to the Python implementation
# (collate_issues.py) for robust text processing. The Python version uses
# Pydantic models for type safety and avoids memory issues with large PRs.
#
# Features:
#   - Single command execution: collate-issues <PR#>
#   - Automatic caching via fetch-pr-data
#   - Smart categorization by severity (Critical > Major > Minor > Nit)
#   - Deduplication of similar issues
#   - Token-efficient output (< 2000 tokens)
#   - Ready for agent consumption (no parsing needed)
#   - Resolution detection via GitHub review threads
# ============================================================================

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PYTHON_SCRIPT="$SCRIPT_DIR/collate_issues.py"
SHOW_STATS=false
INCLUDE_NITPICKS=false
PARALLEL_SOLVE_FORMAT=false
HIDE_RESOLVED=false
SHOW_RESOLVED_ONLY=false

# Usage
usage() {
    cat << 'EOF'
Usage: collate-issues <PR_NUMBER> [OPTIONS]

Automated PR issue collation and prioritization.

Arguments:
  PR_NUMBER    PR number (e.g., 33) or full GitHub URL

Options:
  --include-nitpicks       Include nitpick issues in output (default: excluded)
  --parallel-solve-format  Output in format ready for /parallel-solve command
  --hide-resolved          Hide issues that have been resolved on GitHub
                           (uses GitHub's native thread resolution status)
  --show-resolved-only     Only show resolved issues (inverse of --hide-resolved)
  --stats                  Show statistics summary
  --help                   Show this help message

Output:
  Clean prioritized list of all PR issues by severity:
    CRITICAL - Must address before merge
    MAJOR    - Must address before merge
    MINOR    - Must address before merge
    NITPICK  - Optional improvements (only with --include-nitpicks)
    UNMATCHED - Comments not matching any pattern (review manually)

  Resolution indicators (when showing resolved issues):
    [RESOLVED] - Issue thread marked as resolved on GitHub
    [OUTDATED] - Code has changed since the comment was made

Examples:
  collate-issues 33                      # Critical, Major, Minor only
  collate-issues 33 --include-nitpicks   # Include nitpicks too
  collate-issues 33 --hide-resolved      # Hide resolved GitHub threads
  collate-issues 33 --show-resolved-only # Show only resolved issues
  collate-issues 33 --stats              # With statistics summary
  collate-issues 33 --parallel-solve-format  # For /parallel-solve command

Exit codes:
  0 - Success
  1 - Missing arguments or dependencies
  2 - PR data fetch failed or processing error
EOF
    exit 1
}

# Determine Python executable (prefer poetry if available)
get_python_executable() {
    # Find project root by searching upward for pyproject.toml
    local current_dir="$SCRIPT_DIR"
    local project_root=""

    # Search up to 5 levels up for pyproject.toml
    for i in {1..5}; do
        if [[ -f "$current_dir/pyproject.toml" ]]; then
            project_root="$current_dir"
            break
        fi
        current_dir="$(dirname "$current_dir")"
    done

    # If found pyproject.toml, try Poetry from that directory
    if [[ -n "$project_root" ]] && command -v poetry &> /dev/null; then
        local poetry_python
        poetry_python=$(cd "$project_root" && poetry env info --executable 2>/dev/null)
        if [[ -n "$poetry_python" && -x "$poetry_python" ]]; then
            echo "$poetry_python"
            return
        fi
    fi

    # Fallback: Try OMNICLAUDE_PATH or common container/user paths
    # This handles case where script is called via plugin cache
    # but Poetry venv is only active in the container/workspace
    # NOTE: Uses generic patterns only, no user-specific paths
    local omniclaude_paths=(
        "${OMNICLAUDE_PATH:-}"
        "${PROJECT_ROOT:-}"
        "/workspace/omniclaude"
        "${HOME}/Code/omniclaude"
    )

    for omniclaude_path in "${omniclaude_paths[@]}"; do
        if [[ -n "$omniclaude_path" && -f "$omniclaude_path/pyproject.toml" ]] && command -v poetry &> /dev/null; then
            local poetry_python
            poetry_python=$(cd "$omniclaude_path" && poetry env info --executable 2>/dev/null)
            if [[ -n "$poetry_python" && -x "$poetry_python" ]]; then
                echo "$poetry_python"
                return
            fi
        fi
    done

    # Final fallback to system python3
    if command -v python3 &> /dev/null; then
        echo "python3"
        return
    fi

    echo ""
}

# Check dependencies
check_dependencies() {
    local missing_deps=()

    if [[ ! -f "$PYTHON_SCRIPT" ]]; then
        missing_deps+=("collate_issues.py (Python implementation not found)")
    fi

    PYTHON_EXEC=$(get_python_executable)
    if [[ -z "$PYTHON_EXEC" ]]; then
        missing_deps+=("python3 (neither poetry env nor system python3 found)")
    fi

    if [ ${#missing_deps[@]} -ne 0 ]; then
        echo "ERROR: Missing required dependencies:" >&2
        for dep in "${missing_deps[@]}"; do
            echo "  - $dep" >&2
        done
        exit 1
    fi
}

# Validate PR input (handles URLs or numbers)
validate_pr_input() {
    local input="$1"

    # If it's a URL, validate and pass through
    if [[ "$input" =~ github\.com/.*/pull/([0-9]+) ]]; then
        echo "$input"  # Pass full URL to preserve repo context
    # If it's already a number, use it
    elif [[ "$input" =~ ^[0-9]+$ ]]; then
        echo "$input"
    else
        echo "ERROR: Invalid PR number or URL: $input" >&2
        exit 1
    fi
}

# Main
main() {
    local pr_number=""
    local python_args=()

    # Parse arguments
    while [[ $# -gt 0 ]]; do
        case $1 in
            --include-nitpicks)
                INCLUDE_NITPICKS=true
                python_args+=("--include-nitpicks")
                shift
                ;;
            --parallel-solve-format)
                PARALLEL_SOLVE_FORMAT=true
                python_args+=("--parallel-solve-format")
                shift
                ;;
            --hide-resolved)
                HIDE_RESOLVED=true
                python_args+=("--hide-resolved")
                shift
                ;;
            --show-resolved-only)
                SHOW_RESOLVED_ONLY=true
                python_args+=("--show-resolved-only")
                shift
                ;;
            --stats)
                SHOW_STATS=true
                python_args+=("--stats")
                shift
                ;;
            -h|--help)
                usage
                ;;
            # Legacy options (silently ignored for backward compatibility)
            --include-praise|--unfinished-only)
                shift
                ;;
            *)
                if [[ -z "$pr_number" ]]; then
                    pr_number="$1"
                else
                    echo "ERROR: Unknown argument: $1" >&2
                    usage
                fi
                shift
                ;;
        esac
    done

    # Validate conflicting options
    if [[ "$HIDE_RESOLVED" == "true" ]] && [[ "$SHOW_RESOLVED_ONLY" == "true" ]]; then
        echo "ERROR: Cannot use both --hide-resolved and --show-resolved-only" >&2
        exit 1
    fi

    if [[ -z "$pr_number" ]]; then
        usage
    fi

    check_dependencies

    pr_input=$(validate_pr_input "$pr_number")

    # Call the Python implementation
    # Pass the original input (URL or number) so Python can preserve repo context
    exec "$PYTHON_EXEC" "$PYTHON_SCRIPT" "$pr_input" "${python_args[@]}"
}

main "$@"
