"""
Read-only MCP tools for Apollo prospecting and enrichment.
"""

from __future__ import annotations

from typing import Any, Callable, Dict, List, Tuple

from g_gremlin import apollo as apollo_helpers
from g_gremlin.sequencer.apollo import ApolloSequencerProvider

ToolTuple = Tuple[str, Callable[..., Dict[str, Any]], str]


def _first_list(payload: Dict[str, Any], keys: Tuple[str, ...]) -> List[Dict[str, Any]]:
    for key in keys:
        value = payload.get(key)
        if isinstance(value, list):
            return value
    return []


def apollo_search_people(
    q_keywords: str | None = None,
    request: Dict[str, Any] | None = None,
    page: int = 1,
    per_page: int = 25,
) -> Dict[str, Any]:
    payload = dict(request or {})
    if q_keywords and not payload.get("q_keywords"):
        payload["q_keywords"] = q_keywords
    payload.setdefault("page", max(int(page), 1))
    payload.setdefault("per_page", max(int(per_page), 1))

    result = apollo_helpers.ApolloClient().search_people(payload)
    people = _first_list(result, ("people", "contacts", "mixed_people", "results", "data"))
    return {
        "count": len(people),
        "people": people,
        "pagination": result.get("pagination"),
        "raw": result,
    }


def apollo_search_companies(
    q_keywords: str | None = None,
    request: Dict[str, Any] | None = None,
    page: int = 1,
    per_page: int = 25,
) -> Dict[str, Any]:
    payload = dict(request or {})
    if q_keywords and not payload.get("q_keywords"):
        payload["q_keywords"] = q_keywords
    payload.setdefault("page", max(int(page), 1))
    payload.setdefault("per_page", max(int(per_page), 1))

    result = apollo_helpers.ApolloClient().search_companies(payload)
    companies = _first_list(result, ("organizations", "accounts", "companies", "results", "data"))
    return {
        "count": len(companies),
        "companies": companies,
        "pagination": result.get("pagination"),
        "raw": result,
    }


def apollo_enrich_company(domain: str, fields: List[str] | None = None) -> Dict[str, Any]:
    return apollo_helpers.ApolloClient().enrich_company(domain=domain, fields=fields)


def apollo_enrich_contact(
    email: str | None = None,
    first_name: str | None = None,
    last_name: str | None = None,
    company: str | None = None,
    domain: str | None = None,
    linkedin_url: str | None = None,
    fields: List[str] | None = None,
) -> Dict[str, Any]:
    if not any([email, first_name, last_name, company, domain, linkedin_url]):
        raise ValueError(
            "Provide at least one identifier for apollo.enrich_contact "
            "(email, name, company/domain, or linkedin_url)."
        )
    return apollo_helpers.ApolloClient().enrich_contact(
        email=email,
        first_name=first_name,
        last_name=last_name,
        company=company,
        domain=domain,
        linkedin_url=linkedin_url,
        fields=fields,
    )


def apollo_list_campaigns(active_only: bool = False) -> Dict[str, Any]:
    provider = ApolloSequencerProvider(api_key=apollo_helpers.get_apollo_api_key())
    campaigns = [campaign.to_dict() for campaign in provider.list_campaigns()]
    if active_only:
        campaigns = [campaign for campaign in campaigns if campaign.get("status") == "active"]
    return {"count": len(campaigns), "campaigns": campaigns}


def get_tools() -> List[ToolTuple]:
    return [
        ("apollo.search_people", apollo_search_people, "Search Apollo people/prospects."),
        ("apollo.search_companies", apollo_search_companies, "Search Apollo organizations/companies."),
        ("apollo.enrich_company", apollo_enrich_company, "Enrich a company profile by domain."),
        ("apollo.enrich_contact", apollo_enrich_contact, "Enrich a contact profile by email/name/company."),
        ("apollo.list_campaigns", apollo_list_campaigns, "List Apollo email campaigns/sequences."),
    ]

