$ErrorActionPreference = "Continue"

function Get-SystemReport {
    $os = $null
    try { $os = (Get-CimInstance Win32_OperatingSystem).Caption } catch { $os = [System.Environment]::OSVersion.VersionString }
    $ram = $null
    try { $ram = [math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB, 2) } catch { $ram = 0 }

    [pscustomobject]@{
        ComputerName = $env:COMPUTERNAME
        UserName     = $env:USERNAME
        OS           = $os
        TotalRAMGB   = $ram
        Time         = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
    }
}

function Get-NetworkReport {
    try {
        $items = Get-NetIPAddress -AddressFamily IPv4 -ErrorAction Stop |
            Where-Object { $_.IPAddress -notlike "127.*" } |
            Select-Object InterfaceAlias, IPAddress, PrefixLength
        if ($items) { return $items }
    } catch { }

    try {
        $fallback = Get-CimInstance Win32_NetworkAdapterConfiguration |
            Where-Object { $_.IPAddress } |
            ForEach-Object {
                foreach ($ip in $_.IPAddress) {
                    if ($ip -and $ip -notlike '127.*' -and $ip -notlike '*:*') {
                        [pscustomobject]@{
                            InterfaceAlias = $_.Description
                            IPAddress      = $ip
                            PrefixLength   = ''
                        }
                    }
                }
            }
        if ($fallback) { return $fallback }
    } catch { }

    return @()
}

function Get-TopProcesses {
    try { return Get-Process | Sort-Object CPU -Descending | Select-Object -First 5 Name, Id, CPU } catch { return @() }
}

function Export-Report {
    $folder = Join-Path $PSScriptRoot "data"
    if (!(Test-Path $folder)) { New-Item -ItemType Directory -Path $folder | Out-Null }
    $file = Join-Path $folder "diagnostics-report.txt"
    $system = Get-SystemReport | Out-String
    $network = (Get-NetworkReport | Out-String)
    $processes = (Get-TopProcesses | Out-String)
@"
=== SYSTEM ===
$system
=== NETWORK ===
$network
=== PROCESSES ===
$processes
"@ | Set-Content -Path $file -Encoding UTF8
    Write-Output $file
}

function New-DashboardHtml {
    $folder = Join-Path $PSScriptRoot "data"
    if (!(Test-Path $folder)) { New-Item -ItemType Directory -Path $folder | Out-Null }
    $file = Join-Path $folder "diagnostics-dashboard.html"
    $system = Get-SystemReport

    $networkRows = foreach ($item in (Get-NetworkReport)) {
        "<tr><td>$($item.InterfaceAlias)</td><td>$($item.IPAddress)</td><td>$($item.PrefixLength)</td></tr>"
    }
    if (-not $networkRows) { $networkRows = "<tr><td colspan='3'>Data jaringan tidak tersedia.</td></tr>" }

    $processRows = foreach ($item in (Get-TopProcesses)) {
        $cpuValue = if ($null -ne $item.CPU) { [math]::Round([double]$item.CPU, 2) } else { 0 }
        "<tr><td>$($item.Name)</td><td>$($item.Id)</td><td>$cpuValue</td></tr>"
    }
    if (-not $processRows) { $processRows = "<tr><td colspan='3'>Data proses tidak tersedia.</td></tr>" }

    $html = @"
<!doctype html>
<html lang="id">
<head>
  <meta charset="utf-8">
  <title>Diagnostics Toolkit Shell</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body { font-family: Segoe UI, Arial, sans-serif; margin: 0; background: #f8fafc; color: #0f172a; }
    header { padding: 22px 28px; background: linear-gradient(135deg, #0f172a, #0284c7); color: white; }
    main { padding: 22px 28px; display: grid; gap: 18px; }
    .grid { display: grid; gap: 14px; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }
    .card { background: white; border: 1px solid #e2e8f0; border-radius: 16px; padding: 16px; box-shadow: 0 12px 24px rgba(15, 23, 42, 0.06); }
    .label { color: #475569; font-size: 13px; margin-bottom: 6px; }
    .value { font-size: 22px; font-weight: 700; }
    table { width: 100%; border-collapse: collapse; }
    th, td { padding: 10px 8px; text-align: left; border-bottom: 1px solid #e2e8f0; vertical-align: top; }
    th { color: #475569; font-weight: 600; }
    .note { color: #475569; font-size: 13px; }
  </style>
</head>
<body>
  <header>
    <h1>Diagnostics Toolkit Shell</h1>
    <p>Dashboard HTML untuk ringkasan kondisi sistem, jaringan, dan proses aktif.</p>
  </header>
  <main>
    <section class="grid">
      <div class="card"><div class="label">Computer Name</div><div class="value">$($system.ComputerName)</div></div>
      <div class="card"><div class="label">User</div><div class="value">$($system.UserName)</div></div>
      <div class="card"><div class="label">OS</div><div class="value">$($system.OS)</div></div>
      <div class="card"><div class="label">RAM (GB)</div><div class="value">$($system.TotalRAMGB)</div></div>
    </section>
    <section class="card">
      <h2>Jaringan</h2>
      <table><thead><tr><th>Interface</th><th>IPv4</th><th>Prefix</th></tr></thead><tbody>$($networkRows -join "`n")</tbody></table>
    </section>
    <section class="card">
      <h2>Proses Aktif Teratas</h2>
      <table><thead><tr><th>Nama</th><th>ID</th><th>CPU</th></tr></thead><tbody>$($processRows -join "`n")</tbody></table>
    </section>
    <p class="note">Tip presentasi: tunjukkan ringkasan sistem dulu, lalu masuk ke IP aktif, kemudian jelaskan proses mana yang paling berat.</p>
  </main>
</body>
</html>
"@
    Set-Content -Path $file -Value $html -Encoding UTF8
    Write-Output $file
}

function Show-Menu {
    Write-Host ""
    Write-Host "=== Diagnostics Toolkit Shell (Windows) ===" -ForegroundColor Cyan
    Write-Host "1. Info sistem"
    Write-Host "2. Info jaringan"
    Write-Host "3. Proses aktif (5 teratas)"
    Write-Host "4. Ekspor laporan teks"
    Write-Host "5. Bangun dashboard HTML"
    Write-Host "0. Keluar"
}

if ($args -contains "--smoke-test") {
    [pscustomobject]@{
        app     = 'diagnostics-toolkit-shell'
        system  = Get-SystemReport
        network = @(Get-NetworkReport).Count
        process = @(Get-TopProcesses).Count
    } | ConvertTo-Json -Depth 4
    exit 0
}

if ($args -contains "--dashboard") {
    New-DashboardHtml
    exit 0
}

do {
    Show-Menu
    $choice = Read-Host "Pilih menu"
    switch ($choice) {
        "1" { Get-SystemReport | Format-List }
        "2" { Get-NetworkReport | Format-Table -AutoSize }
        "3" { Get-TopProcesses | Format-Table -AutoSize }
        "4" { $file = Export-Report; Write-Host "Laporan disimpan ke $file" -ForegroundColor Green }
        "5" { $file = New-DashboardHtml; Write-Host "Dashboard dibuat di $file" -ForegroundColor Green }
        "0" { break }
        default { Write-Host "Menu tidak valid." -ForegroundColor Yellow }
    }
} while ($true)
