{% extends "base.html" %}
{% set active_page = "monitor" %}

{% block title %}Monitor — IETF Draft Analyzer{% endblock %}

{% block extra_head %}<script src="/static/js/plotly.min.js"></script>{% endblock %}

{% block content %}
<div class="mb-6">
    <h1 class="text-2xl font-bold text-white">Live Monitor</h1>
    <p class="text-slate-400 text-sm mt-1">Track automated monitoring runs and pipeline status. The pipeline fetches new drafts from the IETF Datatracker, rates them with Claude AI, generates embeddings with Ollama, and extracts ideas. Unprocessed counts show drafts waiting at each stage.</p>
</div>

<div id="monitor-app"></div>

{% endblock %}

{% block extra_scripts %}
<script>
const PLOTLY_LAYOUT = {
    paper_bgcolor: 'transparent',
    plot_bgcolor: 'transparent',
    font: { color: '#94a3b8', family: 'Inter, system-ui, sans-serif', size: 12 },
    margin: { t: 30, r: 20, b: 40, l: 40 },
    xaxis: { gridcolor: '#1e293b', zerolinecolor: '#334155' },
    yaxis: { gridcolor: '#1e293b', zerolinecolor: '#334155' },
};
const PLOTLY_CONFIG = { responsive: true, displayModeBar: false };
const PALETTE = [
    '#3b82f6', '#ef4444', '#22c55e', '#a855f7', '#f59e0b',
    '#06b6d4', '#ec4899', '#84cc16', '#f97316', '#8b5cf6',
];

const data = {{ status | tojson }};
const app = document.getElementById('monitor-app');

// Status banner
const lastRun = data.last_run;
let bannerColor, bannerBorder, bannerText;
if (!lastRun) {
    bannerColor = 'text-slate-400';
    bannerBorder = 'border-slate-700';
    bannerText = 'No monitoring runs recorded yet. Run <code class="text-slate-300">ietf monitor run</code> to start.';
} else if (lastRun.status === 'completed') {
    bannerColor = 'text-green-400';
    bannerBorder = 'border-green-500/30';
    bannerText = 'Last run completed successfully';
} else if (lastRun.status === 'failed') {
    bannerColor = 'text-red-400';
    bannerBorder = 'border-red-500/30';
    bannerText = 'Last run failed: ' + (lastRun.error_message || 'unknown error');
} else {
    bannerColor = 'text-yellow-400';
    bannerBorder = 'border-yellow-500/30';
    bannerText = 'A monitoring run is currently in progress...';
}

let html = `
<div class="stat-card rounded-xl border ${bannerBorder} p-4 mb-6">
    <div class="flex items-center gap-3">
        <div class="w-3 h-3 rounded-full ${lastRun && lastRun.status === 'completed' ? 'bg-green-500' : lastRun && lastRun.status === 'failed' ? 'bg-red-500' : lastRun && lastRun.status === 'running' ? 'bg-yellow-500 animate-pulse' : 'bg-slate-600'}"></div>
        <span class="${bannerColor} font-medium">${bannerText}</span>
    </div>
</div>
`;

// Stat cards row
const lastTime = lastRun ? (lastRun.started_at || '').replace('T', ' ').slice(0, 19) : '-';
const lastDuration = lastRun && lastRun.duration_seconds ? lastRun.duration_seconds.toFixed(1) + 's' : '-';
const lastNew = lastRun ? lastRun.new_drafts_found : 0;
const totalRuns = data.total_runs;

html += `
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
    <div class="stat-card rounded-xl border border-slate-800 p-4">
        <div class="text-2xl font-bold text-slate-200">${totalRuns}</div>
        <div class="text-xs text-slate-400 mt-1">Total Runs</div>
    </div>
    <div class="stat-card rounded-xl border border-slate-800 p-4">
        <div class="text-sm font-mono font-bold text-slate-200 truncate">${lastTime}</div>
        <div class="text-xs text-slate-400 mt-1">Last Run</div>
    </div>
    <div class="stat-card rounded-xl border border-slate-800 p-4">
        <div class="text-2xl font-bold text-slate-200">${lastDuration}</div>
        <div class="text-xs text-slate-400 mt-1">Duration</div>
    </div>
    <div class="stat-card rounded-xl border border-slate-800 p-4">
        <div class="text-2xl font-bold text-blue-400">${lastNew}</div>
        <div class="text-xs text-slate-400 mt-1">New Drafts (Last Run)</div>
    </div>
</div>
`;

// Unprocessed counts
const up = data.unprocessed;
function warnColor(n) { return n > 0 ? 'text-yellow-400 border-yellow-500/30' : 'text-green-400 border-green-500/30'; }

html += `
<h2 class="text-lg font-semibold text-white mb-3">Unprocessed Drafts</h2>
<div class="grid grid-cols-3 gap-4 mb-8">
    <div class="stat-card rounded-xl border ${up.unrated > 0 ? 'border-yellow-500/30' : 'border-green-500/30'} p-4">
        <div class="text-2xl font-bold ${up.unrated > 0 ? 'text-yellow-400' : 'text-green-400'}">${up.unrated}</div>
        <div class="text-xs text-slate-400 mt-1">Unrated</div>
    </div>
    <div class="stat-card rounded-xl border ${up.unembedded > 0 ? 'border-yellow-500/30' : 'border-green-500/30'} p-4">
        <div class="text-2xl font-bold ${up.unembedded > 0 ? 'text-yellow-400' : 'text-green-400'}">${up.unembedded}</div>
        <div class="text-xs text-slate-400 mt-1">Un-embedded</div>
    </div>
    <div class="stat-card rounded-xl border ${up.no_ideas > 0 ? 'border-yellow-500/30' : 'border-green-500/30'} p-4">
        <div class="text-2xl font-bold ${up.no_ideas > 0 ? 'text-yellow-400' : 'text-green-400'}">${up.no_ideas}</div>
        <div class="text-xs text-slate-400 mt-1">No Ideas</div>
    </div>
</div>
`;

// Pipeline progress
const pl = data.pipeline || {};
const cost = data.cost || {};
if (pl.total_drafts) {
    const pctRated = Math.round((pl.rated / pl.total_drafts) * 100);
    const pctEmbedded = Math.round((pl.embedded / pl.total_drafts) * 100);
    const pctIdeas = Math.round((pl.with_ideas / pl.total_drafts) * 100);

    function progressBar(pct, color) {
        return `<div class="w-full bg-slate-800 rounded-full h-2.5 mt-1.5">
            <div class="h-2.5 rounded-full ${color}" style="width: ${pct}%"></div>
        </div>`;
    }

    html += `
    <h2 class="text-lg font-semibold text-white mb-3">Pipeline Progress</h2>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        <div class="stat-card rounded-xl border border-slate-800 p-4">
            <div class="flex justify-between items-baseline">
                <span class="text-xs text-slate-400">Rated</span>
                <span class="text-sm font-bold text-blue-400">${pl.rated} / ${pl.total_drafts}</span>
            </div>
            ${progressBar(pctRated, 'bg-blue-500')}
            <div class="text-xs text-slate-600 mt-1 text-right">${pctRated}%</div>
        </div>
        <div class="stat-card rounded-xl border border-slate-800 p-4">
            <div class="flex justify-between items-baseline">
                <span class="text-xs text-slate-400">Embedded</span>
                <span class="text-sm font-bold text-purple-400">${pl.embedded} / ${pl.total_drafts}</span>
            </div>
            ${progressBar(pctEmbedded, 'bg-purple-500')}
            <div class="text-xs text-slate-600 mt-1 text-right">${pctEmbedded}%</div>
        </div>
        <div class="stat-card rounded-xl border border-slate-800 p-4">
            <div class="flex justify-between items-baseline">
                <span class="text-xs text-slate-400">Ideas Extracted</span>
                <span class="text-sm font-bold text-green-400">${pl.with_ideas} / ${pl.total_drafts}</span>
            </div>
            ${progressBar(pctIdeas, 'bg-green-500')}
            <div class="text-xs text-slate-600 mt-1 text-right">${pctIdeas}%</div>
        </div>
    </div>

    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
        <div class="stat-card rounded-xl border border-slate-800 p-4">
            <div class="text-2xl font-bold text-slate-200">${pl.total_drafts}</div>
            <div class="text-xs text-slate-400 mt-1">Total Documents</div>
        </div>
        <div class="stat-card rounded-xl border border-slate-800 p-4">
            <div class="text-2xl font-bold text-slate-200">${pl.idea_total}</div>
            <div class="text-xs text-slate-400 mt-1">Total Ideas</div>
        </div>
        <div class="stat-card rounded-xl border border-slate-800 p-4">
            <div class="text-2xl font-bold text-slate-200">${pl.gap_count}</div>
            <div class="text-xs text-slate-400 mt-1">Gaps Identified</div>
        </div>
        <div class="stat-card rounded-xl border border-slate-800 p-4">
            <div class="text-xl font-bold text-amber-400">$${cost.estimated_usd || '0.00'}</div>
            <div class="text-xs text-slate-400 mt-1">Est. API Cost</div>
            <div class="text-xs text-slate-600 mt-0.5">${(cost.input_tokens || 0).toLocaleString()} in / ${(cost.output_tokens || 0).toLocaleString()} out</div>
        </div>
    </div>
    `;
}

// New drafts over time chart
const runs = data.runs.slice().reverse(); // chronological order
if (runs.length > 1) {
    html += `
    <h2 class="text-lg font-semibold text-white mb-3">New Drafts Found Over Time</h2>
    <div id="monitor-chart" class="bg-slate-900/50 rounded-xl border border-slate-800 p-4 mb-8" style="height:300px"></div>
    `;
}

// Run history table
if (data.runs.length > 0) {
    html += `
    <h2 class="text-lg font-semibold text-white mb-3">Run History</h2>
    <div class="bg-slate-900/50 rounded-xl border border-slate-800 overflow-hidden">
        <table class="w-full text-sm">
            <thead>
                <tr class="border-b border-slate-800 text-slate-400 text-xs uppercase">
                    <th class="px-4 py-3 text-left">#</th>
                    <th class="px-4 py-3 text-left">Started</th>
                    <th class="px-4 py-3 text-right">Duration</th>
                    <th class="px-4 py-3 text-center">Status</th>
                    <th class="px-4 py-3 text-right">New Drafts</th>
                    <th class="px-4 py-3 text-right">Analyzed</th>
                    <th class="px-4 py-3 text-right">Embedded</th>
                    <th class="px-4 py-3 text-right">Ideas</th>
                </tr>
            </thead>
            <tbody>`;

    for (const r of data.runs) {
        const statusBadge = r.status === 'completed'
            ? '<span class="px-2 py-0.5 rounded-full text-xs font-semibold bg-green-500/20 text-green-400">completed</span>'
            : r.status === 'failed'
            ? '<span class="px-2 py-0.5 rounded-full text-xs font-semibold bg-red-500/20 text-red-400">failed</span>'
            : '<span class="px-2 py-0.5 rounded-full text-xs font-semibold bg-yellow-500/20 text-yellow-400">running</span>';
        const started = (r.started_at || '').replace('T', ' ').slice(0, 19);
        const dur = r.duration_seconds ? r.duration_seconds.toFixed(1) + 's' : '-';
        html += `
                <tr class="border-b border-slate-800/50 hover:bg-slate-800/30">
                    <td class="px-4 py-2.5 text-slate-500">${r.id}</td>
                    <td class="px-4 py-2.5 font-mono text-xs text-slate-300">${started}</td>
                    <td class="px-4 py-2.5 text-right text-slate-400">${dur}</td>
                    <td class="px-4 py-2.5 text-center">${statusBadge}</td>
                    <td class="px-4 py-2.5 text-right text-slate-300">${r.new_drafts_found}</td>
                    <td class="px-4 py-2.5 text-right text-slate-300">${r.drafts_analyzed}</td>
                    <td class="px-4 py-2.5 text-right text-slate-300">${r.drafts_embedded}</td>
                    <td class="px-4 py-2.5 text-right text-slate-300">${r.ideas_extracted}</td>
                </tr>`;
    }
    html += `
            </tbody>
        </table>
    </div>`;
}

app.innerHTML = html;

// Render chart
if (runs.length > 1) {
    const x = runs.map(r => (r.started_at || '').slice(0, 19));
    const y = runs.map(r => r.new_drafts_found || 0);
    Plotly.newPlot('monitor-chart', [{
        x: x,
        y: y,
        type: 'scatter',
        mode: 'lines+markers',
        fill: 'tozeroy',
        line: { color: PALETTE[0], width: 2 },
        marker: { color: PALETTE[0], size: 6 },
        fillcolor: PALETTE[0] + '30',
    }], {
        ...PLOTLY_LAYOUT,
        xaxis: { ...PLOTLY_LAYOUT.xaxis, title: { text: 'Run Date', font: { size: 11 } } },
        yaxis: { ...PLOTLY_LAYOUT.yaxis, title: { text: 'New Drafts', font: { size: 11 } } },
    }, PLOTLY_CONFIG);
}
</script>
{% endblock %}
