{% extends "base.html" %}
{% block extra_head %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<link rel="stylesheet" href="/static/css/ops-topology.css?v=3" />
<link rel="stylesheet" href="/static/css/herman-dashboard.css?v=13" />
{% endblock %}
{% block content %}
<div class="ops-shell hm-neo" x-data="opsPage()" x-init="init()">
  <header class="ops-header herman-hero">
    <div>
      <h1>IT Ops · Dell R340 <span class="live-badge">Live</span></h1>
      <p class="hero-sub">PowerEdge R340 → Proxmox VE → VM 106 → online services · SysOps agent</p>
    </div>
    <div class="btn-group">
      <button class="btn btn-sm btn-pulse" @click="refresh()" :disabled="loading">↻ Verversen</button>
      <button class="btn btn-sm btn-pulse-green" @click="snapshot()" :disabled="loading">Snapshot</button>
      <a href="/agents?tab=approvals" class="btn btn-sm btn-pulse-purple">Goedkeuringen →</a>
    </div>
  </header>

  <div id="viz-toolbar" class="viz-toolbar"></div>
  <div class="hm-dash-two-col" style="margin-bottom:1rem">
    <div class="hm-chart-panel page-viz-panel viz-mode-chart">
      <div class="hm-chart-head"><h4>Maintenance severity</h4><small>open items</small></div>
      <div class="page-viz-body">
        <div class="hm-chart-wrap page-viz-canvas"><canvas id="chart-ops-maint"></canvas></div>
        <div id="viz-ops-maint-alt" class="viz-alt"></div>
      </div>
    </div>
    <div class="hm-chart-panel page-viz-panel viz-mode-chart">
      <div class="hm-chart-head"><h4>Backup status</h4><small>Gitea commits</small></div>
      <div class="page-viz-body">
        <div class="hm-chart-wrap page-viz-canvas"><canvas id="chart-ops-backup"></canvas></div>
        <div id="viz-ops-backup-alt" class="viz-alt"></div>
      </div>
    </div>
  </div>

  <section class="ops-kpis hm-neo-kpi-row" style="grid-template-columns:repeat(5,1fr)">
    <div class="hm-neo-kpi"><div class="hm-neo-kpi-label">Health</div><div class="hm-neo-kpi-value" x-text="summary.health || '—'"></div><div class="hm-eq"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></div></div>
    <div class="hm-neo-kpi"><div class="hm-neo-kpi-label">Online nodes</div><div class="hm-neo-kpi-value" x-text="summary.counts?.online ?? 0"></div><div class="hm-eq hm-eq-lime"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></div></div>
    <div class="hm-neo-kpi"><div class="hm-neo-kpi-label">Services</div><div class="hm-neo-kpi-value" x-text="meta.services_online ?? '—'"></div><div class="hm-eq hm-eq-cyan"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></div></div>
    <div class="hm-neo-kpi"><div class="hm-neo-kpi-label">Open maintenance</div><div class="hm-neo-kpi-value" x-text="maintenance.length"></div><div class="hm-eq hm-eq-purple"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></div></div>
    <div class="hm-neo-kpi"><div class="hm-neo-kpi-label">Laatste backup</div><div class="hm-neo-kpi-value" style="font-size:0.95rem" x-text="lastBackupLabel()"></div><div class="hm-eq"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></div></div>
  </section>

  <div class="ops-panels-grid">
    <section class="panel ops-side-panel">
      <h2>Maintenance · SysOps</h2>
      <p class="page-tip">Dagelijks scan — updates, schijf, Docker health</p>
      <template x-if="!maintenance.length">
        <p class="empty-state">Geen open items 🎉</p>
      </template>
      <div class="ops-maint-list">
        <template x-for="n in maintenance" :key="n.id">
          <div class="ops-maint-item" :class="'sev-'+(n.severity||'info')">
            <strong x-text="n.title"></strong>
            <small x-text="(n.created_at||'').substring(0,16).replace('T',' ')"></small>
            <p x-text="n.body" x-show="n.body"></p>
          </div>
        </template>
      </div>
    </section>

    <section class="panel ops-side-panel">
      <h2>Config backups · Gitea</h2>
      <p class="page-tip">SysOps vraagt dagelijks goedkeuring — na ✓ push naar Gitea</p>
      <template x-if="pendingBackup">
        <div class="ops-maint-item sev-warning">
          <strong>⏳ Wacht op goedkeuring</strong>
          <p x-text="pendingBackup.title"></p>
          <a href="/agents?tab=approvals" class="btn btn-sm btn-pulse-green">Keur goed →</a>
        </div>
      </template>
      <div class="ops-maint-list">
        <template x-for="b in backups.slice(0,5)" :key="b.id">
          <div class="ops-maint-item" :class="b.status==='success'?'sev-info':'sev-warning'">
            <strong x-text="b.status + (b.commit_ref ? ' · '+b.commit_ref : '')"></strong>
            <small x-text="(b.created_at||'').substring(0,16).replace('T',' ')"></small>
            <p x-text="b.message"></p>
          </div>
        </template>
      </div>
      <a href="http://10.4.7.18:3001/aissa/foodlinkk-command-center" target="_blank" rel="noopener" class="btn btn-sm" style="margin-top:0.5rem">Gitea repo →</a>
    </section>

    <section class="panel ops-side-panel" style="grid-column:1/-1">
      <h2>SysOps verslag · activiteitenlog</h2>
      <p class="page-tip">Elke deploy, Gitea-push en maintenance-scan — Herman leest dit in de dagelijkse briefing.</p>
      <div class="ops-maint-list">
        <template x-for="a in sysopsActivity" :key="a.id">
          <div class="ops-maint-item" :class="a.status==='success'?'sev-info':'sev-warning'">
            <strong x-text="a.title"></strong>
            <small x-text="(a.action_type||'')+' · '+(a.created_at||'').substring(0,16).replace('T',' ')"></small>
            <p x-text="a.body" x-show="a.body"></p>
            <small x-show="a.commit_ref" style="color:#38bdf8" x-text="'commit '+a.commit_ref"></small>
          </div>
        </template>
      </div>
      <p x-show="!sysopsActivity.length" class="empty-state">Nog geen SysOps-activiteit gelogd.</p>
    </section>
  </div>

  <section class="panel topology-card">
    <div class="ops-legend">
      <span><i class="dot dot-online"></i> Online / bereikbaar</span>
      <span><i class="dot dot-degraded"></i> Onbekend</span>
      <span><i class="dot dot-offline"></i> Offline</span>
      <span>Klik service-node → opent URL</span>
    </div>
    <svg id="ops-topology-canvas" viewBox="0 0 1200 620" class="topology-canvas"></svg>
  </section>

  <p class="ops-meta">Last update: <span id="ops-meta-time">—</span></p>
</div>
{% endblock %}
{% block scripts %}
<script src="/static/js/dashboard-layout.js?v=2"></script>
<script src="/static/js/page-viz.js?v=1"></script>
<script src="/static/js/ops-topology.js?v=3"></script>
<script>
function opsPage() {
  return {
    loading: false,
    summary: { counts: {} },
    meta: {},
    maintenance: [],
    backups: [],
    sysopsActivity: [],
    pendingBackup: null,
    timer: null,
    renderViz(mode) {
      if (!window.VizEngine) return;
      const sevMap = {};
      (this.maintenance || []).forEach(n => {
        const s = n.severity || 'info';
        sevMap[s] = (sevMap[s] || 0) + 1;
      });
      let sevRows = Object.keys(sevMap).map(k => ({ label: k, value: sevMap[k], raw: sevMap[k] }));
      if (!sevRows.length) sevRows = [{ label: 'ok', value: 0, raw: 0 }];
      VizEngine.renderFromRows(mode,
        document.getElementById('chart-ops-maint'),
        document.getElementById('viz-ops-maint-alt'),
        'ops-maint', 'Maintenance', sevRows, 'hm-eq-purple'
      );
      const stMap = {};
      (this.backups || []).forEach(b => {
        const s = b.status || 'unknown';
        stMap[s] = (stMap[s] || 0) + 1;
      });
      let stRows = Object.keys(stMap).map(k => ({ label: k, value: stMap[k], raw: stMap[k] }));
      if (!stRows.length) stRows = [{ label: 'geen', value: 0, raw: 0 }];
      VizEngine.renderFromRows(mode,
        document.getElementById('chart-ops-backup'),
        document.getElementById('viz-ops-backup-alt'),
        'ops-backup', 'Backups', stRows, 'hm-eq-cyan'
      );
    },
    async init() {
      await this.loadAll();
      await this.draw();
      if (window.PageViz) {
        window.PageViz.init('ops', (mode) => this.renderViz(mode));
      }
      this.timer = setInterval(() => this.refresh(false), 30000);
    },
    lastBackupLabel() {
      const ok = this.backups.find(b => b.status === 'success');
      if (!ok) return '—';
      return (ok.commit_ref || ok.status) + ' · ' + (ok.created_at || '').substring(0, 10);
    },
    async loadAll() {
      await Promise.all([this.loadStatus(), this.loadMaintenance(), this.loadBackups(), this.loadSysopsActivity(), this.loadPendingApproval()]);
      this.renderViz(window.__vizMode || 'neo-bars');
    },
    async loadStatus() {
      try {
        const data = await fetch('/api/ops/status').then(r => r.json());
        this.summary = data || { counts: {} };
        this.meta = (data.topology && data.topology.meta) || data.sources || {};
      } catch (e) { console.warn(e); }
    },
    async loadMaintenance() {
      try {
        const r = await fetch('/api/ops/maintenance?limit=12').then(x => x.json());
        this.maintenance = (r.items || []).filter(n => !n.resolved);
      } catch (e) { this.maintenance = []; }
    },
    async loadBackups() {
      try {
        const r = await fetch('/api/ops/backups?limit=8').then(x => x.json());
        this.backups = r.items || [];
      } catch (e) { this.backups = []; }
    },
    async loadSysopsActivity() {
      try {
        const r = await fetch('/api/ops/sysops-activity?limit=20').then(x => x.json());
        this.sysopsActivity = r.items || [];
      } catch (e) { this.sysopsActivity = []; }
    },
    async loadPendingApproval() {
      try {
        const r = await fetch('/api/agents/approvals?status=pending&limit=20').then(x => x.json());
        this.pendingBackup = (r.items || []).find(i => i.agent_key === 'sysops' && i.action_type === 'config_backup') || null;
      } catch (e) { this.pendingBackup = null; }
    },
    async draw() {
      if (window.OpsTopology) {
        await window.OpsTopology.render('ops-topology-canvas', document.getElementById('ops-meta-time'));
      }
    },
    async refresh(toast) {
      this.loading = true;
      try {
        await this.loadAll();
        await this.draw();
        if (toast !== false && window.Cockpit) Cockpit.toast('IT Ops bijgewerkt', 'success');
      } finally { this.loading = false; }
    },
    async snapshot() {
      this.loading = true;
      try {
        await fetch('/api/ops/refresh', { method: 'POST' });
        await this.refresh(false);
        if (window.Cockpit) Cockpit.toast('Infra snapshot opgeslagen', 'success');
      } catch (e) {
        if (window.Cockpit) Cockpit.toast('Snapshot mislukt', 'error');
      } finally { this.loading = false; }
    },
  };
}
</script>
{% endblock %}
