import json
import logging
from datetime import datetime
from soagila.db.event_bus import publish_event

logger = logging.getLogger("soagila.canary.alert")

CHANNEL = "soagila:metrics"


async def broadcast_canary_alert(
    token_id: str,
    memory_id: str,
    token_type: str,
    triggered_by: str | None,
):
    """
    Broadcast a canary trigger alert to all connected dashboards.
    This is a CRITICAL security event — zero false positive.
    """
    alert = {
        "type": "canary_alert",
        "severity": "CRITICAL",
        "token_id": token_id,
        "memory_id": memory_id,
        "token_type": token_type,
        "triggered_by": triggered_by,
        "message": (
            "SECURITY ALERT: Canary token accessed. "
            "This indicates unauthorized data access. "
            "Canary tokens are synthetic bait — any access is guaranteed unauthorized."
        ),
        "recommended_actions": [
            "Immediately freeze the accessing user's session",
            "Notify Level 2 Security Officer",
            "Preserve all audit logs for forensic analysis",
            "Check for lateral movement from the same session",
        ],
        "timestamp": datetime.utcnow().isoformat(),
    }

    await publish_event(CHANNEL, json.dumps(alert))
    logger.critical(f"Canary alert broadcast: {token_id}")
