#!/bin/bash
set -euo pipefail

# ============================================================================
# PR Dev Review Wrapper
# ============================================================================
# Simplified wrapper for development-focused PR reviews.
# Automatically fetches PR data and categorizes issues by dev priorities.
#
# Usage:
#   pr-dev-review-wrapper 22              # Review PR #22
#   pr-dev-review-wrapper 22 --json       # JSON output
#   pr-dev-review-wrapper 22 --save FILE  # Save to file
# ============================================================================

# Get repo root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
mkdir -p "$REPO_ROOT/tmp"

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

usage() {
    cat << EOF
Usage: $(basename "$0") <PR_NUMBER> [OPTIONS]

Development-focused PR review (CRITICAL/MAJOR/MINOR only, skips nits).

Arguments:
  PR_NUMBER    PR number or GitHub URL

Options:
  --json       Output JSON only
  --save FILE  Save output to specific file
  --help, -h   Show this help

Priority Focus (Development):
  🔴 CRITICAL - MUST FIX (security, bugs, test failures)
  🟠 MAJOR    - SHOULD FIX (consistency, architecture, error handling)
  🟡 MINOR    - FIX NOW (docs, tests, unused code)
  ⚪ NITPICKS - SKIP (defer to release review)

Examples:
  # Quick dev review
  $(basename "$0") 22

  # Save to file
  $(basename "$0") 22 --save ./dev-review.md

  # JSON output
  $(basename "$0") 22 --json > pr22-dev.json
EOF
    exit 0
}

# Parse arguments
PR_NUMBER=""
JSON_MODE=false
SAVE_FILE=""

while [[ $# -gt 0 ]]; do
    case $1 in
        --json)
            JSON_MODE=true
            shift
            ;;
        --save)
            if [[ $# -lt 2 ]]; then
                echo "Error: --save requires a file path argument" >&2
                echo "Usage: $(basename "$0") <PR_NUMBER> --save <FILE_PATH>" >&2
                exit 1
            fi
            SAVE_FILE="$2"
            shift 2
            ;;
        -h|--help)
            usage
            ;;
        *)
            if [[ -z "$PR_NUMBER" ]]; then
                PR_NUMBER="$1"
            else
                echo "Error: Unknown argument: $1"
                usage
            fi
            shift
            ;;
    esac
done

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

# Extract PR number from URL if needed
if [[ "$PR_NUMBER" =~ pull/([0-9]+) ]]; then
    PR_NUMBER="${BASH_REMATCH[1]}"
fi

# Determine output file
if [[ -z "$SAVE_FILE" ]]; then
    SAVE_FILE="$REPO_ROOT/tmp/pr-dev-review-${PR_NUMBER}.md"
fi

echo -e "${BLUE}[DEV-REVIEW]${NC} Fetching PR #${PR_NUMBER}..." >&2

# Fetch PR data
PR_DATA=$("$SCRIPT_DIR/fetch-pr-data" "$PR_NUMBER") || {
    echo -e "${RED}✗${NC} Failed to fetch PR data" >&2
    exit 1
}

echo -e "${GREEN}✓${NC} PR data fetched" >&2
echo -e "${BLUE}[DEV-REVIEW]${NC} Analyzing comments..." >&2

# Analyze using analyze-pr-comments (pre-categorized, no jq parsing needed)
ANALYSIS=$(echo "$PR_DATA" | "$SCRIPT_DIR/analyze-pr-comments" 2>/dev/null) || {
    echo -e "${RED}✗${NC} Failed to analyze PR comments" >&2
    exit 1
}

# Transform analysis to dev-focused format (skip nits)
categorize_dev_from_analysis() {
    local analysis="$1"

    # Extract categorized issues (skip nitpicks for dev review)
    jq '{
        critical: .categorized_issues.critical,
        major: .categorized_issues.major,
        minor: .categorized_issues.minor,
        summary: {
            critical_count: (.categorized_issues.critical | length),
            major_count: (.categorized_issues.major | length),
            minor_count: (.categorized_issues.minor | length),
            total: (
                (.categorized_issues.critical | length) +
                (.categorized_issues.major | length) +
                (.categorized_issues.minor | length)
            )
        }
    }' <<< "$analysis"
}

# Format as markdown
format_dev_markdown() {
    local categorized="$1"
    local pr_number="$2"

    cat << EOF
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
PR DEV REVIEW - Development Priority Issues
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

PR #${pr_number}
Generated: $(date '+%Y-%m-%d %H:%M:%S')

📊 SUMMARY:
- 🔴 Critical: $(echo "$categorized" | jq '.summary.critical_count')
- 🟠 Major: $(echo "$categorized" | jq '.summary.major_count')
- 🟡 Minor: $(echo "$categorized" | jq '.summary.minor_count')
- Total actionable: $(echo "$categorized" | jq '.summary.total')

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
EOF

    # Output each priority
    for priority in "critical" "major" "minor"; do
        local count=$(echo "$categorized" | jq ".summary.${priority}_count")
        [[ $count -eq 0 ]] && continue

        case "$priority" in
            critical) echo "🔴 CRITICAL ISSUES ($count) - Must fix before merge:" ;;
            major) echo "🟠 MAJOR ISSUES ($count) - Fix to prevent tech debt:" ;;
            minor) echo "🟡 MINOR ISSUES ($count) - Fix now to maintain quality:" ;;
        esac
        echo ""

        local issues=$(echo "$categorized" | jq -c ".${priority}[]")
        local num=1

        while IFS= read -r issue; do
            [[ -z "$issue" ]] && continue

            local author=$(echo "$issue" | jq -r '.author')
            local title=$(echo "$issue" | jq -r '.title // (.description | .[0:100])')
            local file=$(echo "$issue" | jq -r '.file // "N/A"')
            local status=$(echo "$issue" | jq -r '.status // "unknown"')

            # Status indicator
            local status_icon=""
            case "$status" in
                unaddressed) status_icon="❌" ;;
                potentially_addressed) status_icon="✓" ;;
                *) status_icon="?" ;;
            esac

            echo "$num. [$file] $author $status_icon"
            echo "   $title"
            echo ""

            ((num++))
        done <<< "$issues"

        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo ""
    done
}

# Transform analysis to dev-focused format
CATEGORIZED=$(categorize_dev_from_analysis "$ANALYSIS")

echo -e "${GREEN}✓${NC} Issues categorized" >&2

# Generate output
if [[ "$JSON_MODE" == true ]]; then
    echo "$CATEGORIZED" | tee "$SAVE_FILE"
else
    format_dev_markdown "$CATEGORIZED" "$PR_NUMBER" | tee "$SAVE_FILE"
fi

echo "" >&2
echo -e "${GREEN}✓${NC} Dev review saved to: $SAVE_FILE" >&2
