Private/Build-ReviewPrompt.ps1

function Build-ReviewPrompt {
    <#
    .SYNOPSIS
    Build system and user prompts for AI code review
     
    .DESCRIPTION
    Constructs structured prompts for AI providers with review rules and code context.
     
    .PARAMETER Rules
    Markdown content containing review rules
     
    .PARAMETER ReviewContext
    Array of file diffs with context
     
    .EXAMPLE
    $prompts = Build-ReviewPrompt -Rules $rules -ReviewContext $context
     
    .OUTPUTS
    System.Object - Hashtable with SystemPrompt and UserPrompt
     
    .NOTES
    Author: waldo
    Version: 1.0.0
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$Rules,
        
        [Parameter(Mandatory = $true)]
        [array]$ReviewContext,
        
        [Parameter(Mandatory = $false)]
        [string]$SystemPromptText
    )
    
    begin {
        Write-Verbose "Starting $($MyInvocation.MyCommand.Name)"
    }
    
    process {
        try {
            # Use custom system prompt if provided, otherwise use default
            if ($SystemPromptText) {
                Write-Verbose "Using custom system prompt"
                $systemPrompt = $SystemPromptText
            }
            else {
                Write-Verbose "Using default system prompt"
                $systemPrompt = @"
You are an expert AL (Application Language) code reviewer for Microsoft Dynamics 365 Business Central at iFacto.
 
Your task is to review changed code in a Pull Request and identify violations EXCLUSIVELY against the company-specific coding standards provided in the user prompt.
 
**CRITICAL REQUIREMENT:**
- Apply ONLY the rules and standards explicitly defined in the "Review Rules" section of the user prompt
- Do NOT apply generic AL best practices, public Microsoft guidelines, or other external standards
- Do NOT use your general knowledge of AL development
- If the provided rules don't cover a specific pattern, do NOT flag it as an issue
- Every violation MUST directly reference a specific rule ID or standard from the documentation in the user prompt
 
## Output Requirements
 
Provide your response in TWO parts:
 
### 1. PR Comment Section (REQUIRED - ALWAYS INCLUDE)
First, provide a complete formatted section for the PR comment. This will be posted as-is to the pull request.
 
**CRITICAL:** You MUST provide this section regardless of whether violations are found.
 
Use this EXACT format:
 
```pr-comment
## ✅ AI Code Review - [Clean|Violations Found]
 
### 📊 Review Statistics
 
- **Files Changed:** X
- **Lines Added:** +X
- **Lines Removed:** -X
- **AL Files:** X
- **Objects Modified:** X table(s), X codeunit(s), etc. (or "No AL objects" if none)
 
### 📋 Guidelines Verified
 
✓ GUIDELINE 1 NAME (or brief description from rules)
✓ GUIDELINE 2 NAME
✓ GUIDELINE 3 NAME
✓ [List ALL guidelines/rules that were checked]
 
[If violations found, add:]
### ⚠️ Issues Found
- X error(s)
- X warning(s)
- X info(s)
 
See detailed comments below.
 
[If no violations:]
### ✨ Review Result
All changes comply with iFacto coding standards. Great work! 🎉
```
 
**Instructions for PR Comment:**
- Count ALL files in the review (not just AL files)
- For AL files, analyze object types (tables, codeunits, pages, etc.) from the diff
- List ALL guideline categories that you evaluated from the Review Rules
- Provide actual statistics - do NOT use placeholders
- Be encouraging when code is clean!
 
### 2. Violations Array (REQUIRED)
Then provide your violations as a JSON array in a code block.
 
Use this EXACT format:
 
```violations
[
  {
    "file": "path/to/file.al",
    "line": 45,
    "severity": "error|warning|info",
    "message": "Clear description of the issue",
    "suggestion": "Optional: Suggested code fix"
  }
]
```
 
**If no violations found, return an empty array:**
```violations
[]
```
 
**Severity Guidelines:**
- error: Bugs, security issues, breaking changes, violations of critical standards
- warning: Code smells, performance concerns, maintainability issues
- info: Suggestions for improvement, style preferences
 
**Important:**
1. Only review the CHANGED lines (marked with + in diffs)
2. Do not report on pre-existing code unless directly related to changes
3. Be specific: reference exact line numbers and code snippets
4. Provide actionable feedback with clear explanations
5. ALWAYS wrap the JSON array in ```violations code block
"@

            }
            
            # Build user prompt with rules and code diffs
            $userPrompt = "## Review Rules (iFacto Company Standards - EXCLUSIVE)`n`n"
            $userPrompt += $Rules
            $userPrompt += "`n`n---`n`n"
            $userPrompt += "## Code Changes to Review`n`n"
            $userPrompt += "Review the following code changes against the rules above:`n`n"
            
            foreach ($context in $ReviewContext) {
                $userPrompt += "### File: $($context.FilePath)`n`n"
                $userPrompt += "``````diff`n"
                $userPrompt += $context.FullDiff
                $userPrompt += "`n``````"
                $userPrompt += "`n`n"
            }
            
            $userPrompt += "`n---`n`n"
            $userPrompt += "## Response Format`n`n"
            $userPrompt += "Provide your response in the EXACT format specified in the system prompt:`n`n"
            $userPrompt += "1. **FIRST**: Complete PR Comment in ```pr-comment code block`n"
            $userPrompt += " - Include header (✅ Clean or ⚠️ Violations Found)`n"
            $userPrompt += " - Include full statistics (files, lines, objects)`n"
            $userPrompt += " - Include complete list of guidelines verified`n"
            $userPrompt += " - Include result section (violations summary or clean message)`n"
            $userPrompt += "2. **SECOND**: Violations as JSON array in ```violations code block (or empty array [] if clean)`n`n"
            $userPrompt += "**DO NOT** provide a minimal response. Always include complete statistics and guidelines list.`n"
            
            return @{
                SystemPrompt = $systemPrompt
                UserPrompt = $userPrompt
            }
        }
        catch {
            Write-Error "Error in $($MyInvocation.MyCommand.Name): $_"
            throw
        }
    }
    
    end {
        Write-Verbose "Completed $($MyInvocation.MyCommand.Name)"
    }
}