# ReconcileLocalToGitHub.ps1
# Connect C:\Repositories\GetEstablished to https://github.com/dwlott/GetEstablished
# and merge local session work with origin/main.
#
# Run from an elevated or normal PowerShell window:
#   Set-Location C:\Repositories\GetEstablished
#   .\Plans\ReconcileLocalToGitHub.ps1
#
# Optional: pass -Push to push after a successful merge.

param(
    [switch]$Push
)

$ErrorActionPreference = 'Stop'
$RepoRoot = 'C:\Repositories\GetEstablished'
$RemoteUrl = 'https://github.com/dwlott/GetEstablished.git'

Set-Location $RepoRoot

Write-Host "=== 1. Ensure git repository ===" -ForegroundColor Cyan
if (-not (Test-Path '.git')) {
    git init -b main
}

Write-Host "=== 2. Ensure origin remote ===" -ForegroundColor Cyan
$remotes = git remote
if ($remotes -notcontains 'origin') {
    git remote add origin $RemoteUrl
} else {
    git remote set-url origin $RemoteUrl
}

Write-Host "=== 3. Fetch origin/main ===" -ForegroundColor Cyan
git fetch origin

Write-Host "=== 4. Stage local work (respects .gitignore if present) ===" -ForegroundColor Cyan
git add -A

$status = git status --porcelain
if ($status) {
    Write-Host "=== 5. Commit local baseline ===" -ForegroundColor Cyan
    git commit -m @"
Reconcile local GetEstablished with GitHub origin.

Session work: Plans cleanup, RepositoryLearning harmonize,
AgentSituationalAwareness (Cursor vs ChatGPT), Cursor YouTube demo
guides, bulk Plans path normalization, and related registry updates.
"@
} else {
    Write-Host "No local changes to commit before merge." -ForegroundColor Yellow
}

Write-Host "=== 6. Merge origin/main ===" -ForegroundColor Cyan
$mergeCheck = git merge-base HEAD origin/main 2>$null
if ($LASTEXITCODE -ne 0 -or -not $mergeCheck) {
    git merge origin/main -m @"
Merge origin/main into local main after session reconciliation.
"@ --allow-unrelated-histories
} else {
    git merge origin/main -m @"
Merge origin/main into local main after session reconciliation.
"@
}

if ($LASTEXITCODE -ne 0) {
    Write-Host "=== 6b. Resolve add/add conflicts (keep local session work) ===" -ForegroundColor Yellow
    $conflicts = git diff --name-only --diff-filter=U
    if ($conflicts) {
        $conflicts | ForEach-Object {
            git checkout --ours -- $_
            git add -- $_
        }
        git add -A
        git commit -m @"
Merge origin/main; keep local session work on conflicts.
"@
    } else {
        Write-Host "MERGE FAILED — resolve manually, then commit." -ForegroundColor Red
        git status -sb
        exit 1
    }
}

Write-Host "=== 7. Status ===" -ForegroundColor Cyan
git status -sb
git log -3 --oneline

if ($Push) {
    Write-Host "=== 8. Push to origin ===" -ForegroundColor Cyan
    git push -u origin main
    Write-Host "Push complete." -ForegroundColor Green
} else {
    Write-Host @"

Merge complete. Review with:  git status
To push:  git push -u origin main
Or rerun: .\Plans\ReconcileLocalToGitHub.ps1 -Push

"@ -ForegroundColor Green
}
