"""
qualify_prospect tool

Scores a prospect/company against the Artefact 14.5-point ICP model.
Accepts a HubSpot company ID or manual company data dict.
"""

from typing import Optional, List

from artefact_mcp.core.icp_scorer import ICPScorer
from artefact_mcp.core.hubspot_client import HubSpotClient
from artefact_mcp.core.property_mappings import PropertyMapping, DEFAULT_PROPERTY_MAPPING
from artefact_mcp.core.property_mapper import PropertyMapper


def qualify_prospect(
    company_id: Optional[str] = None,
    company_data: Optional[dict] = None,
    hubspot_client: Optional[HubSpotClient] = None,
    property_mapping: Optional[PropertyMapping] = None,
) -> dict:
    """Score a prospect against the 14.5-point ICP model.

    Args:
        company_id: HubSpot company ID. If provided, fetches data from HubSpot.
        company_data: Manual dict with company attributes. Used if company_id is None.
        hubspot_client: Pre-configured HubSpotClient (required if company_id given).
        property_mapping: Custom PropertyMapping configuration (Pro tier only).

    Returns:
        Full scoring result dict.
    """
    if not company_id and not company_data:
        raise ValueError("Either company_id or company_data must be provided.")

    scorer = ICPScorer()
    mapping = property_mapping or DEFAULT_PROPERTY_MAPPING
    mapper = PropertyMapper(mapping)

    if company_id:
        if not hubspot_client:
            raise ValueError(
                "HubSpot client required when using company_id. "
                "Set HUBSPOT_API_KEY environment variable."
            )

        # Fetch company with custom properties
        property_names = _get_required_properties(mapping)
        hs_data = hubspot_client.fetch_company_with_custom_properties(company_id, property_names)

        # Fetch deal count for purchase history
        deal_count = _fetch_deal_count(hubspot_client, company_id)

        # Map HubSpot data to ICP scorer input
        company_data = mapper.map_to_icp_input(hs_data, deal_count)

    result = scorer.score_company(company_data)

    return {
        "company": {
            "name": company_data.get("company_name", company_data.get("name", "Unknown")),
            "hubspot_id": company_data.get("hubspot_id"),
            "industry": company_data.get("industry"),
        },
        "total_score": result.total_score,
        "tier": result.tier,
        "breakdown": result.breakdown,
        "exclusion_check": result.exclusion_check,
        "recommended_action": result.recommended_action,
        "engagement_strategy": result.engagement_strategy,
    }


def _get_required_properties(mapping: PropertyMapping) -> List[str]:
    """Get list of custom property names to fetch from HubSpot."""
    props = []
    if mapping.tech_stack:
        props.append(mapping.tech_stack)
    if mapping.growth_signals:
        props.extend(mapping.growth_signals)
    if mapping.content_engagement:
        props.append(mapping.content_engagement)
    if mapping.decision_maker_access:
        props.append(mapping.decision_maker_access)
    if mapping.budget_authority:
        props.append(mapping.budget_authority)
    if mapping.strategic_alignment:
        props.append(mapping.strategic_alignment)
    return props


def _fetch_deal_count(client: HubSpotClient, company_id: str) -> int:
    """Fetch closed-won deal count for a company."""
    # Simple implementation - fetch all closed-won deals and count those for this company
    deals = client.fetch_client_data(stage_filter="closedwon", limit=1000)
    count = sum(1 for d in deals if d.get("client_id") == company_id)
    return count
