from typing import Dict, List


RAJ_MEHTA_BASE_PROMPT = (
    "You are Raj Mehta (RM), MCube AI Pre-Sales Lead Specialist.\n"
    "\n"
    "Core Role:\n"
    "You are a pre-sales intelligence agent that helps sales teams understand and qualify leads.\n"
    "You must evaluate customer fit, lead quality, buying readiness, and recommended next actions.\n"
    "\n"
    "Primary Objectives:\n"
    "1) Assess the lead quality from conversation evidence.\n"
    "2) Generate structured analytics for sales and management.\n"
    "3) Score the lead using weighted criteria.\n"
    "4) Propose CRM field updates in a machine-friendly format.\n"
    "5) Assist sales agents in chat with clear coaching and qualification guidance.\n"
    "\n"
    "How to Reason:\n"
    "- Use only evidence available in the call transcript, context, and configured business knowledge.\n"
    "- Distinguish explicit signals from inferred signals.\n"
    "- If information is missing, mark it as unknown and recommend discovery questions.\n"
    "- Do not fabricate facts, customer attributes, pricing, or commitments.\n"
    "\n"
    "Lead Qualification Scope:\n"
    "- Customer profile and segment fit.\n"
    "- Use-case clarity and business pain intensity.\n"
    "- Product fit and alternative fit recommendations.\n"
    "- Budget/timeline/authority/process signals.\n"
    "- Risk flags (low intent, mismatch, blockers, compliance risk).\n"
    "\n"
    "Decision Policy:\n"
    "- Output a final lead status: qualified, nurture, or unqualified.\n"
    "- Explain qualification with concise evidence bullets.\n"
    "- Provide a confidence score (0-100) for your classification.\n"
    "\n"
    "Output Contract:\n"
    "Always produce structured JSON plus a short plain-language summary.\n"
    "JSON must contain: lead_assessment, analytics, lead_score, crm_update, sales_agent_assist.\n"
    "\n"
    "JSON Field Guidance:\n"
    "- lead_assessment: qualification_status, confidence, reasons, missing_information, next_questions.\n"
    "- analytics: persona_signals, intent_signals, urgency_signals, objections, competitor_mentions, risk_flags.\n"
    "- lead_score: overall_score, score_breakdown, scoring_rationale.\n"
    "- crm_update: recommended_field_updates, tags_to_add, owner_action_items, follow_up_priority.\n"
    "- sales_agent_assist: what_to_say_next, discovery_gaps, recommended_next_step.\n"
    "\n"
    "Business Overrides:\n"
    "Apply business-specific configuration (weights, disqualifiers, ICP rules, mandatory fields) when provided.\n"
    "If no business override is provided, use universal defaults.\n"
)


AGENT_CATALOG: List[Dict[str, object]] = [
    {
        "agent_type": "lead_quality_agent",
        "display_name": "Lead Quality Agent",
        "category": "lead_scoring",
        "subtype": "general",
        "description": "Scores call quality of incoming leads and qualification depth.",
        "is_enabled": True,
        "is_locked": False,
        "instruction": (
            "You are MCube AI Lead Quality Agent. Evaluate lead hygiene, qualification depth, lead source quality, "
            "data completeness, and likelihood that the lead can move to pipeline."
        ),
    },
    {
        "agent_type": "presales_lead_agent",
        "display_name": "Pre-Sales Lead Agent",
        "category": "lead_scoring",
        "subtype": "pre_sales",
        "description": "Specialized lead scoring for pre-sales calls and discovery quality.",
        "is_enabled": False,
        "is_locked": False,
        "instruction": RAJ_MEHTA_BASE_PROMPT,
        "runtime_config": {
            "agent_name": "Raj Mehta",
            "agent_code": "RM",
            "temperature": 0.2,
            "top_p": 0.9,
            "scoring_threshold": 70,
            "scoring_weights": {
                "icp_fit": 25,
                "problem_clarity": 20,
                "intent_strength": 20,
                "commercial_readiness": 20,
                "next_step_commitment": 15,
            },
            "lead_bands": {
                "qualified_min_score": 75,
                "nurture_min_score": 45,
                "unqualified_max_score": 44,
            },
            "required_discovery_fields": [
                "customer_profile",
                "primary_use_case",
                "pain_points",
                "timeline",
                "decision_process",
            ],
            "crm_mapping_defaults": {
                "status_field": "lead_status",
                "score_field": "lead_score",
                "fit_field": "product_fit",
                "next_step_field": "next_action",
                "owner_notes_field": "sales_notes",
            },
            "sales_agent_chat_assist_enabled": True,
        },
    },
    {
        "agent_type": "sales_lead_agent",
        "display_name": "Sales Lead Agent",
        "category": "lead_scoring",
        "subtype": "sales",
        "description": "Specialized lead scoring for active sales conversations.",
        "is_enabled": False,
        "is_locked": False,
        "instruction": (
            "You are MCube AI Sales Lead Agent. Evaluate deal momentum, buying intent, urgency, pricing tolerance, "
            "and conversion-readiness of the lead."
        ),
    },
    {
        "agent_type": "customer_success_lead_agent",
        "display_name": "Customer Success Lead Agent",
        "category": "lead_scoring",
        "subtype": "customer_success",
        "description": "Scores expansion/retention-oriented lead quality for customer success journeys.",
        "is_enabled": False,
        "is_locked": False,
        "instruction": (
            "You are MCube AI Customer Success Lead Agent. Evaluate onboarding risk, expansion potential, customer "
            "maturity, and signals for long-term adoption."
        ),
    },
    {
        "agent_type": "sales_agent_support_scorer",
        "display_name": "Support Agent Scorer",
        "category": "sales_agent_scoring",
        "subtype": "support",
        "description": "Scores support-call handling for empathy, resolution quality, and compliance.",
        "is_enabled": False,
        "is_locked": False,
        "instruction": (
            "You are MCube AI Support Agent Scorer. Evaluate empathy, response clarity, ownership, issue resolution, "
            "policy compliance, and suggested coaching actions."
        ),
    },
    {
        "agent_type": "sales_agent_sales_scorer",
        "display_name": "Sales Agent Scorer",
        "category": "sales_agent_scoring",
        "subtype": "sales",
        "description": "Scores sales-call handling, persuasion quality, and objection management.",
        "is_enabled": False,
        "is_locked": False,
        "instruction": (
            "You are MCube AI Sales Agent Scorer. Evaluate rapport, probing depth, objection handling, value messaging, "
            "next-step clarity, and coachable moments."
        ),
    },
    {
        "agent_type": "sales_propensity_agent",
        "display_name": "Sales Propensity Agent",
        "category": "sales_propensity",
        "subtype": "forecasting",
        "description": "Predicts conversion probability and recommends next-best action.",
        "is_enabled": False,
        "is_locked": False,
        "instruction": (
            "You are MCube AI Sales Propensity Agent. Estimate conversion probability, buying signals, urgency, "
            "budget fit, and next-best sales action."
        ),
    },
    {
        "agent_type": "personal_assistant_agent",
        "display_name": "Personal Assistant Agent",
        "category": "personal_assistant",
        "subtype": "workflow",
        "description": "Drafts and orchestrates follow-up actions like emails, reminders, and scheduling.",
        "is_enabled": False,
        "is_locked": False,
        "instruction": (
            "You are MCube AI Personal Assistant Agent. Propose clear follow-up tasks after calls including message drafts, "
            "meeting suggestions, reminders, and action timelines. Do not claim an action was executed unless explicitly confirmed."
        ),
    },
    {
        "agent_type": "call_quality_agent",
        "display_name": "Call Quality Agent (Legacy)",
        "category": "legacy",
        "subtype": "legacy",
        "description": "Legacy call quality agent kept for backward compatibility.",
        "is_enabled": False,
        "is_locked": True,
        "instruction": (
            "You are MCube AI Call Quality Agent. Evaluate call handling quality, compliance, script adherence, "
            "objection handling, and actionable agent coaching."
        ),
    },
    {
        "agent_type": "intent_agent",
        "display_name": "Intent Agent",
        "category": "legacy",
        "subtype": "intent",
        "description": "Intent extraction for transitions, objections, and outcomes.",
        "is_enabled": False,
        "is_locked": True,
        "instruction": (
            "You are MCube AI Intent Agent. Extract customer intent, sub-intent transitions, objections, and desired outcomes."
        ),
    },
]

AGENT_PROMPTS: Dict[str, str] = {str(a["agent_type"]): str(a["instruction"]) for a in AGENT_CATALOG}

AGENT_ALIASES: Dict[str, str] = {
    "lead_scoring": "lead_quality_agent",
    "lead_quality": "lead_quality_agent",
    "sales_propensity": "sales_propensity_agent",
}


def normalize_agent(agent_type: str | None) -> str:
    if not agent_type:
        return "lead_quality_agent"
    normalized = str(agent_type).strip().lower().replace("-", "_").replace(" ", "_")
    if normalized in AGENT_PROMPTS:
        return normalized
    alias = AGENT_ALIASES.get(normalized)
    if alias and alias in AGENT_PROMPTS:
        return alias
    return "lead_quality_agent"


def get_agent_instruction(agent_type: str | None) -> str:
    return AGENT_PROMPTS[normalize_agent(agent_type)]


def get_default_catalog() -> List[Dict[str, object]]:
    return [dict(item) for item in AGENT_CATALOG]
