# Synopsis: Audits active files against registered skills.
# Description: Compares physical files in the Skills folder against the registered skills manifest.

# Safely resolve directories using the script's local directory root
$SkillsDir = $PSScriptRoot
if ($SkillsDir -match "Skills$") {
    $ParentDir = Split-Path $SkillsDir -Parent
} else {
    $ParentDir = $SkillsDir
    $SkillsDir = Join-Path $ParentDir "Skills"
}

$RegistryPath = Join-Path $ParentDir "Config\skills_registry.txt"

Write-Output "=== SKILL REGISTRY AUDIT ==="

# 1. Get Actual Files
if (Test-Path $SkillsDir) {
    $ActualSkills = Get-ChildItem -Path $SkillsDir -Filter "*.ps1" | Select-Object -ExpandProperty Name
    Write-Output "Total Files Found: $($ActualSkills.Count)"
} else {
    Write-Output "ERROR: Skills directory not found at $SkillsDir"
    exit
}

# 2. Get Registered Skills
$RegisteredSkills = @()
if (Test-Path $RegistryPath) {
    $RegistryContent = Get-Content $RegistryPath
    foreach ($line in $RegistryContent) {
        if ($line -match "^\d+\.\s*([^:]+\.ps1)") {
            $RegisteredSkills += $matches[1].Trim()
        }
    }
    Write-Output "Total Registered Skills: $($RegisteredSkills.Count)"
} else {
    Write-Output "ERROR: Registry file not found at $RegistryPath"
    exit
}

Write-Output "`n--- ANALYSIS ---"

# 3. Find Unregistered Files
$Unregistered = $ActualSkills | Where-Object { $_ -notin $RegisteredSkills }
if ($Unregistered.Count -gt 0) {
    Write-Output "WARNING: Found $($Unregistered.Count) unregistered skills:"
    foreach ($skill in $Unregistered) { Write-Output "  - $skill" }
} else {
    Write-Output "SUCCESS: All physical files are registered."
}

# 4. Find Missing Files (Ghosts)
$Ghosts = $RegisteredSkills | Where-Object { $_ -notin $ActualSkills }
if ($Ghosts.Count -gt 0) {
    Write-Output "WARNING: Found $($Ghosts.Count) registered skills that do not exist on disk:"
    foreach ($skill in $Ghosts) { Write-Output "  - $skill" }
} else {
    Write-Output "SUCCESS: All registered skills exist on disk."
}
