<script lang="ts">
  import { api } from '@core/api.js'
  import { toast } from '@core/ui.js'

  // ---- State ----
  let status     = $state<any>(null)
  let setupOpen  = $state(false)
  let cockpitOpen   = $state(false)
  let cockpitLoading = $state(false)
  let agent      = $state<any>(null)
  let cronJobs   = $state<any[]>([])
  let skills     = $state<any[]>([])
  let pubkey     = $state('')

  // ---- Status laden ----
  async function loadStatus() {
    try { status = await api('/api/hermes/status') }
    catch { status = null }
  }

  async function loadPubkey() {
    try {
      const r = await api('/api/hermes/pubkey')
      pubkey = r.pubkey
    } catch { pubkey = '' }
  }

  // ---- Cockpit (Phase 4): Agent-Status, Cron, Skills ----
  async function loadCockpit() {
    cockpitLoading = true
    try {
      const [a, c, s] = await Promise.all([
        api('/api/hermes/agent'),
        api('/api/hermes/cron'),
        api('/api/hermes/skills'),
      ])
      agent    = a
      cronJobs = c.jobs   || []
      skills   = s.skills || []
    } catch { agent = null }
    cockpitLoading = false
  }

  // Skills sortiert: meistgenutzt zuerst, dann alphabetisch
  let skillsSorted = $derived(
    [...skills].sort((a, b) =>
      (b.use_count || 0) - (a.use_count || 0) || (a.name || '').localeCompare(b.name || ''))
  )
  let skillsEnabled = $derived(skills.filter(s => (s.status || '').includes('enabled')).length)

  function copyKey() {
    navigator.clipboard?.writeText(pubkey)
    toast('SSH-Key kopiert')
  }

  // ---- Boot ----
  $effect(() => {
    loadStatus()
  })
</script>

<!-- ==================== HEADER ==================== -->
<div class="pagehead" style="display:flex;justify-content:space-between;align-items:flex-start">
  <div>
    <h1>Hermes</h1>
    <div class="sub">Dein lokaler KI-Assistent — kennt den Bosgame, lernt mit.</div>
  </div>
  <div class="flex gap-2" style="flex-shrink:0;margin-top:6px;flex-wrap:wrap;align-items:center">
    <!-- Hermes-Status -->
    <span class="chip" style="font-size:11px;{status?.hermes === 'ready'
      ? 'color:#7ee29a;border-color:rgba(126,226,154,.4)'
      : 'color:#ff9b95;border-color:rgba(255,155,149,.4)'}">
      ● Agent: {status?.hermes === 'ready' ? 'online' : 'offline'}
    </span>
    <!-- Cockpit (Phase 4) -->
    <button class="ghost" style="padding:4px 10px;font-size:12px;{cockpitOpen ? 'border-color:var(--accent);color:var(--accent)' : ''}"
      onclick={() => { cockpitOpen = !cockpitOpen; if (cockpitOpen) loadCockpit() }}>
      📡 Cockpit
    </button>
    <!-- Setup -->
    <button class="ghost" style="padding:4px 10px;font-size:12px"
      onclick={() => { setupOpen = !setupOpen; if (setupOpen) { loadStatus(); loadPubkey() } }}>
      ⚙ Setup
    </button>
  </div>
</div>

<!-- ==================== COCKPIT (Phase 4) ==================== -->
{#if cockpitOpen}
  <div class="card" style="border-color:rgba(45,212,191,.3)">
    <div class="card-h" style="display:flex;justify-content:space-between;align-items:center">
      <h3>Agent-Cockpit</h3>
      <button class="ghost" style="font-size:11px;padding:2px 10px" onclick={loadCockpit}>
        {cockpitLoading ? '…' : '↻ Aktualisieren'}
      </button>
    </div>

    <!-- Agent-Status -->
    <div class="tile" style="margin-bottom:10px">
      <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px">
        <div>
          <b>Status</b>
          <div class="card-sub" style="font-size:12px">Hermes-Gateway-Dienst (:8642) auf dem Bosgame</div>
        </div>
        <div class="flex gap-2" style="flex-wrap:wrap;align-items:center">
          <span class="chip" style="font-size:11px;{agent?.gateway_state === 'running'
            ? 'color:#7ee29a;border-color:rgba(126,226,154,.4)' : 'color:#ff9b95;border-color:rgba(255,155,149,.4)'}">
            ● {agent?.gateway_state ?? 'offline'}
          </span>
          <span class="chip" style="font-size:11px;{agent?.cron_running
            ? 'color:var(--accent);border-color:var(--accent)' : 'color:var(--mut)'}">
            ⏱ Scheduler {agent?.cron_running ? 'läuft' : 'inaktiv'}
          </span>
          {#if agent?.heartbeat_age_s != null}
            <span class="chip" style="font-size:11px;color:var(--mut)">Ticker vor {agent.heartbeat_age_s}s</span>
          {/if}
          {#if agent?.version}
            <span class="chip" style="font-size:11px;color:var(--mut)" title={agent.version}>{agent.version.split(' · ')[0]}</span>
          {/if}
        </div>
      </div>
    </div>

    <!-- Cron-Scheduler -->
    <div class="tile" style="margin-bottom:10px">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px">
        <b>Geplante Aufgaben <span class="card-sub" style="font-size:11px">({cronJobs.length})</span></b>
      </div>
      {#if cronJobs.length === 0}
        <div class="card-sub" style="font-size:12px">
          Keine geplanten Jobs. Hermes kann selbst welche anlegen — sag ihm z. B.
          „Erinnere mich jeden Morgen um 9 Uhr an die offenen Modell-Upgrades".
        </div>
      {:else}
        <div style="display:flex;flex-direction:column;gap:6px">
          {#each cronJobs as job}
            <div style="display:flex;align-items:center;gap:8px;font-size:12.5px;
                        padding:6px 8px;background:rgba(255,255,255,.02);border-radius:6px">
              {#each Object.entries(job) as [k, v]}
                {#if v}<span style="color:var(--mut)"><span style="opacity:.6">{k}:</span> {v}</span>{/if}
              {/each}
            </div>
          {/each}
        </div>
      {/if}
    </div>

    <!-- Skills -->
    <div class="tile">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px">
        <b>Skills <span class="card-sub" style="font-size:11px">({skillsEnabled} aktiv von {skills.length})</span></b>
      </div>
      {#if skills.length === 0}
        <div class="card-sub" style="font-size:12px">Keine Skills geladen (oder Agent offline).</div>
      {:else}
        <div style="max-height:260px;overflow-y:auto;display:flex;flex-direction:column;gap:3px">
          {#each skillsSorted as s}
            <div style="display:flex;align-items:center;gap:8px;font-size:12.5px;padding:4px 8px;
                        border-radius:6px;{(s.status || '').includes('enabled') ? '' : 'opacity:.45'}">
              <span style="width:7px;height:7px;border-radius:50%;flex-shrink:0;
                background:{(s.status || '').includes('enabled') ? 'var(--accent)' : 'var(--mut)'}"></span>
              <span style="font-weight:500">{s.name}</span>
              {#if s.category}<span class="card-sub" style="font-size:11px">{s.category}</span>{/if}
              <span style="flex:1"></span>
              {#if s.use_count > 0}
                <span class="chip" style="font-size:10px;color:var(--accent);border-color:rgba(45,212,191,.3)">
                  {s.use_count}× genutzt
                </span>
              {/if}
              <span class="card-sub" style="font-size:10px">{s.source}</span>
            </div>
          {/each}
        </div>
      {/if}
    </div>
  </div>
{/if}

<!-- ==================== SETUP-WIZARD ==================== -->
{#if setupOpen}
  <div class="card" style="border-color:rgba(45,212,191,.3)">
    <div class="card-h"><h3>Hermes Setup-Wizard</h3></div>

    <!-- Whisper -->
    <div class="tile" style="margin-bottom:10px">
      <div style="display:flex;justify-content:space-between;align-items:center">
        <div>
          <b>Whisper (Sprache → Text)</b>
          <div class="card-sub" style="font-size:12px">faster-whisper muss auf dem Bosgame installiert sein</div>
        </div>
        <span class="chip" style="font-size:11px;{status?.whisper !== 'not_installed' ? 'color:#7ee29a' : 'color:#ff9b95'}">
          {status?.whisper !== 'not_installed' ? '✓ OK' : '✗ fehlt'}
        </span>
      </div>
      {#if status?.whisper === 'not_installed'}
        <div class="log" style="margin-top:8px"><code>pip install faster-whisper</code></div>
      {/if}
    </div>

    <!-- Piper -->
    <div class="tile" style="margin-bottom:10px">
      <div style="display:flex;justify-content:space-between;align-items:center">
        <div>
          <b>Piper TTS (Text → Sprache)</b>
          <div class="card-sub" style="font-size:12px">Piper-Binary + deutsche Stimme</div>
        </div>
        <span class="chip" style="font-size:11px;{status?.piper === 'ready' ? 'color:#7ee29a' : 'color:#ff9b95'}">
          {status?.piper === 'ready' ? '✓ OK' : '✗ fehlt'}
        </span>
      </div>
      {#if status?.piper !== 'ready'}
        <div class="log" style="margin-top:8px"><code>{[
          '# 1. Piper Binary (Linux x86_64)',
          'mkdir -p /opt/mission-control/piper/voices',
          'cd /tmp && wget -q https://github.com/rhasspy/piper/releases/download/2023.11.14-2/piper_linux_x86_64.tar.gz',
          'tar -xzf piper_linux_x86_64.tar.gz -C /opt/mission-control/piper/ --strip-components=1',
          '',
          '# 2. Deutsche Stimme — Kerstin (weiblich, ~25 MB)',
          'wget -q -O /opt/mission-control/piper/voices/de_DE-kerstin-low.onnx \\',
          '  "https://huggingface.co/rhasspy/piper-voices/resolve/v1.0.0/de/de_DE/kerstin/low/de_DE-kerstin-low.onnx"',
          'wget -q -O /opt/mission-control/piper/voices/de_DE-kerstin-low.onnx.json \\',
          '  "https://huggingface.co/rhasspy/piper-voices/resolve/v1.0.0/de/de_DE/kerstin/low/de_DE-kerstin-low.onnx.json"',
        ].join('\n')}</code></div>
      {/if}
    </div>

    <!-- Windows SSH -->
    <div class="tile">
      <div style="display:flex;justify-content:space-between;align-items:center">
        <div>
          <b>Windows SSH-Verbindung</b>
          <div class="card-sub" style="font-size:12px">Damit Hermes Dateien auf deinem Windows-PC ändern kann</div>
        </div>
        <span class="chip" style="font-size:11px;{status?.ssh_ok ? 'color:#7ee29a' : 'color:var(--mut)'}">
          {status?.ssh_ok ? '✓ verbunden' : 'optional'}
        </span>
      </div>

      {#if !status?.ssh_ok}
        <div style="margin-top:12px">
          <div style="font-size:12.5px;font-weight:500;margin-bottom:8px">Einrichtung (einmalig, ~3 Minuten):</div>

          <div style="margin-bottom:8px">
            <div class="card-sub" style="font-size:11.5px;margin-bottom:4px">1. PowerShell als Admin — OpenSSH Server installieren:</div>
            <div class="log"><code>Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0</code></div>
          </div>

          <div style="margin-bottom:8px">
            <div class="card-sub" style="font-size:11.5px;margin-bottom:4px">2. Dienst starten und dauerhaft aktivieren:</div>
            <div class="log"><code>{"Start-Service sshd\nSet-Service -Name sshd -StartupType Automatic"}</code></div>
          </div>

          <div style="margin-bottom:8px">
            <div class="card-sub" style="font-size:11.5px;margin-bottom:4px">3. SSH-Ordner erstellen:</div>
            <div class="log"><code>{"New-Item -ItemType Directory -Force -Path \"$env:USERPROFILE\\.ssh\""}</code></div>
          </div>

          {#if pubkey}
            <div style="margin-bottom:8px">
              <div class="card-sub" style="font-size:11.5px;margin-bottom:4px">4. Bosgame-Key eintragen (in Windows PowerShell):</div>
              <div style="position:relative">
                <button class="ghost" style="position:absolute;top:6px;right:6px;font-size:11px;padding:2px 8px;z-index:1"
                  onclick={copyKey}>Kopieren</button>
                <div class="log"><code>{"echo \"" + pubkey + "\" >> \"$env:USERPROFILE\\.ssh\\authorized_keys\""}</code></div>
              </div>
            </div>
          {:else}
            <div class="card-sub" style="font-size:11.5px">SSH-Key nicht gefunden — bitte auf dem Bosgame generieren:
              <code style="display:block;margin-top:4px">ssh-keygen -t ed25519 -C "hermes-agent@bosgame" -f ~/.ssh/id_ed25519_hermes_agent -N ""</code>
            </div>
          {/if}

          <div style="margin-bottom:8px">
            <div class="card-sub" style="font-size:11.5px;margin-bottom:4px">5. Windows-IP in Mission Control Env-Var setzen:</div>
            <div class="log"><code>HERMES_WINDOWS_HOST=192.168.178.XXX</code></div>
          </div>

          <button class="primary" style="margin-top:4px" onclick={() => { loadStatus(); toast('Status aktualisiert') }}>
            Verbindung testen
          </button>
        </div>
      {/if}
    </div>
  </div>
{/if}

<!-- ==================== CHAT (eingebettetes Hermes-Web-Dashboard) ==================== -->
<div class="card" style="padding:0;overflow:hidden">
  {#if status?.hermes === 'ready'}
    <iframe
      title="Hermes Chat"
      src="/hermes-ui/"
      style="width:100%;height:calc(100vh - 210px);min-height:540px;border:0;display:block;background:#0f1720"
    ></iframe>
  {:else}
    <div class="empty-c" style="padding:48px 24px">
      <div class="e-t">Hermes-Agent offline</div>
      <div class="e-s">Der Hermes-Gateway (:8642) bzw. das Dashboard (:9119) ist nicht erreichbar.
        Status im Cockpit prüfen oder den Dienst neu starten.</div>
    </div>
  {/if}
</div>
