/**
 * src/autonomy/scorecard.ts
 *
 * Daily 18:00 KSA: rolls up today's journal entries into a one-line value
 * scorecard delivered to the owner. The point: make the owner SEE that
 * Muassis is doing real work — not just sitting there. "Today I did X
 * actions, drafted Y messages, saved you ~Z hours."
 *
 * This is what makes the agent feel indispensable — quantified value.
 *
 * Time savings are heuristic estimates based on industry averages for
 * SMB tasks (typing a follow-up email = ~3 min, scheduling a meeting =
 * ~5 min, researching a topic = ~15 min, etc.). Conservative numbers.
 */
import { createChildLogger } from '../utils/logger.js';
import { list as listJournal, record as journalRecord } from './journal.js';
import { deliverMessage } from '../delivery/delivery.js';
import { getFact } from './identity.js';
const log = createChildLogger('autonomy:scorecard');
// Heuristic: time-saved per action type in MINUTES.
// Conservative — better to under-promise than over-claim.
const TIME_PER_ACTION = {
    // Communication
    send_email: 3,
    send_whatsapp: 2,
    send_telegram: 2,
    // Drafting (proactive)
    proactive_followup_silent: 4,
    proactive_invoice_dunning: 5,
    proactive_promise_reminder: 2,
    proactive_birthday_greeting: 3,
    // Scheduling
    schedule_followup: 1,
    schedule_recurring: 2,
    // Research
    research_topic: 15,
    web_search: 2,
    internal_knowledge_search: 1,
    // Skills + KG
    skill_create: 8,
    skill_evolve: 3,
    skill_install_from_url: 5,
    learn_from_document: 10,
    // Customer ops
    team_handoff: 2,
    escalate_decision: 4,
    // Saudi-specific
    zatca_invoice: 12,
    saudization_check: 5,
    arabic_contract_gen: 20,
    // PDF/Excel
    create_pdf_report: 15,
    create_excel: 10,
    // Browser
    browser_open: 1,
    browser_type: 1,
    // Reflection cycle
    reflection: 8, // saves owner from manually reviewing yesterday's failures
};
const days = (n) => new Date(Date.now() - n * 24 * 60 * 60 * 1000).toISOString();
export async function runDailyScorecard(tenantId) {
    const result = {
        totalActions: 0,
        toolCalls: 0,
        draftsCreated: 0,
        remindersSent: 0,
        schedulesCreated: 0,
        researchPerformed: 0,
        lessonsLearned: 0,
        escalationsRaised: 0,
        documentsLearned: 0,
        estimatedMinutesSaved: 0,
        topActions: [],
        delivered: false,
    };
    const startOfDay = new Date();
    startOfDay.setUTCHours(0, 0, 0, 0);
    const since = startOfDay.toISOString();
    const all = await listJournal({ tenantId, since, limit: 1000 }).catch(() => []);
    result.totalActions = all.length;
    const actionCounts = new Map();
    for (const entry of all) {
        const action = entry.action || 'unknown';
        actionCounts.set(action, (actionCounts.get(action) ?? 0) + 1);
        if (entry.kind === 'tool')
            result.toolCalls++;
        if (action.startsWith('proactive_') || action === 'silent_hot_lead' || action === 'promise_reminder') {
            result.draftsCreated++;
        }
        if (action === 'send_email' || action === 'send_whatsapp' || action === 'send_telegram') {
            result.remindersSent++;
        }
        if (action === 'schedule_followup' || action === 'schedule_recurring') {
            result.schedulesCreated++;
        }
        if (action === 'research_topic' || action === 'web_search') {
            result.researchPerformed++;
        }
        if (entry.kind === 'reflection' && entry.outcome === 'success') {
            const md = entry.metadata;
            const lc = md?.lessonCount ?? 0;
            result.lessonsLearned += lc;
        }
        if (entry.outcome === 'escalated')
            result.escalationsRaised++;
        if (action === 'learn_from_document')
            result.documentsLearned++;
        const minutes = TIME_PER_ACTION[action] ?? (entry.kind === 'tool' ? 1 : 0);
        result.estimatedMinutesSaved += minutes;
    }
    // Sort top actions by count, take top 5
    result.topActions = [...actionCounts.entries()]
        .sort((a, b) => b[1] - a[1])
        .slice(0, 5)
        .map(([action, count]) => `${action} ×${count}`);
    // Don't deliver if it was a quiet day (under 5 actions)
    if (result.totalActions < 5) {
        log.info({ tenantId, ...result }, 'scorecard: quiet day, no delivery');
        return result;
    }
    // Build the brief
    const hours = Math.floor(result.estimatedMinutesSaved / 60);
    const mins = result.estimatedMinutesSaved % 60;
    const timeSavedStr = hours > 0
        ? `${hours} ساعة${mins > 0 ? ` و${mins} دقيقة` : ''}`
        : `${mins} دقيقة`;
    const lines = [
        `📊 ملخص اليوم (${new Date().toLocaleDateString('ar-SA-u-nu-latn', { weekday: 'long', day: 'numeric', month: 'long' })}):`,
        '',
        `✅ ${result.totalActions} إجراء — وفّرت لك تقريباً ${timeSavedStr}.`,
    ];
    if (result.remindersSent > 0)
        lines.push(`💬 أرسلت ${result.remindersSent} رسالة/تذكير`);
    if (result.draftsCreated > 0)
        lines.push(`✍️ صغت ${result.draftsCreated} رسالة استباقية`);
    if (result.schedulesCreated > 0)
        lines.push(`📅 جدولت ${result.schedulesCreated} متابعة`);
    if (result.researchPerformed > 0)
        lines.push(`🔍 بحثت ${result.researchPerformed} موضوع`);
    if (result.documentsLearned > 0)
        lines.push(`📄 تعلمت من ${result.documentsLearned} مستند`);
    if (result.lessonsLearned > 0)
        lines.push(`🎓 تعلمت ${result.lessonsLearned} درس جديد`);
    if (result.escalationsRaised > 0)
        lines.push(`⚠️ ${result.escalationsRaised} قرار محتاج موافقتك في لوحة العمليات`);
    lines.push('');
    lines.push(`أكثر الأنشطة: ${result.topActions.join('، ')}`);
    // Journal the scorecard so it's queryable
    try {
        await journalRecord({
            tenantId,
            kind: 'scorecard',
            action: 'daily_scorecard',
            outcome: 'success',
            reason: `${result.totalActions} actions, ~${result.estimatedMinutesSaved}min saved`,
            metadata: result,
        });
    }
    catch { /* non-fatal */ }
    // Deliver to owner
    try {
        const ownerPhone = (await getFact(tenantId, 'owner.whatsapp'))?.fact_value;
        if (ownerPhone) {
            await deliverMessage({
                tenantId,
                to: ownerPhone,
                channel: 'whatsapp',
                message: lines.join('\n'),
            });
            result.delivered = true;
        }
    }
    catch (err) {
        log.warn({ tenantId, err: err.message }, 'scorecard delivery failed');
    }
    log.info({ tenantId, ...result }, 'scorecard complete');
    return result;
}
//# sourceMappingURL=scorecard.js.map