from InvestmentWebsite.offers.record_schema import AGENT_ROW_IDX as AIDX
from InvestmentWebsite.offers.record_schema import BRANCH_ROW_IDX as BIDX
from InvestmentWebsite.services.catalog import get_agent_avatar_url


def build_about_context(agents, branches, roles, selected_region):
    branches_by_agent = {}
    for branch in branches:
        agent_id = branch[BIDX.AGENT_ID]
        branch_name = branch[BIDX.BRANCH]
        if not branch_name:
            continue
        branches_by_agent.setdefault(agent_id, [])
        if branch_name not in branches_by_agent[agent_id]:
            branches_by_agent[agent_id].append(branch_name)

    role_map = {role[0]: role[1] for role in roles}

    agents_view = []
    for agent in agents:
        agent_id = agent[AIDX.AGENT_ID]
        assigned_branches = branches_by_agent.get(agent_id, [])
        if not assigned_branches:
            assigned_branches = [""]
        all_branches_label = ", ".join([b for b in assigned_branches if b])

        for branch_name in assigned_branches:
            agents_view.append(
                {
                    "name": agent[AIDX.NAME],
                    "surname": agent[AIDX.SURNAME],
                    "email": agent[AIDX.EMAIL],
                    "phone": agent[AIDX.PHONE],
                    "license": agent[AIDX.LICENSE],
                    "agent_id": agent_id,
                    "region": branch_name,
                    "all_branches": all_branches_label,
                    "roles": role_map.get(agent_id, ""),
                    "agent_image": get_agent_avatar_url(agent_id),
                }
            )

    unique_regions = sorted(set(agent["region"] for agent in agents_view if agent["region"]))

    if selected_region != "all":
        agents_view = [agent for agent in agents_view if agent["region"] == selected_region]

    return {
        "agents_view": agents_view,
        "unique_regions": unique_regions,
        "selected_region": selected_region,
    }
