# iWifiMonitor - Diagnostic Script
# Run this to troubleshoot installation issues

$ErrorActionPreference = "Continue"

$AppName = "iWiFiMonitor"
$ServiceName = "iWiFiMonitor"
$WebServiceName = "iWiFiMonitorWeb"
$InstallDir = "$env:ProgramFiles\$AppName"
$DataDir = "$env:ProgramData\$AppName"

Write-Host ""
Write-Host "==========================================" -ForegroundColor Cyan
Write-Host "   iWifiMonitor - Diagnostics" -ForegroundColor Cyan
Write-Host "==========================================" -ForegroundColor Cyan
Write-Host ""

# System Info
Write-Host "[System Info]" -ForegroundColor Yellow
Write-Host "  Computer: $env:COMPUTERNAME"
Write-Host "  OS: $([System.Environment]::OSVersion.VersionString)"
Write-Host "  PowerShell: $($PSVersionTable.PSVersion)"
Write-Host ""

# Check Installation
Write-Host "[Installation]" -ForegroundColor Yellow
if (Test-Path $InstallDir) {
    Write-Host "  Install directory: OK ($InstallDir)" -ForegroundColor Green
    $exeCount = (Get-ChildItem "$InstallDir\*.exe" -ErrorAction SilentlyContinue).Count
    Write-Host "  Executables found: $exeCount"
} else {
    Write-Host "  Install directory: MISSING ($InstallDir)" -ForegroundColor Red
}

if (Test-Path $DataDir) {
    Write-Host "  Data directory: OK ($DataDir)" -ForegroundColor Green
    $dbPath = Join-Path $DataDir "iwifimonitor.db"
    if (Test-Path $dbPath) {
        $dbSize = (Get-Item $dbPath).Length / 1KB
        Write-Host ("  Database: OK ({0:N1} KB)" -f $dbSize) -ForegroundColor Green
    } else {
        Write-Host "  Database: MISSING" -ForegroundColor Red
    }
} else {
    Write-Host "  Data directory: MISSING ($DataDir)" -ForegroundColor Red
}
Write-Host ""

# Check Services
Write-Host "[Services]" -ForegroundColor Yellow
$svc1 = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
if ($svc1) {
    $color = if ($svc1.Status -eq "Running") { "Green" } else { "Red" }
    Write-Host "  $ServiceName : $($svc1.Status)" -ForegroundColor $color
} else {
    Write-Host "  $ServiceName : NOT INSTALLED" -ForegroundColor Red
}

$svc2 = Get-Service -Name $WebServiceName -ErrorAction SilentlyContinue
if ($svc2) {
    $color = if ($svc2.Status -eq "Running") { "Green" } else { "Red" }
    Write-Host "  $WebServiceName : $($svc2.Status)" -ForegroundColor $color
} else {
    Write-Host "  $WebServiceName : NOT INSTALLED" -ForegroundColor Red
}
Write-Host ""

# Check Port
Write-Host "[Network - Port 5280]" -ForegroundColor Yellow
$listener = Get-NetTCPConnection -LocalPort 5280 -ErrorAction SilentlyContinue
if ($listener) {
    Write-Host "  Port 5280: LISTENING" -ForegroundColor Green
    Write-Host "  Process ID: $($listener.OwningProcess | Select-Object -First 1)"
} else {
    Write-Host "  Port 5280: NOT LISTENING" -ForegroundColor Red
}

# Test web endpoint
try {
    $response = Invoke-WebRequest -Uri "http://localhost:5280" -TimeoutSec 5 -UseBasicParsing -ErrorAction Stop
    Write-Host "  Web UI: RESPONDING (HTTP $($response.StatusCode))" -ForegroundColor Green
} catch {
    Write-Host "  Web UI: NOT RESPONDING" -ForegroundColor Red
}
Write-Host ""

# Check Firewall
Write-Host "[Firewall]" -ForegroundColor Yellow
$rule = Get-NetFirewallRule -DisplayName "iWifiMonitor Web UI" -ErrorAction SilentlyContinue
if ($rule) {
    Write-Host "  Firewall rule: OK (Enabled: $($rule.Enabled))" -ForegroundColor Green
} else {
    Write-Host "  Firewall rule: MISSING" -ForegroundColor Yellow
}
Write-Host ""

# Network Connectivity Tests
Write-Host "[Network Connectivity]" -ForegroundColor Yellow

# Gateway
$gateway = (Get-NetRoute -DestinationPrefix "0.0.0.0/0" -ErrorAction SilentlyContinue | Select-Object -First 1).NextHop
if ($gateway) {
    Write-Host "  Default Gateway: $gateway"
    $pingGw = Test-Connection -ComputerName $gateway -Count 1 -Quiet -ErrorAction SilentlyContinue
    if ($pingGw) {
        Write-Host "  Gateway Ping: OK" -ForegroundColor Green
    } else {
        Write-Host "  Gateway Ping: FAILED" -ForegroundColor Red
    }
} else {
    Write-Host "  Default Gateway: NOT FOUND" -ForegroundColor Red
}

# External IPs
$testIPs = @("8.8.8.8", "1.1.1.1")
foreach ($ip in $testIPs) {
    $ping = Test-Connection -ComputerName $ip -Count 1 -Quiet -ErrorAction SilentlyContinue
    if ($ping) {
        Write-Host "  Ping $ip : OK" -ForegroundColor Green
    } else {
        Write-Host "  Ping $ip : FAILED" -ForegroundColor Red
    }
}

# DNS
try {
    $dns = Resolve-DnsName -Name "google.com" -Type A -ErrorAction Stop | Select-Object -First 1
    Write-Host "  DNS Resolution: OK (google.com -> $($dns.IPAddress))" -ForegroundColor Green
} catch {
    Write-Host "  DNS Resolution: FAILED" -ForegroundColor Red
}

# HTTP test
try {
    $http = Invoke-WebRequest -Uri "http://www.google.com" -TimeoutSec 5 -UseBasicParsing -ErrorAction Stop
    Write-Host "  HTTP Request: OK" -ForegroundColor Green
} catch {
    Write-Host "  HTTP Request: FAILED" -ForegroundColor Red
}
Write-Host ""

# WiFi Adapter
Write-Host "[WiFi Adapter]" -ForegroundColor Yellow
$wifi = Get-NetAdapter | Where-Object { $_.InterfaceDescription -match "Wi-Fi|Wireless|802\.11" }
if ($wifi) {
    Write-Host "  WiFi Adapter: $($wifi.Name) ($($wifi.Status))" -ForegroundColor Green
} else {
    Write-Host "  WiFi Adapter: NOT FOUND (this is expected in VMs)" -ForegroundColor Yellow
}
Write-Host ""

# Recent Event Log Errors
Write-Host "[Recent Errors (last 24 hours)]" -ForegroundColor Yellow
$yesterday = (Get-Date).AddDays(-1)
$events = Get-WinEvent -FilterHashtable @{
    LogName = 'Application'
    Level = 2  # Error
    StartTime = $yesterday
} -MaxEvents 20 -ErrorAction SilentlyContinue | Where-Object {
    $_.Message -match "iWiFi|iwifimonitor" -or $_.ProviderName -match "iWiFi|iwifimonitor"
}

if ($events) {
    foreach ($event in $events) {
        Write-Host "  [$($event.TimeCreated)] $($event.Message.Substring(0, [Math]::Min(100, $event.Message.Length)))..." -ForegroundColor Red
    }
} else {
    Write-Host "  No iWifiMonitor errors found" -ForegroundColor Green
}
Write-Host ""

# Summary
Write-Host "==========================================" -ForegroundColor Cyan
Write-Host "   Diagnostics Complete" -ForegroundColor Cyan
Write-Host "==========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "If you need support, copy all the above output and send it to the developer."
Write-Host ""

# Offer to save to file
$saveToFile = Read-Host "Save diagnostics to file? (Y/n)"
if ($saveToFile -ne "n" -and $saveToFile -ne "N") {
    $outputFile = Join-Path $env:USERPROFILE "Desktop\iwifimonitor-diagnostics.txt"

    # Re-run and capture output
    & $MyInvocation.MyCommand.Path *> $outputFile 2>&1

    # Actually, just tell them to copy manually since re-running would be recursive
    Write-Host ""
    Write-Host "To save: Right-click window title -> Edit -> Select All -> Edit -> Copy"
    Write-Host "Then paste into a text file."
}
