"""Graph relationship builders.

These helpers infer edges between already-enumerated Microsoft Graph nodes.
"""

from __future__ import annotations

from typing import Dict, Iterable, List

from ..adt_types import ResourceNode, ResourceRelationship


def build_graph_appid_edges(nodes: Iterable[ResourceNode]) -> List[ResourceRelationship]:
    """Infer Application <-> ServicePrincipal relationships via appId.

    Emits directed edges from servicePrincipal -> application when both share the
    same appId.
    """

    apps_by_appid: Dict[str, ResourceNode] = {}
    sps_by_appid: Dict[str, ResourceNode] = {}

    for n in nodes:
        app_id = n.tags.get("appId") if n.tags else None
        if not app_id:
            continue

        if n.type == "Microsoft.Graph/Application":
            apps_by_appid[str(app_id)] = n
        elif n.type == "Microsoft.Graph/ServicePrincipal":
            sps_by_appid[str(app_id)] = n

    edges: List[ResourceRelationship] = []
    for app_id, sp in sorted(sps_by_appid.items(), key=lambda kv: kv[0]):
        app = apps_by_appid.get(app_id)
        if not app:
            continue
        edges.append(
            ResourceRelationship(
                source_id=sp.id,
                target_id=app.id,
                relation_type="appId",
                weight=1.0,
            )
        )

    return edges
