/**
 * src/autonomy/delivery-health.ts
 *
 * Round-6 fix for caveat 5: detect stale/broken WhatsApp delivery before
 * the owner notices alerts have stopped arriving. Runs daily 09:00 KSA:
 *   1. Read the delivery_queue table for failed/expired rows in last 7d.
 *   2. Read the WhatsApp client status if available.
 *   3. If channel is unhealthy AND owner has fallback contact (email),
 *      send the daily alert via that fallback.
 *
 * The point: WA can quietly disconnect (QR session expires, device offline,
 * Baileys hiccup). Alert mechanisms shouldn't silently fail. If WA is
 * broken, the owner sees a daily heads-up via email or web-chat banner so
 * they re-pair the QR code.
 */
import { supabase } from '../utils/supabase.js';
import { createChildLogger } from '../utils/logger.js';
import { record as journalRecord, list as listJournal } from './journal.js';
import { getFact } from './identity.js';
import { whatsappClient } from '../channels/whatsapp/client.js';
const log = createChildLogger('autonomy:delivery-health');
const days = (n) => new Date(Date.now() - n * 24 * 60 * 60 * 1000).toISOString();
export async function runDeliveryHealthCheck(tenantId) {
    const result = {
        channel: 'whatsapp',
        ok: true,
        detail: '',
        failuresLast7d: 0,
        alertSent: false,
    };
    // 1. Count delivery_queue failures in last 7 days
    try {
        const { data } = await supabase
            .from('delivery_queue')
            .select('id, channel, status')
            .eq('tenant_id', tenantId)
            .in('status', ['failed', 'expired'])
            .gte('updated_at', days(7));
        const fails = (data ?? []).filter((r) => r.channel === 'whatsapp');
        result.failuresLast7d = fails.length;
    }
    catch { /* table may not exist */ }
    // 2. Check delivery health via journal — count proactive/scorecard/heartbeat
    //    deliveries in last 7d. If 0 attempts but the cron has been firing,
    //    something is wrong upstream (no owner phone fact, etc.).
    try {
        const recent = await listJournal({
            tenantId,
            since: days(7),
            limit: 500,
        });
        const deliveryAttempts = recent.filter((e) => ['scorecard', 'heartbeat', 'proactive_followup_silent', 'proactive_invoice_dunning',
            'proactive_deadline_check', 'proactive_promise_reminder', 'catchup_digest']
            .includes(e.kind)).length;
        if (deliveryAttempts > 0 && result.failuresLast7d / deliveryAttempts > 0.4) {
            result.ok = false;
            result.detail = `${result.failuresLast7d}/${deliveryAttempts} delivery attempts failed in last 7d (>40%). WhatsApp likely disconnected.`;
        }
    }
    catch { /* non-fatal */ }
    // 3. Try a synchronous "is the WA client awake?" probe
    try {
        const status = whatsappClient.ready;
        if (status === false) {
            result.ok = false;
            result.detail = result.detail || 'WhatsApp client reports not ready (Baileys session may need re-pair)';
        }
    }
    catch { /* probe not available — skip */ }
    // 4. If unhealthy, try fallback delivery channels
    if (!result.ok) {
        try {
            // First fallback: email if owner has email fact and Resend is configured
            const ownerEmail = (await getFact(tenantId, 'owner.email'))?.fact_value;
            if (ownerEmail && process.env.EMAIL_RESEND_API_KEY) {
                const { executeTool } = await import('../tools/executor.js');
                const r = await executeTool('send_email', {
                    to: ownerEmail,
                    subject: '⚠️ Muassis WhatsApp delivery down',
                    body: `Your Muassis agent's WhatsApp channel has had ${result.failuresLast7d} ` +
                        `delivery failures in the last 7 days. Daily alerts (scorecard, heartbeats) ` +
                        `may be silently failing.\n\n` +
                        `Likely cause: Baileys session expired (QR re-scan needed) or device offline.\n\n` +
                        `Action: Open the dashboard → Channels tab → WhatsApp → re-scan QR.\n\n` +
                        `Detail: ${result.detail}`,
                }, tenantId);
                if (r.success)
                    result.alertSent = true;
            }
        }
        catch (err) {
            log.warn({ tenantId, err: err.message }, 'fallback email alert failed');
        }
    }
    // 5. Journal the health check itself so the owner can audit it
    try {
        await journalRecord({
            tenantId,
            kind: 'delivery_health',
            action: 'check',
            outcome: result.ok ? 'success' : 'failure',
            reason: result.detail || 'WhatsApp delivery healthy',
            metadata: {
                failuresLast7d: result.failuresLast7d,
                alertSent: result.alertSent,
            },
        });
    }
    catch { /* non-fatal */ }
    log.info({ tenantId, ...result }, 'delivery health check complete');
    return result;
}
//# sourceMappingURL=delivery-health.js.map