[CmdletBinding()]
param(
    [string]$EmmaHome = 'C:\Emma\current',
    [switch]$JsonOutput
)

$ErrorActionPreference = 'Continue'
$results = [System.Collections.Generic.List[object]]::new()

function Add-Result {
    param([string]$Name, [bool]$Passed, [string]$Detail = '')
    $results.Add([ordered]@{ Name = $Name; Passed = $Passed; Detail = $Detail }) | Out-Null
    $symbol = if ($Passed) { 'PASS' } else { 'FAIL' }
    Write-Host "[$symbol] $Name" -ForegroundColor $(if ($Passed) { 'Green' } else { 'Red' })
    if ($Detail) { Write-Host "       $Detail" }
}

function Test-PortListening {
    param([int]$Port)
    return [bool](Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue)
}

function Test-HttpEndpoint {
    param(
        [string]$Uri,
        [string]$Method = 'GET',
        [string]$Body = $null
    )
    try {
        $params = @{
            Uri             = $Uri
            Method          = $Method
            UseBasicParsing = $true
            TimeoutSec      = 10
        }
        if ($Body) {
            $params['Body'] = $Body
            $params['ContentType'] = 'application/json'
        }
        $r = Invoke-WebRequest @params
        return @{ Ok = $true; StatusCode = $r.StatusCode; Content = $r.Content }
    }
    catch {
        return @{ Ok = $false; Error = $_.Exception.Message }
    }
}

Write-Host 'Emma Local Self-Test'
Write-Host "EmmaHome: $EmmaHome"
Write-Host ''

$portOk = Test-PortListening -Port 3000
Add-Result -Name 'Service port 3000 listening' -Passed $portOk `
    -Detail $(if ($portOk) { 'OK' } else { 'Port 3000 not listening' })

$health = Test-HttpEndpoint -Uri 'http://127.0.0.1:3000/health'
Add-Result -Name 'GET /health' -Passed $health.Ok `
    -Detail $(if ($health.Ok) { "HTTP $($health.StatusCode)" } else { $health.Error })

$proxy = Test-HttpEndpoint -Uri 'http://127.0.0.1:3000/t2med/setup-exists' -Method POST -Body '{}'
Add-Result -Name 'POST /t2med/setup-exists' -Passed $proxy.Ok `
    -Detail $(if ($proxy.Ok) { "HTTP $($proxy.StatusCode)" } else { $proxy.Error })

$devAllowed = Test-HttpEndpoint -Uri 'http://127.0.0.1:3000/t2med/dev/allowed'
$devAllowedOk = $devAllowed.Ok
Add-Result -Name 'GET /t2med/dev/allowed' -Passed $devAllowedOk `
    -Detail $(if ($devAllowedOk) { "HTTP $($devAllowed.StatusCode)" } else { $devAllowed.Error })

if ($devAllowedOk -and $devAllowed.Content -match '"allowed"\s*:\s*true') {
    $devScenarios = Test-HttpEndpoint -Uri 'http://127.0.0.1:3000/t2med/dev/scenarios'
    Add-Result -Name 'GET /t2med/dev/scenarios' -Passed $devScenarios.Ok `
        -Detail $(if ($devScenarios.Ok) { "HTTP $($devScenarios.StatusCode)" } else { $devScenarios.Error })
}
else {
    Add-Result -Name 'GET /t2med/dev/scenarios' -Passed $true `
        -Detail 'Skipped (dev mock disabled)'
}

$edgeOk = [bool](Get-Process -Name 'msedge' -ErrorAction SilentlyContinue)
Add-Result -Name 'Microsoft Edge running' -Passed $edgeOk `
    -Detail $(if ($edgeOk) { 'OK' } else { 'msedge not found' })

$task = Get-ScheduledTask -TaskName 'EmmaLocal' -ErrorAction SilentlyContinue
$legacyService = Get-Service -Name 'EmmaLocal' -ErrorAction SilentlyContinue
$serverHostOk = [bool]$task -or [bool]$legacyService
$serverHostDetail = if ($task) {
    (Get-ScheduledTaskInfo -TaskName 'EmmaLocal').LastTaskResult
} elseif ($legacyService) {
    "$($legacyService.Status) (legacy Windows service)"
} else {
    'Startup task not found'
}
Add-Result -Name 'EmmaLocal server host registered' -Passed $serverHostOk `
    -Detail $serverHostDetail

$winlogonPath = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'
$props = Get-ItemProperty -Path $winlogonPath -ErrorAction SilentlyContinue
$autologonOk = ($props.AutoAdminLogon -eq '1')
Add-Result -Name 'Autologon configured' -Passed $autologonOk

$fwRules = @(Get-NetFirewallRule -ErrorAction SilentlyContinue |
    Where-Object { $_.DisplayName -like 'Emma Local*' })
Add-Result -Name 'Emma Local firewall rules present' -Passed ($fwRules.Count -gt 0) `
    -Detail "Rules: $($fwRules.Count)"

$versionPath = Join-Path $EmmaHome 'version.json'
$versionOk = Test-Path $versionPath
Add-Result -Name 'version.json present' -Passed $versionOk -Detail $versionPath

$failed = @($results | Where-Object { -not $_.Passed })
$summary = [ordered]@{
    Total  = $results.Count
    Passed = $results.Count - $failed.Count
    Failed = $failed.Count
    Checks = $results
}

Write-Host ''
Write-Host "Summary: $($summary.Passed)/$($summary.Total) passed"
if ($JsonOutput) { $summary | ConvertTo-Json -Depth 5 }
if ($failed.Count -gt 0) { exit 1 }
exit 0
