# Synopsis: Encodes operational lessons into identity.
# Description: Appends newly discovered rules from NextLesson.txt directly to identity.txt.

$TargetDir = Split-Path -Parent $PSScriptRoot
$LessonPath = Join-Path $TargetDir "Memory\NextLesson.txt"
$IdPath = Join-Path $TargetDir "Config\identity.txt"

if (-not (Test-Path $LessonPath)) {
    Write-Output "ERROR: No lesson found at $LessonPath"
    exit
}

$Lesson = Get-Content $LessonPath -Raw

if (Test-Path $IdPath) {
    $Content = Get-Content $IdPath -Raw
    
    # We use bullet points instead of numbers to avoid parsing errors
    $NewRule = "- Auto-Learned Rule: $Lesson"
    
    $Content = $Content -replace "\*\*\*MIRROR DIRECTIVE\*\*\*", "$NewRule`n`n***MIRROR DIRECTIVE***"
    $Content = $Content -replace "\*\*\*PRODUCTION DIRECTIVE\*\*\*", "$NewRule`n`n***PRODUCTION DIRECTIVE***"
    
    Set-Content -Path $IdPath -Value $Content -Encoding UTF8
    Write-Output "SUCCESS: Permanently embedded rule into identity: '$NewRule'"
    
    Remove-Item $LessonPath -Force
} else {
    Write-Output "ERROR: identity.txt not found at $IdPath"
}

