"""Write a linked ATS export, one JSON record per line. Requires Python 3."""
import json
import os
from pathlib import Path
import sys
from urllib.request import Request, urlopen


QUERIES = Path(__file__).with_name("agency-export.graphql").read_text(encoding="utf-8")


def export_records(endpoint, api_key, page_size=50):
    def pages(operation, parent=None):
        after = None
        while True:
            variables = {"first": page_size, "after": after}
            if parent is not None:
                variables["id"] = parent["id"]
            request = Request(endpoint, data=json.dumps({
                "operationName": operation, "query": QUERIES, "variables": variables,
            }).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"])
            data = result["data"]
            if parent is not None:
                data = data["parent"]
                if data is None:
                    raise RuntimeError(f"{parent} is no longer visible. Start a fresh export.")
            page = data["items"]
            for edge in page["edges"]:
                yield edge["node"]
            if not page["pageInfo"]["hasNextPage"]:
                return
            cursor = page["pageInfo"]["endCursor"]
            if not cursor or cursor == after:
                raise ValueError(f"{operation} returned another page without advancing its cursor.")
            after = cursor

    for kind, operation in (("user", "Team"), ("company", "Companies"), ("contact", "Contacts"),
                            ("candidate", "Candidates"), ("job", "Jobs"), ("application", "Applications"),
                            ("note", "Notes")):
        for record in pages(operation):
            yield {"type": kind, "record": record}
            parent = {"type": kind, "id": record["id"]}
            if kind == "candidate":
                for document in pages("CandidateFiles", parent):
                    yield {"type": "candidateDocument", "parent": parent, "record": document}
            elif kind == "job":
                for document in pages("JobFiles", parent):
                    yield {"type": "jobDocument", "parent": parent, "record": document}
                for change in pages("StageHistory", parent):
                    yield {"type": "stageEvent", "parent": parent, "record": change}
            elif kind == "application":
                for interview in pages("Appointments", parent):
                    yield {"type": "interview", "parent": parent, "record": interview}
                    appointment = {"type": "interview", "id": interview["id"]}
                    for change in pages("AppointmentChanges", appointment):
                        yield {"type": "interviewChange", "parent": appointment, "record": change}


if __name__ == "__main__":
    for row in export_records(sys.argv[1], os.environ["KITH_ATS_API_KEY"]):
        print(json.dumps(row, ensure_ascii=False))
