#!/usr/bin/env python3
import cgi, sys
sys.path.insert(0, '/opt/ngon/apps')
from managers.auth_manager import AuthManager, generate_login_page_html

_form = cgi.FieldStorage()
_auth = AuthManager('how_to_status_page')
_auth_required, _should_exit, _headers = _auth.require_auth(_form)

if _should_exit:
    print("Content-Type: application/json")
    if _headers:
        print(_headers)
    print("")
    if _auth_required:
        print('{"success": false, "error": "Authentication required"}')
    else:
        print('{"success": true}')
    sys.exit(0)

if _auth_required:
    print("Content-Type: text/html")
    print("")
    print(generate_login_page_html("How-To: Using the Status Page"))
    sys.exit(0)


sys.path.insert(0, '/var/www/html/ngon')
from links import generate_dropdown_html, generate_dropdown_css, generate_dropdown_js
_user_access = AuthManager.get_user_access()
_nav_html = generate_dropdown_html(_user_access)
_nav_css = generate_dropdown_css()
_nav_js = generate_dropdown_js()

print("Content-Type: text/html\n")

HTML = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NGON How-To: Using the Status Page</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<link rel="stylesheet" href="/status/styles.css?v=30" />
<style>__NAV_CSS__</style>
<style>
html, body { background: #1a1a1a !important; }
body { padding-bottom: 60px; }
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-thumb { background: #666; border-radius: 3px; }

.header {
    background-color: rgba(255,255,255,0.05) !important;
    border-radius: 8px !important;
    padding: 30px !important;
    margin: 20px !important;
    border: 1px solid rgba(255,255,255,0.1) !important;
    border-bottom: none !important;
    display: flex !important;
    justify-content: space-between !important;
    align-items: flex-start !important;
}
.header h1.dropdown-title {
    font-size: 2.2em !important;
    font-weight: 600 !important;
    margin: 3px 0 0 0 !important;
    line-height: 1.2 !important;
}

.howto-body { max-width: 900px; margin: 0 auto; padding: 20px; }

h2 {
    font-size: 22px;
    color: #00ff00;
    margin: 40px 0 14px 0;
    padding-bottom: 8px;
    border-bottom: 1px solid #333;
}
h3 { font-size: 17px; color: #4a9eff; margin: 24px 0 10px 0; }
h4 { font-size: 15px; color: #ffaa00; margin: 18px 0 8px 0; }
p { margin: 10px 0; color: #ccc; }
ul, ol { margin: 10px 0 10px 24px; color: #ccc; }
li { margin: 6px 0; }
code {
    background: #2a2a2a;
    padding: 2px 6px;
    border-radius: 3px;
    font-family: 'Menlo', 'Consolas', monospace;
    font-size: 13px;
    color: #ffaa00;
}

.toc {
    background: #222;
    border: 1px solid #333;
    border-radius: 6px;
    padding: 16px 20px;
    margin: 20px 0;
}
.toc h3 { color: #e0e0e0; margin-top: 0; font-size: 14px; text-transform: uppercase; letter-spacing: 1px; }
.toc ul { list-style: none; margin: 10px 0 0 0; }
.toc li { margin: 4px 0; }
.toc a { color: #4a9eff; text-decoration: none; }
.toc a:hover { color: #00ff00; }

.cheat {
    background: #1e2a1e;
    border: 1px solid #2a4a2a;
    border-radius: 6px;
    padding: 18px 22px;
    margin: 20px 0;
}
.cheat h3 { color: #00ff00; margin-top: 0; }
.cheat table { width: 100%; border-collapse: collapse; margin-top: 10px; font-size: 14px; }
.cheat th, .cheat td { padding: 8px 10px; text-align: left; border-bottom: 1px solid #2a4a2a; vertical-align: top; }
.cheat th { color: #00ff00; font-weight: 600; }
.cheat td { color: #ccc; }

.callout {
    border-left: 3px solid #4a9eff;
    background: #1e232a;
    padding: 12px 16px;
    margin: 16px 0;
    border-radius: 0 4px 4px 0;
}
.callout.warn { border-left-color: #ff6600; background: #2a1f12; }
.callout.bad  { border-left-color: #ff4444; background: #2a1414; }
.callout.good { border-left-color: #00ff00; background: #122a12; }
.callout .label {
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 1px;
    text-transform: uppercase;
    display: block;
    margin-bottom: 4px;
}
.callout.warn .label { color: #ff6600; }
.callout.bad  .label { color: #ff4444; }
.callout.good .label { color: #00ff00; }
.callout p { margin: 4px 0; }

/* inline icons matching the status page (Font Awesome), colored like the page */
.ic { margin: 0 3px; }
.ic-wifi { color: #00ff00; }
.ic-warn { color: #ff6600; }
.ic-hold { color: #4a9eff; }
.ic-mute { color: #888; }
.ic-misplaced { color: #aa44ff; }
.ic-bolt { color: #ffdd00; }
.ic-dish { color: #4a9eff; }
.ic-wrench { color: #888; }

.swatch {
    display: inline-block;
    width: 12px; height: 12px;
    border-radius: 50%;
    margin-right: 6px;
    vertical-align: middle;
}
.s-green { background: #00ff00; }
.s-blue  { background: #4a9eff; }
.s-orange{ background: #ff6600; }
.s-red   { background: #ff4444; }
.s-yellow{ background: #ffdd00; }
.s-purple{ background: #aa44ff; }
.s-white { background: #ffffff; }
.s-grey  { background: #888888; }

.tag {
    display: inline-block;
    background: #2a2a2a;
    color: #4a9eff;
    padding: 2px 8px;
    border-radius: 3px;
    font-size: 12px;
    font-family: monospace;
    margin: 0 2px;
}

@media (max-width: 700px) {
    .howto-body { padding: 14px; }
    h2 { font-size: 19px; }
    h3 { font-size: 15px; }
    .cheat table { font-size: 12px; }
    .cheat th, .cheat td { padding: 6px 4px; }
}
</style>
</head>
<body>

<div class="header">
    <div>
      <div class="dropdown">
        <h1 class="dropdown-title">NGON Mining - How-To: Using the Status Page</h1>
        <div class="dropdown-content">__DROPDOWN_HTML__</div>
      </div>
    </div>
</div>

<div class="howto-body">

<p>The Status Page is the main dashboard for the whole fleet. It's a
<strong>live</strong> view — it stays connected and updates about once a second,
so what you see is close to real-time. This guide walks a new person through
everything on it: the numbers up top, how the page is laid out, what the colors
mean, and what each thing does when you click it. Almost everything here is
just <em>looking</em> at data; the few controls that actually change something
are flagged clearly.</p>

<div class="toc">
    <h3>Contents</h3>
    <ul>
        <li><a href="#connection">Is It Live? (top-of-page indicators)</a></li>
        <li><a href="#summary">The Four Big Numbers</a></li>
        <li><a href="#colors">Color Legend (read this)</a></li>
        <li><a href="#layout">How the Page Is Laid Out</a></li>
        <li><a href="#gens">Reading a Generator</a></li>
        <li><a href="#pods">Reading a Pod</a></li>
        <li><a href="#modals">Clicking In — What Each Pop-Up Shows</a></li>
        <li><a href="#logs">The Activity Logs</a></li>
        <li><a href="#controls">Look vs. Touch (what changes things)</a></li>
        <li><a href="#signals">Other Signals (weather, network, warnings)</a></li>
    </ul>
</div>

<!-- ============================================================ -->
<h2 id="connection">Is It Live? (top-of-page indicators)</h2>
<p>Before trusting anything on the page, glance at the connection dot near the
top:</p>
<ul>
<li><span class="swatch s-green"></span><strong>Green</strong> — Live. Data is
streaming, you're current.</li>
<li><span class="swatch s-yellow"></span><strong>Yellow</strong> —
Reconnecting. Hang on a moment.</li>
<li><span class="swatch s-red"></span><strong>Red</strong> — Connecting / not
connected. The page may be showing stale numbers.</li>
</ul>
<p>There's also a small <strong>Data Rate</strong> (KB/s) showing how much live
data is flowing — mostly a health indicator that the feed is alive.</p>

<!-- ============================================================ -->
<h2 id="summary">The Four Big Numbers</h2>
<p>The summary column shows four headline tiles — the fleet's vital signs. Each
tile header is <strong>clickable</strong> and opens a deeper view.</p>

<div class="cheat">
<table>
<tr><th>Tile</th><th>What it is</th><th>Unit</th></tr>
<tr><td><strong>Hashrate</strong></td>
    <td>Total mining output right now — the core "how much are we mining"
    number. Shows current vs. the max the installed miners could do, a fill bar,
    and a <strong>TX / ND</strong> regional split.</td>
    <td>PH/s (petahash/sec)</td></tr>
<tr><td><strong>Power</strong></td>
    <td>Total generator electrical output. Shows current vs. max capacity,
    spare capacity available, and efficiency in <strong>J/TH</strong> (energy
    per unit of hashing — lower is better).</td>
    <td>MW (megawatts)</td></tr>
<tr><td><strong>Gas</strong></td>
    <td>Natural gas the fleet is burning. Metered directly at sites with a
    flowmeter, estimated from gen power elsewhere.</td>
    <td>MCF/day (thousand cu ft)</td></tr>
<tr><td><strong>Miners</strong></td>
    <td>How many machines are hashing right now, out of the total installed,
    plus a breakdown of zero-hash / sleeping / offline.</td>
    <td>count</td></tr>
</table>
</div>

<p>If you only look at four things, look at these: are we mining (Hashrate),
are the gens carrying it (Power), is gas feeding them (Gas), and are the
machines healthy (Miners).</p>

<!-- ============================================================ -->
<h2 id="colors">Color Legend (read this)</h2>
<p>The same colors mean the same thing everywhere on the page — on gen dots,
miner squares, kW bars, and counts. Learn these once and the whole page reads
faster.</p>

<div class="cheat">
<table>
<tr><th>Color</th><th>Means</th></tr>
<tr><td><span class="swatch s-green"></span>Green</td>
    <td>Good — online, hashing, healthy. Also a wake action in logs.</td></tr>
<tr><td><span class="swatch s-blue"></span>Blue</td>
    <td>Sleeping miners, or a gen running <em>below</em> its target load.</td></tr>
<tr><td><span class="swatch s-orange"></span>Orange</td>
    <td>Attention — a <strong>stuck</strong> gen (says "Running" but its data is
    &gt;30 min old), an over-target/"hot" gen, or a low-performing miner.</td></tr>
<tr><td><span class="swatch s-red"></span>Red</td>
    <td>Bad — offline, down, or zero-hash. Also a sleep action in logs.</td></tr>
<tr><td><span class="swatch s-yellow"></span>Yellow</td>
    <td>Warning (a reboot action in logs).</td></tr>
<tr><td><span class="swatch s-purple"></span>Purple</td>
    <td>A miner with a dead hashboard (a "pull" candidate); fix-pools action in
    logs.</td></tr>
<tr><td><span class="swatch s-white"></span>White</td>
    <td>An offline miner square in the grids.</td></tr>
<tr><td><span class="swatch s-grey"></span>Grey</td>
    <td>Disabled, secondary, or stale/unknown.</td></tr>
</table>
</div>

<!-- ============================================================ -->
<h2 id="layout">How the Page Is Laid Out</h2>
<p>Top to bottom, the page is organized <strong>Sites → Generator Groups →
Pods</strong>, with generators and miners shown side by side so you can see
capacity vs. load together.</p>

<h3>Sites Overview strip (top)</h3>
<p>One card per site. Each card has a row of <strong>gen dots</strong> (one per
generator, colored by health) and a <strong>pod pixel-map</strong> — each pod is
a tiny picture where every miner slot is a single colored pixel. From across the
room you can tell a healthy site (mostly green) from a hurting one (red/orange).
Click a site card to open its full drill-down.</p>

<h3>The columns</h3>
<p>Below the strip the page splits into columns:</p>
<ul>
<li><strong>Peps / Pods</strong> — the network routers (Peplinks) and the pods
under them, with each pod's live miner stats.</li>
<li><strong>Generators</strong>, split by region into <strong>TX</strong>,
<strong>NDS</strong> (Nate/Dan), and <strong>GW</strong> (GN/Will) — the gen
groups and their gens.</li>
<li><strong>Summary</strong> — the four big numbers, weather, the activity
logs, and notes.</li>
</ul>
<p>Each gen column header has a <strong>wrench
(<i class="fas fa-wrench ic ic-wrench"></i>) badge</strong> showing how many
out-of-service gens are parked there.</p>

<h3>Generator group boxes</h3>
<p>Gens are grouped into the units that share a pod's load. A group box
auto-expands when something's wrong (a gen down, off-target, or warning) and
collapses when it's healthy, so trouble surfaces itself. In each group you'll
see:</p>
<ul>
<li>The <strong>group name</strong> (click for charts) and a reorder handle.</li>
<li>The <strong>kW/gen target</strong> with a
<i class="fas fa-bolt ic ic-bolt"></i>bolt (e.g. "330 kW/gen") — this is the
per-gen load target. <em>Clicking it edits the target (a real change).</em></li>
<li>A capacity line: <strong>"Avail: X kW (N miners)"</strong> if there's room,
or <strong>"Over: X kW"</strong> if overloaded, plus a blue
<strong>"N sleeping"</strong> link.</li>
<li>A plain-English <strong>control blurb</strong> — what the automatic
sleep/wake engine is doing right now and why, with a countdown.</li>
<li>Four toggles: <span class="tag">R0</span> (auto-reboot dead miners),
<span class="tag">AS</span> (auto-sleep), <span class="tag">AW</span>
(auto-wake), <span class="tag">EMS</span> (emergency sleep). See the Power
Management guide for what these do.</li>
</ul>

<!-- ============================================================ -->
<h2 id="gens">Reading a Generator</h2>
<p>Each gen row packs a lot into a small space:</p>
<ul>
<li>A <strong>status dot</strong> (color per the legend) and the gen ID.</li>
<li>Icons: <i class="fas fa-wifi ic ic-wifi"></i><strong>wifi</strong> =
streaming live telemetry; <i class="fas fa-triangle-exclamation ic ic-warn"></i>
<strong>warning triangle</strong> = active alarm;
<i class="fas fa-bell-slash ic ic-mute"></i><strong>bell-slash</strong> = a
muted/ignored alarm; <i class="fas fa-circle-pause ic ic-hold"></i>
<strong>pause-circle</strong> = the gen is on a capacity hold (its headroom is
being reserved — see Power Management);
<i class="fas fa-location-dot ic ic-misplaced"></i><strong>purple pin</strong> =
the gen is in the wrong spot in one of our systems (see below).</li>
<li>Maintenance badges (Swap / Inspect / Parts / Gas / OOS / Loaner / Service,
"NO AS", and a self-fading "✓ Rep" after a repair).</li>
<li>On the right: if running, its <strong>gas pressure (PSI)</strong>, its
<strong>kW</strong> (colored — green on target, blue under, orange over), and an
up-timer. If stopped, a <strong>battery-voltage chip</strong> and the
down-reason.</li>
<li>A full-width <strong>kW bar</strong> on a fixed 0–380 scale so you can
compare gens at a glance. A down gen with telemetry shows a
<strong>battery bar</strong> instead, so you can watch a dead gen's battery
drain.</li>
</ul>
<p>Click a gen to open its action picker (data views, and — for permitted
users — gen control).</p>

<!-- ============================================================ -->
<h2 id="pods">Reading a Pod</h2>
<p>In the Peps/Pods column, each pod row reads like this:</p>
<p><code>● PodName - hashing/installed (notHashing) (sleeping) - hashrate</code></p>
<ul>
<li>The leading <strong>dot</strong> is green if any miner is hashing, red if
none are.</li>
<li><strong>hashing / installed</strong> — how many are mining out of how many
are physically there. The installed number is white if it came from inventory,
orange if it's a fallback guess.</li>
<li>The first <span style="color:#ff4444">(N)</span> in <strong>red</strong> =
zero-hash miners (there but not producing). The
<span style="color:#4a9eff">(N)</span> in <strong>blue</strong> = sleeping
miners.</li>
<li><strong>hashrate</strong> — the pod's output in PH/s.</li>
</ul>
<p>Peplink (router) rows also show a Starlink dish
(<i class="fas fa-satellite-dish ic ic-dish"></i>) icon for internet up/down.
Click a pod to open its detail/history.</p>

<!-- ============================================================ -->
<h2 id="modals">Clicking In — What Each Pop-Up Shows</h2>
<p>Almost everything on the page opens a focused pop-up. Here's what each one is
for.</p>

<h4>From the four big numbers</h4>
<ul>
<li><strong>Performance</strong> (Hashrate tile) — current vs. max, an all-sites
hashrate chart and a TX-vs-ND chart, per-site cards comparing <em>our</em>
measured hashrate against the <strong>Foundry pool's</strong> reported number,
and 24h history. Timeframe dropdown redraws the charts.</li>
<li><strong>Power</strong> (Power tile) — power totals, gens running/total,
available capacity, per-site MW, and 24h power history.</li>
<li><strong>Gas</strong> (Gas tile) — gas totals + yesterday's, per-site gas
(green wifi <i class="fas fa-wifi ic ic-wifi"></i> = real flowmeter vs.
estimate), a consumption chart, and a
gas-pressure chart.</li>
<li><strong>Miners</strong> (Miners tile) — Hashing / Sleeping / Zero-Hash /
Offline counts, history charts, and a per-pod breakdown table (all-offline pods
flagged red).</li>
</ul>

<h4>From the map elements</h4>
<ul>
<li><strong>Site modal</strong> (a site card) — the deep drill-down: every pod
drawn as a dense grid of colored miner squares. Hover a square for that miner's
detail; the problem-list view lets you filter by error type. This is where you
go to see exactly which machines are hurting at a site.</li>
<li><strong>Gen Group modal</strong> (a group name) — pick a metric (power,
current, gas pressure, coolant/intake temp, voltage, engine hours, energy) and
compare all gens in the group on one chart, plus the group's power-control
action log.</li>
<li><strong>Pod modal</strong> (a pod) — pod config, its Peplink LAN device
count, a hashrate chart, and a miner-status-over-time chart.</li>
<li><strong>Gen modal</strong> (a gen) — telemetry views (full Mesa data, our
live-ingest data with raw registers, and an animated schematic of the genset),
plus control actions for permitted users.</li>
</ul>

<h4>From the header indicator dots</h4>
<ul>
<li><strong>Scanner / Agent Monitor</strong> — health of our per-pod scanning
agents: who's scanning, miner counts, last scan, and a red <strong>CONFLICT</strong>
flag if the third-party Foreman scanner is fighting ours.</li>
<li><strong>Watcher / Pickaxe</strong> — a view of the third-party Foreman
scanner daemons and which pods they're probing.</li>
<li><strong>Services</strong> — a board of backend processes (APIs, background
services, field server) with running/stopped dots.</li>
</ul>

<!-- ============================================================ -->
<h2 id="logs">The Activity Logs</h2>
<p>At the bottom of the summary column are live logs, newest at the bottom:</p>
<ul>
<li><strong>Power Control Log</strong> — <em>manual</em> operator sleeps/wakes/
reboots, with the person's name. Green=wake, red=sleep, yellow=reboot.</li>
<li><strong>Miner Monitor Log</strong> — <em>automated</em> agent sweeps (no
user). Yellow=reboot, purple=fix-pools, cyan=fix-power.</li>
<li><strong>Automated Sleep/Wake Log</strong> — the power engine's own
<span class="tag">AS</span>/<span class="tag">AW</span> decisions. Green=wake,
red=sleep. If you want to know why miners went to sleep on their own, this is
the log.</li>
</ul>
<p>There's also a <strong>Miner Control</strong> panel listing pods with
sleeping miners or with automation toggled off, and a <strong>Notes</strong> box
for free-text team notes.</p>

<!-- ============================================================ -->
<h2 id="controls">Look vs. Touch (what changes things)</h2>
<p>New folks worry about breaking something by clicking. Almost nothing on the
page changes anything — opening tiles, cards, gens, pods, charts, and the header
dots are all just <em>views</em>. Only these actually do something, and most are
permission-gated:</p>

<div class="cheat">
<table>
<tr><th>Control</th><th>What it changes</th></tr>
<tr><td>kW/gen target (<i class="fas fa-bolt ic ic-bolt"></i> link)</td><td>Sets the per-gen load target for the group</td></tr>
<tr><td>R0 / AS / AW / EMS toggles</td><td>Turn automatic behaviors on/off for a pod</td></tr>
<tr><td>"N sleeping" → Miner Actions</td><td>Bulk sleeps or wakes miners</td></tr>
<tr><td>Gen Control buttons</td><td>Physically command a gen (Manual/Clear/Start/On Load) — see the Remote Gen Start guide</td></tr>
<tr><td>Add Note / Mark Repaired / status</td><td>Updates a gen's maintenance record</td></tr>
<tr><td>Move / Swap / reorder gen</td><td>Relocates or reorders a gen</td></tr>
<tr><td>Site modal Repair → Done</td><td>Logs a physical miner repair</td></tr>
<tr><td>Services Restart</td><td>Restarts a backend service (admins only)</td></tr>
</table>
</div>

<div class="callout good">
<span class="label">Rule of thumb</span>
<p>If a click opens a chart or a detail view, you can't hurt anything — explore
freely. If it's a toggle, a button, or an editable number, it's a real action.
When in doubt, ask before flipping toggles or hitting gen-control buttons.</p>
</div>

<!-- ============================================================ -->
<h2 id="signals">Other Signals (weather, network, warnings)</h2>
<ul>
<li><strong>Weather</strong> — per-location temp, high/low, conditions, and
humidity in the summary column (heat affects gen derating and miner temps).</li>
<li><strong>Gas pressure (PSI)</strong> — shown per gen and in the Gas modal;
low pressure upstream is an early warning of a gas problem.</li>
<li><strong>Network</strong> — Peplink router dots (green/red) and Starlink
<i class="fas fa-satellite-dish ic ic-dish"></i>dish up/down icons; per-pod LAN
device counts live in the Pod modal.</li>
<li><strong>Stuck gen</strong> — an <span class="swatch s-orange"></span>orange
gen dot means it claims "Running" but its data is over 30 minutes old, so it's
left out of the capacity math until it reports fresh.</li>
<li><strong>Warning <i class="fas fa-triangle-exclamation ic ic-warn"></i> /
hold <i class="fas fa-circle-pause ic ic-hold"></i> / muted
<i class="fas fa-bell-slash ic ic-mute"></i></strong> — active alarm,
reserved-capacity hold, and intentionally-ignored bad sensor, respectively.</li>
<li><strong>Wrong spot <i class="fas fa-location-dot ic ic-misplaced"></i></strong>
— Mesa has this gen at a different site than we do. Mesa is what decides where a
gen's alerts go, so this gen's down/up alerts are landing in the wrong site's
chat. Hover the pin to see both sides. It's a paperwork mismatch, not a fault
with the gen — and it's fixed on Mesa's side, not ours. The pin clears itself
once Mesa is corrected.</li>
</ul>

<div class="callout">
<span class="label">Where to go next</span>
<p>Once the page makes sense, read the <strong>How-To: Power Management</strong>
guide to understand the AS/AW/EMS toggles and what the system does on its own,
and <strong>How-To: Remote Gen Start</strong> if you'll be controlling gens.</p>
</div>

</div>

<script>__DROPDOWN_JS__</script>
</body>
</html>
"""

HTML = HTML.replace("__NAV_CSS__", _nav_css)
HTML = HTML.replace("__DROPDOWN_CSS__", "")
HTML = HTML.replace("__DROPDOWN_HTML__", _nav_html)
HTML = HTML.replace("__DROPDOWN_JS__", _nav_js)

print(HTML)
