"""
AutoGen integration for scandar-guard.

Hooks into AutoGen's ConversableAgent message processing to monitor
agent behavior and send ASG telemetry.

Usage:
    from autogen import ConversableAgent
    from scandar_guard.integrations.autogen import register_scandar_hooks

    agent = ConversableAgent(name="my-agent", ...)
    register_scandar_hooks(agent, api_key="sk_xxx")
"""
from __future__ import annotations

import uuid
from typing import Any, Dict, List, Optional, Union

from ..asg_telemetry import AsgTelemetrySender
from ..inspector import MessageInspector
from ..tool_inspector import ToolCallInspector


def register_scandar_hooks(
    agent: Any,
    api_key: str,
    agent_id: Optional[str] = None,
    endpoint: Optional[str] = None,
) -> None:
    """
    Register scandar-guard monitoring hooks on an AutoGen ConversableAgent.

    Args:
        agent: AutoGen ConversableAgent instance
        api_key: Scandar API key for ASG telemetry
        agent_id: Override agent ID (defaults to agent.name)
        endpoint: ASG endpoint override
    """
    resolved_agent_id = agent_id or getattr(agent, "name", "autogen-agent")
    session_key = f"autogen_{uuid.uuid4().hex[:12]}"

    sender = AsgTelemetrySender(
        api_key=api_key,
        agent_id=resolved_agent_id,
        endpoint=endpoint or "https://scandar.ai/api/v1/asg/events",
    )

    msg_inspector = MessageInspector()
    tool_inspector = ToolCallInspector()

    sender.send_session_start(session_key)

    message_count = 0
    tool_call_count = 0
    findings_count = 0

    def process_message_hook(
        sender_agent: Any,
        message: Union[Dict, str],
        recipient: Any,
        silent: bool,
    ) -> Union[Dict, str]:
        """Hook called before each message is sent."""
        nonlocal message_count, tool_call_count, findings_count
        try:
            message_count += 1
            text = ""
            if isinstance(message, str):
                text = message
            elif isinstance(message, dict):
                text = message.get("content", "")
                # Check for tool calls
                tool_calls = message.get("tool_calls", [])
                for tc in tool_calls:
                    if isinstance(tc, dict):
                        fn = tc.get("function", {})
                        tool_name = fn.get("name", "unknown") if isinstance(fn, dict) else "unknown"
                    else:
                        tool_name = getattr(getattr(tc, "function", None), "name", "unknown")

                    tool_call_count += 1
                    result = tool_inspector.inspect_tool_call(tool_name, {}, session_key)
                    top = result.findings[0] if result.findings else None
                    sender.send_tool_call(
                        session_key, tool_name,
                        finding_category=top.category if top else None,
                        finding_severity=top.severity if top else None,
                    )
                    findings_count += len(result.findings)

            if text:
                result = msg_inspector.inspect_message("assistant", text, session_key)
                findings_count += len(result.findings)
        except Exception:
            pass
        return message

    def finalize_session() -> None:
        """Send session_end telemetry. Call when the agent conversation is done."""
        try:
            threat_score = min(100, findings_count * 15)
            classification = "suspicious" if findings_count > 3 else "elevated" if findings_count > 0 else "safe"
            sender.send_session_end(
                session_key,
                message_count=message_count,
                tool_call_count=tool_call_count,
                threat_score=threat_score,
                classification=classification,
                findings_summary={},
            )
        except Exception:
            pass

    # Attach finalize to agent for manual calling
    agent._scandar_finalize = finalize_session  # type: ignore[attr-defined]

    # Register the hook
    try:
        if hasattr(agent, "register_hook"):
            agent.register_hook("process_message_before_send", process_message_hook)
        elif hasattr(agent, "_process_message_before_send"):
            original = agent._process_message_before_send
            def wrapped(*args: Any, **kwargs: Any) -> Any:
                result = process_message_hook(*args, **kwargs)
                return original(*args, **kwargs) if original else result
            agent._process_message_before_send = wrapped
    except Exception:
        pass
