Public/Doctor.ps1

# ---------------------------------------------------------------------------
# Doctor - self-diagnostic health checks
# ---------------------------------------------------------------------------

function Invoke-TTDoctor {
    <#
    .SYNOPSIS
        Run health checks on the TerminalTracker installation.
    .DESCRIPTION
        Performs five diagnostic checks and prints a color-coded pass/fail
        result for each. Failing checks include a suggested remedy or
        automatic repair where possible.
    .EXAMPLE
        Invoke-TTDoctor
        Runs all diagnostic checks and reports results.
    #>

    [CmdletBinding()]
    param()

    $pass = 0
    $fail = 0

    function Write-Check {
        param([string]$Label, [bool]$Ok, [string]$Remedy = '')
        if ($Ok) {
            Write-Host " [OK] $Label" -ForegroundColor Green
            $script:pass++
        }
        else {
            Write-Host " [FAIL] $Label" -ForegroundColor Red
            if ($Remedy) {
                Write-Host " Remedy: $Remedy" -ForegroundColor Yellow
            }
            $script:fail++
        }
    }

    Write-Host ""
    Write-Host "TerminalTracker -- Doctor" -ForegroundColor Cyan
    Write-Host ("-" * 40) -ForegroundColor DarkGray
    Write-Host ""

    # Check 1: Module loads without error
    $moduleOk = $false
    try {
        $m = Get-Module TerminalTracker -ErrorAction SilentlyContinue
        if (-not $m) {
            # Try to find the manifest from the current module file location
            $manifestPath = Join-Path (Split-Path $PSScriptRoot -Parent) 'TerminalTracker.psd1'
            if (Test-Path $manifestPath) {
                Import-Module $manifestPath -Force -DisableNameChecking -ErrorAction Stop
                $moduleOk = $true
            }
        }
        else {
            $moduleOk = $true
        }
    }
    catch { }
    Write-Check "Module loads without error" $moduleOk "Run: Import-Module .\TerminalTracker.psd1 and check for errors"

    # Check 2: Profile hook path is valid (no bad Public\ path in hook block)
    $hookOk = $true
    $hookInstalled = $false
    $profilePath = $PROFILE.CurrentUserAllHosts
    if (Test-Path $profilePath) {
        $content = [System.IO.File]::ReadAllText($profilePath)
        $startMarker = '# >>> TerminalTracker Hook >>>'
        $endMarker   = '# <<< TerminalTracker Hook <<<'
        $startIdx = $content.IndexOf($startMarker)
        if ($startIdx -ge 0) {
            $hookInstalled = $true
            $endIdx = $content.IndexOf($endMarker)
            if ($endIdx -gt $startIdx) {
                $block = $content.Substring($startIdx, $endIdx - $startIdx + $endMarker.Length)
                if ($block -match 'Public[/\\]TerminalTracker') {
                    $hookOk = $false
                }
            }
        }
    }
    if ($hookInstalled) {
        Write-Check "Profile hook path is valid" $hookOk "Run: Repair-TTProfileHook"
        if (-not $hookOk) {
            Write-Host " Auto-repairing hook..." -ForegroundColor Yellow
            try {
                Repair-TTProfileHook
            }
            catch {
                Write-Host " Auto-repair failed: $_" -ForegroundColor Red
            }
        }
    }
    else {
        Write-Host " [--] Profile hook not installed (skipping path check)" -ForegroundColor DarkGray
    }

    # Check 3: Data directory exists
    $dataDir = Join-Path $env:APPDATA 'TerminalTracker'
    $dataDirOk = Test-Path $dataDir
    Write-Check "Data directory exists ($dataDir)" $dataDirOk "Run: Initialize-TTDataStore (or Import-Module TerminalTracker)"

    # Check 4: Monitor job status
    $monitorJob = Get-Job -Name 'TerminalTracker-Monitor' -ErrorAction SilentlyContinue |
        Where-Object { $_.State -eq 'Running' } |
        Select-Object -First 1
    $monitorOk = $null -ne $monitorJob
    Write-Check "Background monitor is running" $monitorOk "Run: Start-TTMonitor -AsJob"

    # Check 5: Auto-start task registration
    $autoStartOk = $false
    try {
        $task = Get-ScheduledTask -TaskName 'TerminalTracker-AutoStart' -ErrorAction SilentlyContinue
        $autoStartOk = $null -ne $task
    }
    catch { }
    Write-Check "Auto-start task registered" $autoStartOk "Run: Install-TTAutoStart"

    Write-Host ""
    Write-Host ("-" * 40) -ForegroundColor DarkGray
    $totalChecked = $pass + $fail
    if ($hookInstalled -eq $false) { $totalChecked++ }
    if ($fail -eq 0) {
        Write-Host "All checks passed ($pass/$pass)." -ForegroundColor Green
    }
    else {
        Write-Host "$fail check(s) failed, $pass passed." -ForegroundColor Yellow
    }
    Write-Host ""
}