"""Browse the Contributor Network and pull the top benchmarked items.

Run: python -m sair.examples.contributor_network
Env:
    SAIR_API_KEY                required
    SAIR_COMPETITION_ID         required, filters the network to one competition
"""

from __future__ import annotations

import os
import sys

from sair import Sair


def main() -> None:
    competition_id = os.environ.get("SAIR_COMPETITION_ID")
    if not competition_id:
        sys.exit("Set SAIR_COMPETITION_ID to filter the network.")

    with Sair() as sair:
        # Top 5 by avgAccuracy.
        leaderboard = sair.get(
            "/contributor-network/benchmarks",
            competitionId=competition_id,
            sortBy="avgAccuracy",
            sortDirection="desc",
            limit=5,
        )
        print(f"top {len(leaderboard['items'])} benchmarked items for {competition_id}\n")
        for row in leaderboard["items"]:
            score = row.get("avgAccuracy")
            score_text = f"{score:.3f}" if score is not None else "—"
            print(
                f"  {score_text}  {row['title']!r:40s} "
                f"by {row['author']['displayName']}  ({row['publicCode']})"
            )

        # Detail and lineage for the top entry.
        if leaderboard["items"]:
            head = leaderboard["items"][0]
            print(f"\ndetail for {head['publicCode']}:")
            detail = sair.get(f"/contributor-network/items/{head['itemId']}")
            body = detail.get("content") or detail.get("solverCode") or ""
            print(f"  parent: {detail.get('parent')}")
            print(f"  body preview: {body[:120]}...")

            graph = sair.get(f"/contributor-network/items/{head['itemId']}/graph")
            print(f"  lineage: {len(graph['nodes'])} nodes, {len(graph['edges'])} edges")


if __name__ == "__main__":
    main()
