export async function dashboardRoutes(app, opts) {
    const { db } = opts;
    // GET /api/dashboard/stats — all metrics for the operations dashboard
    app.get('/api/dashboard/stats', {
        preHandler: [app.requireAuth],
    }, async (_request, reply) => {
        // ── KPI Cards ──────────────────────────────────────────
        const open = db.prepare(`SELECT COUNT(*) AS n FROM kanban_tasks WHERE status='planned'`).get().n;
        const delayed = db.prepare(`SELECT COUNT(*) AS n FROM kanban_tasks WHERE status='failed'`).get().n;
        const doneToday = db.prepare(`SELECT COUNT(*) AS n FROM kanban_tasks WHERE status='done' AND date(finished_at,'localtime')=date('now','localtime')`).get().n;
        const inReview = db.prepare(`SELECT COUNT(*) AS n FROM kanban_tasks WHERE status='executing'`).get().n;
        const runningNow = db.prepare(`SELECT COUNT(*) AS n FROM squad_activities WHERE status='running'`).get().n;
        const activeSquads = db.prepare(`SELECT COUNT(DISTINCT squad_code) AS n FROM squad_activities WHERE status='running'`).get().n;
        const hoursTracked = Math.round((db.prepare(`SELECT COALESCE(SUM(CAST(duration_ms AS REAL)),0)/3600000.0 AS h
         FROM squad_activities
         WHERE started_at >= date('now','-7 days','localtime') AND duration_ms IS NOT NULL`).get().h) * 10) / 10;
        const thisWeek = db.prepare(`SELECT COUNT(*) AS n FROM kanban_tasks WHERE status='done' AND finished_at >= date('now','-7 days','localtime')`).get().n;
        const lastWeek = db.prepare(`SELECT COUNT(*) AS n FROM kanban_tasks WHERE status='done' AND finished_at >= date('now','-14 days','localtime') AND finished_at < date('now','-7 days','localtime')`).get().n;
        const weekChange = lastWeek > 0
            ? Math.round(((thisWeek - lastWeek) / lastWeek) * 100)
            : (thisWeek > 0 ? 100 : 0);
        // ── Progress Metrics ────────────────────────────────────
        const totalDone = db.prepare(`SELECT COUNT(*) AS n FROM kanban_tasks WHERE status='done'`).get().n;
        const totalFailed = db.prepare(`SELECT COUNT(*) AS n FROM kanban_tasks WHERE status='failed'`).get().n;
        const totalAll = db.prepare(`SELECT COUNT(*) AS n FROM kanban_tasks`).get().n;
        const regularidade = totalAll > 0 ? Math.round((totalDone / totalAll) * 100) : 0;
        const qualidade = (totalDone + totalFailed) > 0
            ? Math.round((totalDone / (totalDone + totalFailed)) * 100)
            : 0;
        const eficiencia = Math.round((regularidade + qualidade) / 2);
        // ── 14-day completion rhythm ────────────────────────────
        const rhythm14 = db.prepare(`SELECT date(finished_at,'localtime') AS day, COUNT(*) AS count
       FROM kanban_tasks
       WHERE status='done' AND finished_at >= date('now','-14 days','localtime')
       GROUP BY day ORDER BY day`).all();
        // ── Hourly rhythm ───────────────────────────────────────
        const hourlyToday = db.prepare(`SELECT CAST(strftime('%H', finished_at, 'localtime') AS INTEGER) AS hour, COUNT(*) AS count
       FROM kanban_tasks
       WHERE status='done' AND date(finished_at,'localtime') = date('now','localtime')
       GROUP BY hour ORDER BY hour`).all();
        const hourlyLastWeek = db.prepare(`SELECT CAST(strftime('%H', finished_at, 'localtime') AS INTEGER) AS hour,
              CAST(COUNT(*) AS REAL) / 7.0 AS avg_count
       FROM kanban_tasks
       WHERE status='done'
         AND finished_at >= date('now','-7 days','localtime')
         AND date(finished_at,'localtime') < date('now','localtime')
       GROUP BY hour ORDER BY hour`).all();
        // ── Running sessions (with current kanban task) ─────────
        const runningSessions = db.prepare(`SELECT sa.id, sa.squad_code, sa.started_at,
              (SELECT kt.title  FROM kanban_tasks kt WHERE kt.activity_id = sa.id AND kt.status = 'executing' ORDER BY kt.position LIMIT 1) AS current_task,
              (SELECT kt.agent_name FROM kanban_tasks kt WHERE kt.activity_id = sa.id AND kt.status = 'executing' ORDER BY kt.position LIMIT 1) AS current_agent,
              (SELECT kt.step_id    FROM kanban_tasks kt WHERE kt.activity_id = sa.id AND kt.status = 'executing' ORDER BY kt.position LIMIT 1) AS current_step,
              (SELECT COUNT(*) FROM kanban_tasks kt WHERE kt.activity_id = sa.id AND kt.status = 'done') AS steps_done,
              (SELECT COUNT(*) FROM kanban_tasks kt WHERE kt.activity_id = sa.id) AS steps_total
       FROM squad_activities sa
       WHERE sa.status='running'
       ORDER BY sa.started_at ASC`).all();
        let sessionAgents = [];
        if (runningSessions.length > 0) {
            const ids = runningSessions.map(s => s.id);
            const placeholders = ids.map(() => '?').join(',');
            sessionAgents = db.prepare(`SELECT kt.activity_id, kt.agent_name,
                SUM(CASE WHEN kt.status='done'      THEN 1 ELSE 0 END) AS done_count,
                SUM(CASE WHEN kt.status='executing' THEN 1 ELSE 0 END) AS executing_count,
                SUM(CASE WHEN kt.status='planned'   THEN 1 ELSE 0 END) AS planned_count,
                SUM(CASE WHEN kt.status='failed'    THEN 1 ELSE 0 END) AS failed_count,
                COUNT(*) AS total
         FROM kanban_tasks kt
         WHERE kt.activity_id IN (${placeholders})
           AND kt.agent_name IS NOT NULL AND kt.agent_name != ''
         GROUP BY kt.activity_id, kt.agent_name
         ORDER BY kt.activity_id, MIN(kt.position)`).all(...ids);
        }
        // ── Squad performance ───────────────────────────────────
        const squadPerf = db.prepare(`SELECT squad_code,
              SUM(CASE WHEN status='done' THEN 1 ELSE 0 END) AS done,
              SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END) AS failed,
              COUNT(*) AS total
       FROM kanban_tasks
       GROUP BY squad_code
       ORDER BY done DESC
       LIMIT 10`).all();
        // ── Agent performance ───────────────────────────────────
        const agentPerf = db.prepare(`SELECT agent_name,
              SUM(CASE WHEN status='done' THEN 1 ELSE 0 END) AS done,
              SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END) AS failed,
              COUNT(*) AS total
       FROM kanban_tasks
       WHERE agent_name IS NOT NULL AND agent_name != ''
       GROUP BY agent_name
       ORDER BY done DESC
       LIMIT 10`).all();
        return reply.send({
            kpis: { open, delayed, doneToday, activeSquads, runningNow, hoursTracked, weekChange },
            metrics: { regularidade, qualidade, eficiencia },
            rhythm14,
            hourlyToday,
            hourlyLastWeek,
            runningSessions,
            sessionAgents,
            squadPerf,
            agentPerf,
        });
    });
    // POST /api/dashboard/sessions/:id/kill — terminate a running pipeline
    app.post('/api/dashboard/sessions/:id/kill', {
        preHandler: [app.requireAuth],
    }, async (request, reply) => {
        const { id } = request.params;
        const activity = db.prepare(`SELECT id, squad_code FROM squad_activities WHERE id = ? AND status = 'running'`).get(id);
        if (!activity) {
            return reply.code(404).send({ error: 'Session not found or already finished' });
        }
        // Best-effort: try to kill the Claude process via the bridge(s)
        opts.kill?.(activity.squad_code);
        // Mark the activity as cancelled
        db.prepare(`UPDATE squad_activities
       SET status = 'cancelled',
           finished_at = datetime('now'),
           duration_ms = CAST((julianday('now') - julianday(started_at)) * 86400000 AS INTEGER)
       WHERE id = ?`).run(id);
        // Mark any executing kanban tasks as failed
        db.prepare(`UPDATE kanban_tasks SET status = 'failed', finished_at = datetime('now')
       WHERE activity_id = ? AND status = 'executing'`).run(id);
        return reply.send({ success: true, squad_code: activity.squad_code });
    });
}
//# sourceMappingURL=dashboard-routes.js.map