"""Company-level provider ranking for B2B/vendor-fleet checkout.

Reuses market/picker_ranking.py::rank_pickers UNMODIFIED, twice: once inside
each fleet company's own pool of drivers (to pick a single representative —
"who would this company most likely put on the job"), then again across the
representatives (one per company, plus one per unaffiliated individual
owner-operator) to produce the customer-facing top 3. This is deliberately
NOT the same shape as B2C's ranking — see market/views.py::checkout_provider
and the "Region-aware candidate pool" note there for why B2B needs its own
candidate-gathering (region cascade, no per-date fairness signal yet) even
though the underlying scoring function is shared."""

from .picker_ranking import rank_pickers


def group_and_rank_providers(candidates, rating_summaries_by_picker, platform_average_rating):
    """candidates: flat list of picker dicts (each already carrying
    'user_id', 'distance_km', 'today_count', 'company_id' — company_id is
    None for an unaffiliated individual owner-operator, who is always their
    own one-entry group). Returns the ranked list of REPRESENTATIVES —
    at most one per company, plus every unaffiliated individual — each
    tagged with 'is_company' so callers/templates can render the two cases
    differently. Safe to call with an empty list."""
    if not candidates:
        return []

    groups = {}
    for c in candidates:
        groups.setdefault(c.get('company_id'), []).append(c)

    representatives = []
    for company_id, group in groups.items():
        if len(group) > 1:
            ranked_group = rank_pickers(list(group), rating_summaries_by_picker, platform_average_rating)
            representative = ranked_group[0]
        else:
            representative = group[0]
        representative['is_company'] = company_id is not None
        representative['group_size'] = len(group)
        representatives.append(representative)

    return rank_pickers(representatives, rating_summaries_by_picker, platform_average_rating)
