#!/bin/bash

# Generate diff from origin/main
echo "Generating diff from origin/main..."

# Capture diff content directly into variable
DIFF_CONTENT=$(git diff origin/main -- . ':(exclude)package-lock.json' ':(exclude)**/package-lock.json' ':(exclude)yarn.lock' ':(exclude)**/yarn.lock' ':(exclude)pnpm-lock.yaml' ':(exclude)**/pnpm-lock.yaml' ':(exclude)ai-prompt-context/actions/embeddings' ':(exclude)test-results/**' ':(exclude)playwright-report/**')

if [ -z "$DIFF_CONTENT" ]; then
    echo "❌ No changes found compared to origin/main"
    exit 1
fi

# Get list of changed files
CHANGED_FILES=$(git diff --name-only origin/main -- . ':(exclude)package-lock.json' ':(exclude)**/package-lock.json' ':(exclude)yarn.lock' ':(exclude)**/yarn.lock' ':(exclude)pnpm-lock.yaml' ':(exclude)**/pnpm-lock.yaml' ':(exclude)ai-prompt-context/actions/embeddings' ':(exclude)test-results/**' ':(exclude)playwright-report/**')
FILES_COUNT=$(echo "$CHANGED_FILES" | wc -l | tr -d ' ')

# Categorize files for smarter review
SRC_FILES=$(echo "$CHANGED_FILES" | grep -v -E '\.(test|spec)\.(ts|tsx|js)$' | grep -v '__mocks__' | grep -v 'fixtures')
TEST_FILES=$(echo "$CHANGED_FILES" | grep -E '\.(test|spec)\.(ts|tsx|js)$')

# Check diff size and warn if large
DIFF_LINES=$(echo "$DIFF_CONTENT" | wc -l | tr -d ' ')

echo "✅ Diff generated successfully"
echo "✅ Found $FILES_COUNT changed file(s) ($DIFF_LINES lines)"
echo ""

if [ "$DIFF_LINES" -gt 2000 ]; then
    echo "⚠️  Large diff ($DIFF_LINES lines). Consider reviewing in chunks for better results."
    echo ""
fi

# Try to get PR metadata if available (requires gh CLI)
PR_TITLE=""
PR_BODY=""
if command -v gh >/dev/null 2>&1; then
    PR_TITLE=$(gh pr view --json title -q .title 2>/dev/null || echo "")
    PR_BODY=$(gh pr view --json body -q .body 2>/dev/null || echo "")
fi

# Build PR metadata section if available
PR_METADATA=""
if [ -n "$PR_TITLE" ]; then
    PR_METADATA="## PR Metadata
**Title**: $PR_TITLE
**Description**: $PR_BODY

"
fi

# The prompt to copy with embedded diff content
PROMPT="You are an expert code reviewer for a TypeScript/React insurance platform (Root Insurance). Below is a git diff comparing a feature branch to origin/main.

## Project Context
- **Stack**: TypeScript, React, Node.js, PostgreSQL
- **Frontend**: root-web (React SPA with insurance policy management)
- **Backend**: root-platform (Node.js API with insurance business logic)
- **Testing**: Playwright for e2e, Jest for unit tests
- **Domain**: Insurance platform - stability and correctness are critical
- **CLI**: Root Platform CLI

${PR_METADATA}## Your Task

### 0. High-Level Summary
In 2-3 sentences, describe:
- **Product impact**: What does this change deliver for users or customers?
- **Engineering approach**: Key patterns or architectural decisions.

### 1. Critical Review Focus
Prioritize your review on these areas (in order of importance):

**🐛 Bugs & Logic Errors** (HIGHEST PRIORITY)
- Off-by-one errors, null/undefined handling, race conditions
- Incorrect conditional logic, missing edge cases
- Type mismatches, incorrect API contract usage

**💥 Breaking Changes** (CRITICAL)
- Backward compatibility issues
- API contract changes that affect consumers
- Database schema changes without migrations
- Props/interface changes that break existing usage

**🔒 Security Issues**
- Input validation gaps, injection vulnerabilities
- Authentication/authorization bypasses
- Sensitive data exposure in logs or responses

**⚡ Performance Regressions**
- N+1 queries, unnecessary re-renders
- Missing memoization on expensive operations
- Unbounded data fetching

**🧪 Test Coverage Gaps**
- New code paths without tests
- Modified logic without updated tests
- Edge cases not covered

### 2. Review Guidelines
- **Only report issues you're confident about (>80% certainty)**
- **Don't flag stylistic preferences** if the code follows existing patterns in the codebase
- **If you see an unfamiliar pattern**, assume it may be a project convention before flagging
- **Focus on functional correctness** over cosmetic improvements
- **Skip categories with no relevant changes** - don't force issues where none exist

### 3. Issue Format
For each real issue found:

📍 \`path/to/file.ts:line-range\`
**[🔴 Critical | 🟠 Major | 🟡 Minor | 🔵 Enhancement]** Brief title

→ **Problem**: What's wrong and why it matters
→ **Fix**: Specific suggestion or code snippet

**Confidence**: 🔴 Certain / 🟡 Likely / 🟢 Suggestion

### 4. Output Structure

\`\`\`
## Summary
[2-3 sentence overview]

## Prioritized Issues

### 🔴 Critical
[Issues that must be fixed before merge - bugs, security, breaking changes]

### 🟠 Major  
[Issues that should be fixed - logic problems, missing error handling]

### 🟡 Minor
[Issues worth addressing - code clarity, minor optimizations]

### 🔵 Enhancements
[Nice-to-haves - suggestions for improvement]

## ✅ Highlights
[Positive findings, well-implemented patterns, good practices observed]
\`\`\`

## Changed Files

**Source files** (prioritize review):
$SRC_FILES

**Test files** (verify coverage, not style):
$TEST_FILES

## Pull Request Diff

\`\`\`diff
$DIFF_CONTENT
\`\`\`

---

**CRITICAL INSTRUCTION**: Your primary job is catching bugs and breaking changes. This is production insurance software - stability is paramount. Be thorough but avoid false positives. If something looks unusual but might be intentional, note it as a question rather than an issue."

# Copy to clipboard (works on macOS)
if command -v pbcopy >/dev/null 2>&1; then
    echo "$PROMPT" | pbcopy
    echo "✅ Review prompt copied to clipboard!"
    echo "Just paste it into your chat with Cmd+V"
# Fallback for Linux
elif command -v xclip >/dev/null 2>&1; then
    echo "$PROMPT" | xclip -selection clipboard
    echo "✅ Review prompt copied to clipboard!"
    echo "Just paste it into your chat with Ctrl+V"
# Fallback for WSL/Windows
elif command -v clip.exe >/dev/null 2>&1; then
    echo "$PROMPT" | clip.exe
    echo "✅ Review prompt copied to clipboard!"
    echo "Just paste it into your chat with Ctrl+V"
else
    echo "Clipboard copy not available. Manual copy required:"
    echo "----------------------------------------"
    echo "$PROMPT"
    echo "----------------------------------------"
fi
