import { generateId } from '../bridge/conversation.js';
export function logActivityStart(db, params) {
    const id = generateId();
    const now = new Date().toISOString();
    db.prepare(`INSERT INTO squad_activities (id, squad_code, conversation_id, started_at, status, user_message, triggered_by, created_at)
     VALUES (?, ?, ?, ?, 'running', ?, ?, ?)`).run(id, params.squadCode, params.conversationId ?? null, now, params.userMessage ?? null, params.triggeredBy ?? 'dashboard', now);
    return {
        id,
        squad_code: params.squadCode,
        conversation_id: params.conversationId ?? null,
        started_at: now,
        finished_at: null,
        duration_ms: null,
        status: 'running',
        user_message: params.userMessage ?? null,
        result_summary: null,
        triggered_by: params.triggeredBy ?? 'dashboard',
        created_at: now,
    };
}
export function logActivityComplete(db, activityId, resultSummary) {
    const now = new Date().toISOString();
    const activity = db.prepare('SELECT started_at FROM squad_activities WHERE id = ?').get(activityId);
    const durationMs = activity
        ? new Date(now).getTime() - new Date(activity.started_at).getTime()
        : null;
    db.prepare(`UPDATE squad_activities SET finished_at = ?, duration_ms = ?, status = 'completed', result_summary = ? WHERE id = ?`).run(now, durationMs, resultSummary ?? null, activityId);
}
export function logActivityFail(db, activityId, error) {
    const now = new Date().toISOString();
    const activity = db.prepare('SELECT started_at FROM squad_activities WHERE id = ?').get(activityId);
    const durationMs = activity
        ? new Date(now).getTime() - new Date(activity.started_at).getTime()
        : null;
    db.prepare(`UPDATE squad_activities SET finished_at = ?, duration_ms = ?, status = 'failed', result_summary = ? WHERE id = ?`).run(now, durationMs, error ?? null, activityId);
}
export function getActivitiesByDate(db, date, squadCode) {
    const startOfDay = `${date}T00:00:00.000Z`;
    const endOfDay = `${date}T23:59:59.999Z`;
    if (squadCode) {
        return db.prepare(`SELECT * FROM squad_activities WHERE squad_code = ? AND started_at >= ? AND started_at <= ? ORDER BY started_at ASC`).all(squadCode, startOfDay, endOfDay);
    }
    return db.prepare(`SELECT * FROM squad_activities WHERE started_at >= ? AND started_at <= ? ORDER BY started_at ASC`).all(startOfDay, endOfDay);
}
export function getDailySummary(db, date) {
    const activities = getActivitiesByDate(db, date);
    const bySquad = new Map();
    for (const a of activities) {
        const list = bySquad.get(a.squad_code) ?? [];
        list.push(a);
        bySquad.set(a.squad_code, list);
    }
    const summaries = [];
    for (const [squadCode, squadActivities] of bySquad) {
        summaries.push({
            squad_code: squadCode,
            activity_count: squadActivities.length,
            completed_count: squadActivities.filter((a) => a.status === 'completed').length,
            failed_count: squadActivities.filter((a) => a.status === 'failed').length,
            total_duration_ms: squadActivities.reduce((sum, a) => sum + (a.duration_ms ?? 0), 0),
            activities: squadActivities,
        });
    }
    return summaries;
}
export function getRecentActivities(db, limit = 20) {
    return db.prepare('SELECT * FROM squad_activities ORDER BY started_at DESC LIMIT ?').all(limit);
}
export function formatDailySummaryForPrompt(summaries) {
    if (summaries.length === 0) {
        return 'Nenhuma atividade registrada hoje.';
    }
    const lines = [];
    for (const s of summaries) {
        const totalMin = Math.round(s.total_duration_ms / 60000);
        lines.push(`## Squad: ${s.squad_code}`);
        lines.push(`- Atividades: ${s.activity_count} (${s.completed_count} concluídas, ${s.failed_count} falhas)`);
        lines.push(`- Tempo total: ${totalMin} minutos`);
        for (const a of s.activities) {
            const dur = a.duration_ms ? `${Math.round(a.duration_ms / 1000)}s` : 'em andamento';
            const status = a.status === 'completed' ? 'OK' : a.status === 'failed' ? 'FALHA' : 'EM ANDAMENTO';
            const msg = a.user_message ? a.user_message.slice(0, 100) : '(sem mensagem)';
            lines.push(`  - [${status}] "${msg}" (${dur})`);
            if (a.result_summary) {
                lines.push(`    Resultado: ${a.result_summary.slice(0, 200)}`);
            }
        }
        lines.push('');
    }
    return lines.join('\n');
}
//# sourceMappingURL=activity-service.js.map