{% extends 'base.html' %}
{% block title %}Audit Qualys Agent — {{ hostname }}{% endblock %}
{% block content %}

{% if audit_status == 'pending' %}
<meta http-equiv="refresh" content="3">
{% endif %}

{% if audit_status == 'unsupported' %}
<div class="card p-6 mb-4 text-center" style="border:1px solid #6b7280;background:rgba(107,114,128,0.08)">
    <div class="text-cyber-yellow font-bold text-sm mb-2">⚠ Audit non géré</div>
    <p class="text-xs text-gray-400">
        L'audit SSH ciblé n'est disponible que pour les serveurs <strong>Linux</strong>.<br>
        Ce serveur est détecté comme <strong>Windows</strong> ({{ asset_os or '?' }}).
    </p>
    <a href="/qualys/agents#inactive-list" class="btn-sm bg-cyber-border text-gray-300 px-3 py-2 text-xs mt-3 inline-block">← Retour</a>
</div>
{% else %}

<div class="flex justify-between items-center mb-4">
    <div>
        <h2 class="text-xl font-bold text-cyber-accent">Audit Qualys Agent</h2>
        <p class="text-xs text-gray-500 mt-1 font-mono">{{ hostname }}{% if audit and audit.resolved_fqdn %} → {{ audit.resolved_fqdn }}{% endif %}</p>
    </div>
    <div style="display:flex;gap:8px">
        <a href="/qualys/agents/{{ hostname }}/audit-qualys?refresh=1" class="btn-sm bg-cyber-border text-gray-300 px-3 py-2 text-xs">Relancer</a>
        <a href="/qualys/agents#inactive-list" class="btn-sm bg-cyber-border text-gray-300 px-3 py-2 text-xs">← Retour</a>
    </div>
</div>

{% if audit_status == 'pending' %}
<!-- Bandeau "audit en cours" -->
<div class="card p-4 mb-4" style="border:1px solid #f59e0b;background:rgba(245,158,11,0.08)">
    <div class="flex items-center gap-3 text-sm">
        <svg style="width:24px;height:24px;animation:spin 1s linear infinite" viewBox="0 0 24 24" fill="none" stroke="#f59e0b" stroke-width="2">
            <circle cx="12" cy="12" r="10" stroke-opacity="0.3"/><path d="M12 2a10 10 0 0 1 10 10" stroke-linecap="round"/>
        </svg>
        <div>
            <span class="font-bold text-cyber-yellow">⏳ Audit en cours…</span>
            <span class="text-xs text-gray-400 ml-2">Connexion SSH + collecte status, version, logs (10–30s typique)</span>
            <div class="text-xs text-gray-500 mt-1">Démarré : {{ audit_started_at.strftime('%H:%M:%S') if audit_started_at else '?' }} — page rafraichie auto toutes les 3s</div>
        </div>
    </div>
</div>
<style>@keyframes spin{to{transform:rotate(360deg)}}</style>

{% elif audit_status == 'error' %}
<div class="card p-4 mb-4" style="border:1px solid #ef4444;background:rgba(239,68,68,0.08)">
    <span class="font-bold text-cyber-red">✗ Erreur audit</span>
    <pre style="background:#0b0f1a;color:#e5e7eb;padding:10px;border-radius:4px;font-size:11px;margin-top:8px;white-space:pre-wrap">{{ audit_error or '(pas de détail)' }}</pre>
</div>

{% else %}

<!-- Bandeau statut connexion -->
<div class="card p-3 mb-4" style="
    {% if audit.status == 'OK' %}border:1px solid #22c55e;background:rgba(34,197,94,0.08);
    {% elif audit.status == 'CONNECTION_FAILED' %}border:1px solid #ef4444;background:rgba(239,68,68,0.08);
    {% else %}border:1px solid #f59e0b;background:rgba(245,158,11,0.08);{% endif %}">
    <div class="flex justify-between items-center text-xs">
        <div>
            <span class="font-bold {% if audit.status == 'OK' %}text-cyber-green{% elif audit.status == 'CONNECTION_FAILED' %}text-cyber-red{% else %}text-cyber-yellow{% endif %}">
                {% if audit.status == 'OK' %}✓ Connecté{% elif audit.status == 'CONNECTION_FAILED' %}✗ Connexion échouée{% else %}⚠ {{ audit.status }}{% endif %}
            </span>
            <span class="text-gray-400 ml-3">{{ audit.connection_method or '-' }}</span>
            {% if audit.error_msg %}<span class="text-cyber-red ml-3">{{ audit.error_msg }}</span>{% endif %}
        </div>
        <span class="text-gray-500 font-mono">{{ audit.audit_date }}</span>
    </div>
</div>

{% if audit.status == 'OK' %}

<!-- État (checklist binaire) -->
<div class="card p-4 mb-4">
    <h3 class="text-sm font-bold text-cyber-accent mb-3">État</h3>
    <table class="w-full text-xs">
        <tr><td class="p-1">Connectivité Qualys</td><td class="p-1 text-right">{% if audit.check_connectivity %}<span class="text-cyber-green font-bold">✓ OK</span>{% else %}<span class="text-cyber-red font-bold">✗ KO</span>{% endif %}</td></tr>
        <tr><td class="p-1">Espace disque</td><td class="p-1 text-right">{% if audit.check_disk %}<span class="text-cyber-green font-bold">✓ OK</span>{% else %}<span class="text-cyber-red font-bold">✗ KO</span> <span class="text-gray-400 ml-2">{{ audit.disk_saturated_line }}</span>{% endif %}</td></tr>
        <tr><td class="p-1">Service Qualys</td><td class="p-1 text-right">{% if audit.check_service %}<span class="text-cyber-green font-bold">✓ OK</span>{% else %}<span class="text-cyber-red font-bold">✗ KO</span>{% endif %}</td></tr>
        <tr><td class="p-1">Agent installé</td><td class="p-1 text-right">{% if audit.check_installed %}<span class="text-cyber-green font-bold">✓ OK</span>{% else %}<span class="text-cyber-red font-bold">✗ KO</span>{% endif %}</td></tr>
    </table>
</div>

{% if audit.suggestions %}
<!-- Diagnostic -->
<div class="card p-4 mb-4" style="border:1px solid #00ffc8;background:rgba(0,255,200,0.05)">
    <h3 class="text-sm font-bold text-cyber-accent mb-3">🔍 Diagnostic ({{ audit.suggestions|length }} problème(s) détecté(s))</h3>
    <div style="display:flex;flex-direction:column;gap:10px">
    {% for s in audit.suggestions %}
        <div style="border-left:3px solid {% if s.severity == 'critical' %}#ef4444{% elif s.severity == 'high' %}#f97316{% elif s.severity == 'medium' %}#f59e0b{% else %}#3b82f6{% endif %};padding:8px 12px;background:#0b0f1a;border-radius:4px">
            <div class="flex items-center gap-2 mb-1">
                <span class="badge {% if s.severity == 'critical' %}badge-red{% elif s.severity == 'high' %}badge-red{% elif s.severity == 'medium' %}badge-yellow{% else %}badge-gray{% endif %}" style="font-size:9px">{{ s.severity|upper }}</span>
                <span class="text-cyber-accent font-bold text-xs">{{ s.title }}</span>
            </div>
            <pre style="color:#d1d5db;font-size:11px;white-space:pre-wrap;margin:0">{{ s.fix }}</pre>
        </div>
    {% endfor %}
    </div>
    <div class="mt-3 pt-3" style="border-top:1px solid #1f2937">
        <p class="text-xs text-gray-400">
            <span class="text-cyber-accent font-bold">→ Proposition :</span>
            ces constats sont basés sur les sorties d'audit, à valider en contexte. Ouvrir un ticket support
            avec une capture/PDF de cette page pour analyse et action côté équipe en charge.
        </p>
    </div>
</div>
{% endif %}

<!-- OS détecté -->
<div class="card p-4 mb-4">
    <h3 class="text-sm font-bold text-cyber-accent mb-2">OS détecté</h3>
    <pre style="background:#0b0f1a;color:#e5e7eb;padding:10px;border-radius:4px;font-size:11px;overflow-x:auto;white-space:pre-wrap">{{ audit.os_release or '(vide)' }}</pre>
</div>

<!-- Statut du service -->
<div class="card p-4 mb-4">
    <h3 class="text-sm font-bold text-cyber-accent mb-2">État du service <code class="text-cyber-yellow">qualys-cloud-agent</code></h3>
    <pre style="background:#0b0f1a;color:#e5e7eb;padding:10px;border-radius:4px;font-size:11px;overflow-x:auto;white-space:pre-wrap">{{ audit.agent_status or '(vide)' }}</pre>
</div>

<!-- Version agent -->
<div class="card p-4 mb-4">
    <h3 class="text-sm font-bold text-cyber-accent mb-2">Version agent</h3>
    <pre style="background:#0b0f1a;color:#e5e7eb;padding:10px;border-radius:4px;font-size:11px;overflow-x:auto;white-space:pre-wrap">{{ audit.agent_version or '(vide)' }}</pre>
</div>

<!-- Espace disque -->
<div class="card p-4 mb-4">
    <h3 class="text-sm font-bold text-cyber-accent mb-2">Espace disque</h3>
    <pre id="disk-pre" style="background:#0b0f1a;color:#e5e7eb;padding:10px;border-radius:4px;font-size:11px;overflow-x:auto;white-space:pre-wrap">{{ audit.disk_space or '(vide)' }}</pre>
</div>
<script>
(function(){
    var pre = document.getElementById('disk-pre');
    if(!pre) return;
    var lines = pre.textContent.split('\n');
    var html = lines.map(function(l){
        var m = l.match(/\s(\d{2,3})%\s/);
        if(m){
            var pct = parseInt(m[1]);
            var esc = l.replace(/[&<>]/g, function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;'}[c];});
            if(pct >= 90){
                return '<span style="color:#ef4444;font-weight:bold">' + esc + '</span>';
            } else if(pct >= 75){
                return '<span style="color:#f59e0b">' + esc + '</span>';
            }
        }
        return l.replace(/[&<>]/g, function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;'}[c];});
    }).join('\n');
    pre.innerHTML = html;
})();
</script>

<!-- LVM info -->
<div class="card p-4 mb-4">
    <h3 class="text-sm font-bold text-cyber-accent mb-2">LVM (Volume Groups + LV log/var)</h3>
    <pre style="background:#0b0f1a;color:#e5e7eb;padding:10px;border-radius:4px;font-size:11px;overflow-x:auto;white-space:pre-wrap">{{ audit.lvm_info or '(vide)' }}</pre>
</div>

<!-- Logrotate config -->
<div class="card p-4 mb-4">
    <h3 class="text-sm font-bold text-cyber-accent mb-2">Configuration logrotate Qualys</h3>
    <pre style="background:#0b0f1a;color:#e5e7eb;padding:10px;border-radius:4px;font-size:11px;overflow-x:auto;white-space:pre-wrap">{{ audit.logrotate_config or '(vide)' }}</pre>
</div>

<!-- Connectivité console Qualys -->
<div class="card p-4 mb-4">
    <h3 class="text-sm font-bold text-cyber-accent mb-2">Connectivité console Qualys</h3>
    <pre style="background:#0b0f1a;color:#e5e7eb;padding:10px;border-radius:4px;font-size:11px;overflow-x:auto;white-space:pre-wrap">{{ audit.qualys_connectivity or '(vide)' }}</pre>
</div>

<!-- Log agent Qualys -->
<div class="card p-4 mb-4">
    <h3 class="text-sm font-bold text-cyber-accent mb-2">Log agent Qualys (50 dernières lignes)</h3>
    <pre style="background:#0b0f1a;color:#e5e7eb;padding:10px;border-radius:4px;font-size:11px;overflow-x:auto;max-height:400px;white-space:pre-wrap">{{ audit.agent_log or '(vide)' }}</pre>
</div>

<!-- Log système (10 dernières lignes) -->
<div class="card p-4 mb-4">
    <h3 class="text-sm font-bold text-cyber-accent mb-2">Log système (10 dernières lignes)</h3>
    <pre style="background:#0b0f1a;color:#e5e7eb;padding:10px;border-radius:4px;font-size:11px;overflow-x:auto;white-space:pre-wrap">{{ audit.system_log or '(vide)' }}</pre>
</div>

{% else %}

<div class="card p-4 mb-4" style="border:1px solid #ef4444;background:rgba(239,68,68,0.06)">
    {% if audit and audit.fail_reason %}
        <div class="text-cyber-red font-bold text-sm mb-2">
            {% if audit.fail_reason == 'DNS_NOT_RESOLVED' %}🌐 DNS — hostname non résolu
            {% elif audit.fail_reason == 'TCP_TIMEOUT' %}⏱ Port 22/TCP — timeout (serveur down ou flux bloqué)
            {% elif audit.fail_reason == 'TCP_REFUSED' %}🚫 Port 22/TCP — connexion rejetée (sshd arrêté ?)
            {% elif audit.fail_reason == 'SSH_AUTH_OR_HANDSHAKE_FAILED' %}🔑 SSH — handshake ou authentification échouée
            {% else %}✗ Connexion impossible ({{ audit.fail_reason }}){% endif %}
        </div>
        <p class="text-xs text-gray-300 mb-2">{{ audit.fail_detail }}</p>
    {% else %}
        <p class="text-sm text-cyber-red font-bold">✗ Connexion impossible</p>
        <p class="text-xs text-gray-400 mt-1">Détail indisponible.</p>
    {% endif %}
    <p class="text-xs text-gray-500 mt-3">
        <a href="/qualys/search?field=hostname&search={{ hostname }}" class="text-cyber-accent hover:underline">→ Voir ce host dans Qualys (recherche)</a>
    </p>
</div>

{% endif %}

{% endif %}

{% endif %}

{% endblock %}
