#!/bin/bash
set -euo pipefail

# ============================================================================
# pr-review-production - Strict Production-Ready PR Review
# ============================================================================
# Strict PR review wrapper for production deployments with smart caching.
#
# Optimizations:
#   - Single data fetch (no redundant API calls)
#   - Uses cached data for multiple passes
#   - Passes data via stdin to analyze-pr-comments (avoids re-fetch)
#   - Smart auto-limiting for large PRs
# ============================================================================

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

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

Production-grade PR review with strict merge requirements.

Arguments:
  PR_NUMBER    PR number or GitHub URL

Options:
  --output-file FILE       Save review to file (default: {REPO}/tmp/pr-review-{PR}-production.md)
  --json                   Output in JSON format
  --limit NUM              Limit comments (for large PRs, default: auto-detect)
  --no-cache               Skip cache, fetch fresh data

Production Standards:
  🔴 CRITICAL - MUST be resolved (BLOCKING)
  🟠 MAJOR    - MUST be resolved (BLOCKING)
  🟡 MINOR    - MUST be resolved (BLOCKING)
  ⚪ NIT      - Optional (nice to have, NOT blocking)

Exit Codes:
  0 - Ready for production (all Critical/Major/Minor resolved)
  1 - Invalid arguments or missing dependencies
  2 - Not ready for production (unresolved Critical/Major/Minor issues)
  3 - GitHub API error

Examples:
  # Production review
  $(basename "$0") 22

  # Large PR with auto-limiting
  $(basename "$0") 88 --limit 50

  # JSON output for CI/CD
  $(basename "$0") 22 --json | tee production-review.json
EOF
    exit 1
}

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

    local script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    if [[ ! -x "$script_dir/fetch-pr-data" ]]; then
        missing_deps+=("fetch-pr-data (not found at $script_dir/fetch-pr-data)")
    fi

    if [[ ! -x "$script_dir/analyze-pr-comments" ]]; then
        missing_deps+=("analyze-pr-comments (not found at $script_dir/analyze-pr-comments)")
    fi

    if ! command -v jq &> /dev/null; then
        missing_deps+=("jq")
    fi

    if [ ${#missing_deps[@]} -ne 0 ]; then
        echo -e "${RED}✗${NC} Missing required dependencies:"
        for dep in "${missing_deps[@]}"; do
            echo "  - $dep"
        done
        exit 1
    fi
}

# Extract PR number
extract_pr_number() {
    local input="$1"
    if [[ "$input" =~ pull/([0-9]+) ]]; then
        echo "${BASH_REMATCH[1]}"
    elif [[ "$input" =~ ^[0-9]+$ ]]; then
        echo "$input"
    else
        echo -e "${RED}✗${NC} Invalid PR number: $input" >&2
        exit 1
    fi
}

# Format production markdown output
format_production_output() {
    local categorized="$1"
    local pr_number="$2"

    local critical_count=$(echo "$categorized" | jq '.summary.total_critical')
    local major_count=$(echo "$categorized" | jq '.summary.total_major')
    local minor_count=$(echo "$categorized" | jq '.summary.total_minor')
    local nit_count=$(echo "$categorized" | jq '.summary.total_nitpicks')

    cat << EOF
# PR #${pr_number} - Production Review

**Generated**: $(date '+%Y-%m-%d %H:%M:%S')
**Mode**: Production (Strict)

## Priority Breakdown

| Priority | Count | Status |
|----------|-------|--------|
| 🔴 CRITICAL | $critical_count | MUST resolve (BLOCKING) |
| 🟠 MAJOR | $major_count | MUST resolve (BLOCKING) |
| 🟡 MINOR | $minor_count | MUST resolve (BLOCKING) |
| ⚪ NIT | $nit_count | Optional (NOT blocking) |

## Production Readiness

EOF

    if [[ $critical_count -gt 0 ]] || [[ $major_count -gt 0 ]] || [[ $minor_count -gt 0 ]]; then
        echo "❌ **NOT READY FOR PRODUCTION**"
        echo ""
        [[ $critical_count -gt 0 ]] && echo "- ❌ $critical_count Critical issue(s) MUST be resolved"
        [[ $major_count -gt 0 ]] && echo "- ❌ $major_count Major issue(s) MUST be resolved"
        [[ $minor_count -gt 0 ]] && echo "- ⚠️  $minor_count Minor issue(s) MUST be resolved"
    else
        echo "✅ **READY FOR PRODUCTION**"
        echo ""
        echo "All critical, major, and minor issues have been resolved."
        [[ $nit_count -gt 0 ]] && echo "" && echo "⚪ $nit_count nit(s) remain but are optional."
    fi

    echo ""
    echo "---"
    echo ""

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

        case "$priority" in
            critical) echo "## 🔴 CRITICAL Issues ($count)" ;;
            major) echo "## 🟠 MAJOR Issues ($count)" ;;
            minor) echo "## 🟡 MINOR Issues ($count)" ;;
            nitpicks) echo "## ⚪ NIT / Nice to Have ($count)" ;;
        esac

        echo ""

        local issues=$(echo "$categorized" | jq -c ".categorized_issues.${priority}[]")
        local issue_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' | head -c 150)
            local file=$(echo "$issue" | jq -r '.file // "N/A"')
            local status=$(echo "$issue" | jq -r '.status // "unknown"')

            echo "### ${priority^^}-${issue_num}: $author"
            [[ "$file" != "N/A" ]] && [[ "$file" != "null" ]] && echo "**File**: \`$file\`"
            echo "**Status**: $status"
            echo ""
            echo "$title..."
            echo ""
            echo "---"
            echo ""

            ((issue_num++))
        done <<< "$issues"
    done
}

# Main function
main() {
    local pr_number=""
    local output_file=""
    local json_output=false
    local limit=""
    local use_cache=true

    # Parse arguments
    while [[ $# -gt 0 ]]; do
        case $1 in
            --output-file)
                output_file="$2"
                shift 2
                ;;
            --json)
                json_output=true
                shift
                ;;
            --limit)
                limit="$2"
                shift 2
                ;;
            --no-cache)
                use_cache=false
                shift
                ;;
            -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

    check_dependencies

    pr_number=$(extract_pr_number "$pr_number")

    echo -e "${MAGENTA}╔════════════════════════════════════════════════════════════╗${NC}" >&2
    echo -e "${MAGENTA}║           PR REVIEW - PRODUCTION MODE                      ║${NC}" >&2
    echo -e "${MAGENTA}╚════════════════════════════════════════════════════════════╝${NC}" >&2
    echo "" >&2
    echo -e "${BLUE}[PRODUCTION]${NC} Running strict production review for PR #${pr_number}..." >&2
    echo "" >&2

    # Determine output file
    if [[ -z "$output_file" ]]; then
        local script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
        local repo_root="$(cd "$script_dir/../.." && pwd)"
        mkdir -p "$repo_root/tmp"
        output_file="$repo_root/tmp/pr-review-${pr_number}-production.md"
    fi

    # Fetch PR data ONCE (with caching)
    echo -e "${BLUE}[PRODUCTION]${NC} Fetching PR data (cached)..." >&2
    local fetch_args=("$pr_number")
    [[ -n "$limit" ]] && fetch_args+=("--limit" "$limit")
    [[ "$use_cache" == false ]] && fetch_args+=("--no-cache")

    local pr_data
    local script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    pr_data=$("$script_dir/fetch-pr-data" "${fetch_args[@]}") || {
        echo -e "${RED}✗${NC} Failed to fetch PR data" >&2
        exit 3
    }

    echo -e "${GREEN}✓${NC} PR data fetched" >&2

    # Check if we need auto-limiting for large PRs
    local total_comments=$(echo "$pr_data" | jq '.summary.total_all_comments')
    if [[ $total_comments -gt 1000 ]] && [[ -z "$limit" ]]; then
        echo -e "${YELLOW}⚠${NC} Large PR detected ($total_comments comments)" >&2
        echo -e "${YELLOW}⚠${NC} Re-fetching with auto-limit of 50 recent + all bot comments..." >&2
        pr_data=$("$script_dir/fetch-pr-data" "$pr_number" --limit 50 --no-cache) || {
            echo -e "${RED}✗${NC} Failed to re-fetch with limit" >&2
            exit 3
        }
        total_comments=$(echo "$pr_data" | jq '.summary.total_all_comments')
        echo -e "${GREEN}✓${NC} Limited to $total_comments comments" >&2
    fi

    # Analyze comments (categorization) - uses pr_data from stdin
    echo -e "${BLUE}[PRODUCTION]${NC} Analyzing comments..." >&2
    local categorized
    categorized=$(echo "$pr_data" | "$script_dir/analyze-pr-comments") || {
        echo -e "${RED}✗${NC} Failed to analyze comments" >&2
        exit 3
    }

    echo -e "${GREEN}✓${NC} Analysis complete" >&2

    # Extract counts
    local critical_count=$(echo "$categorized" | jq '.summary.total_critical')
    local major_count=$(echo "$categorized" | jq '.summary.total_major')
    local minor_count=$(echo "$categorized" | jq '.summary.total_minor')
    local nit_count=$(echo "$categorized" | jq '.summary.total_nitpicks')

    # Production summary (to stderr)
    echo "" >&2
    echo -e "${MAGENTA}═══════════════════════════════════════════════════════════${NC}" >&2
    echo -e "${MAGENTA}   PRODUCTION REVIEW SUMMARY${NC}" >&2
    echo -e "${MAGENTA}═══════════════════════════════════════════════════════════${NC}" >&2
    echo "" >&2
    echo "  🔴 CRITICAL (MUST resolve): $critical_count" >&2
    echo "  🟠 MAJOR    (MUST resolve): $major_count" >&2
    echo "  🟡 MINOR    (MUST resolve): $minor_count" >&2
    echo "  ⚪ NIT      (optional):      $nit_count" >&2
    echo "" >&2
    echo -e "${MAGENTA}═══════════════════════════════════════════════════════════${NC}" >&2
    echo "" >&2

    # Generate output
    if [[ "$json_output" == true ]]; then
        echo "$categorized" | tee "$output_file"
    else
        format_production_output "$categorized" "$pr_number" | tee "$output_file"
    fi

    echo "" >&2
    echo -e "${GREEN}✓${NC} Review saved to: $output_file" >&2
    echo "" >&2

    # Production readiness check
    if [[ $critical_count -gt 0 ]] || [[ $major_count -gt 0 ]] || [[ $minor_count -gt 0 ]]; then
        echo -e "${RED}╔════════════════════════════════════════════════════════════╗${NC}" >&2
        echo -e "${RED}║  ❌ NOT READY FOR PRODUCTION                               ║${NC}" >&2
        echo -e "${RED}╚════════════════════════════════════════════════════════════╝${NC}" >&2
        echo "" >&2
        [[ $critical_count -gt 0 ]] && echo -e "${RED}  ✗ $critical_count CRITICAL issue(s) MUST be resolved${NC}" >&2
        [[ $major_count -gt 0 ]] && echo -e "${RED}  ✗ $major_count MAJOR issue(s) MUST be resolved${NC}" >&2
        [[ $minor_count -gt 0 ]] && echo -e "${YELLOW}  ⚠  $minor_count MINOR issue(s) MUST be resolved${NC}" >&2
        echo "" >&2
        exit 2
    else
        echo -e "${GREEN}╔════════════════════════════════════════════════════════════╗${NC}" >&2
        echo -e "${GREEN}║  ✅ READY FOR PRODUCTION                                   ║${NC}" >&2
        echo -e "${GREEN}╚════════════════════════════════════════════════════════════╝${NC}" >&2
        echo "" >&2
        echo -e "${GREEN}  ✓ All Critical, Major, and Minor issues resolved${NC}" >&2
        [[ $nit_count -gt 0 ]] && echo -e "${BLUE}  ℹ  $nit_count nit(s) remain but are optional${NC}" >&2
        echo "" >&2
        exit 0
    fi
}

main "$@"
