"""Print recorded placement fees by currency. Run with Python 3."""
import json
import os
import sys
from decimal import Decimal
from urllib.request import Request, urlopen


QUERY = """
query ReadPlacementFees($first: Int!, $after: String) {
  jobCandidates(filter: { stages: [HIRED] }, first: $first, after: $after) {
    edges { node { id currency placementFee } }
    pageInfo { hasNextPage endCursor }
  }
}
"""


def placement_fees(endpoint, api_key, page_size=100):
    totals = {}
    after = None
    while True:
        request = Request(endpoint, data=json.dumps({
            "query": QUERY, "variables": {"first": page_size, "after": after},
        }).encode(), headers={"Content-Type": "application/json", "x-api-key": api_key})
        with urlopen(request, timeout=30) as response:
            result = json.load(response)
        if result.get("errors"):
            raise RuntimeError(result["errors"])

        page = result["data"]["jobCandidates"]
        for edge in page["edges"]:
            row = edge["node"]
            currency = row["currency"]
            group = totals.setdefault(currency, {"hires": 0, "missingFee": 0, "recordedFees": Decimal("0.00")})
            group["hires"] += 1
            if row["placementFee"] is None:
                group["missingFee"] += 1
            else:
                group["recordedFees"] += Decimal(row["placementFee"])

        if not page["pageInfo"]["hasNextPage"]:
            return totals
        cursor = page["pageInfo"]["endCursor"]
        if not cursor or cursor == after:
            raise ValueError("The API returned another page without advancing its cursor.")
        after = cursor


if __name__ == "__main__":
    totals = placement_fees(sys.argv[1], os.environ["KITH_ATS_API_KEY"])
    print(json.dumps(totals, default=str, indent=2, sort_keys=True))
