"""LeadSquared activity attribution — agent name on activities."""
from __future__ import annotations

from typing import Any, Dict, Optional


def lsq_agent_name_from_call(call: Dict[str, Any]) -> str:
    for key in ("agentname", "agent_name"):
        value = call.get(key)
        if value is not None and str(value).strip():
            return str(value).strip()
    return ""


def resolve_lsq_owner_email(integration_config: Dict[str, Any], agent_name: str) -> Optional[str]:
    """Map Mcube agent name to LeadSquared user email (optional config)."""
    if not agent_name:
        return None
    mapping = integration_config.get("agent_owner_mapping") or {}
    if not isinstance(mapping, dict):
        return None
    direct = mapping.get(agent_name)
    if direct is not None and str(direct).strip():
        return str(direct).strip()
    agent_lower = agent_name.lower()
    for key, email in mapping.items():
        if str(key).strip().lower() == agent_lower and str(email).strip():
            return str(email).strip()
    return None


def apply_lsq_agent_attribution(
    payload: Dict[str, Any],
    call: Dict[str, Any],
    integration_config: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """Set ActivityOwnerEmail when mapped so LeadSquared shows 'Added by' the agent."""
    agent_name = lsq_agent_name_from_call(call)
    if not agent_name:
        return payload

    config = integration_config or {}
    owner_email = resolve_lsq_owner_email(config, agent_name)
    if owner_email:
        payload["ActivityOwnerEmail"] = owner_email

    return payload
