"""Run with Python 3 and requests. Use a test workspace."""
import json
import os
import sys

import requests


def graphql(query, variables):
    response = requests.post(
        sys.argv[1],
        headers={"x-api-key": os.environ["KITH_ATS_API_KEY"]},
        json={"query": query, "variables": variables},
        timeout=30,
    )
    response.raise_for_status()
    result = response.json()
    if result.get("errors"):
        raise RuntimeError(result["errors"])
    return result["data"]


def place_candidate():
    # Open a role for our client.
    client = graphql("""
      mutation AddClient($input: AddCompanyInput!) {
        addCompany(input: $input) { wasCreated company { id name relationship } }
      }
    """, {"input": {"name": "Example Studio", "relationship": "CLIENT"}})["addCompany"]["company"]
    graphql("""
      mutation AddHiringContact($input: AddClientContactInput!) {
        addClientContact(input: $input) { clientContact { id name email company { id } } }
      }
    """, {"input": {"companyId": client["id"], "name": "Alex Marchetti", "email": "alex@example.com"}})
    job = graphql("""
      mutation OpenJob($input: CreateJobInput!) {
        createJob(input: $input) { job { id title status briefRevision client { id } } }
      }
    """, {"input": {"companyId": client["id"], "title": "Engineering Director"}})["createJob"]["job"]

    # Sam is one person. This application tracks Sam on this job.
    person = graphql("""
      mutation AddCandidates($input: AddCandidatesInput!) {
        addCandidates(input: $input) { results { wasCreated candidate { id name } } }
      }
    """, {"input": {"candidates": [{"name": "Sam Lindqvist", "email": "sam@example.com"}]}})
    candidate = person["addCandidates"]["results"][0]["candidate"]
    added = graphql("""
      mutation AddToJob($input: AddCandidatesToJobInput!) {
        addCandidatesToJob(input: $input) {
          results { wasAdded jobCandidate { id stage version placementVersion candidate { id } job { id } } }
        }
      }
    """, {"input": {"jobId": job["id"], "candidates": [{"candidateId": candidate["id"]}]}})
    application = added["addCandidatesToJob"]["results"][0]["jobCandidate"]

    def move(application, stage):
        result = graphql("""
          mutation MoveStage($input: MoveJobCandidateInput!) {
            moveJobCandidate(input: $input) { jobCandidate { id stage version placementVersion } }
          }
        """, {"input": {
            "jobCandidateId": application["id"], "expectedVersion": application["version"], "stage": stage,
        }})
        return result["moveJobCandidate"]["jobCandidate"]

    application = move(application, "SCREENED")

    # The calendar handles invitations. The ATS keeps the appointment.
    scheduled = graphql("""
      mutation ScheduleInterview($input: ScheduleInterviewInput!) {
        scheduleInterview(input: $input) {
          interview { id label scheduledAt status interviewer location feedback version }
        }
      }
    """, {"input": {
        "jobCandidateId": application["id"], "label": "Technical interview",
        "scheduledAt": "2027-01-12T14:00:00Z", "interviewer": "Alex Marchetti",
    }})
    interview = scheduled["scheduleInterview"]["interview"]
    application = move(application, "INTERVIEWING")
    update_interview_query = """
      mutation UpdateInterview($input: UpdateInterviewInput!) {
        updateInterview(input: $input) {
          interview { id label scheduledAt status interviewer location feedback version }
        }
      }
    """
    rescheduled = graphql(update_interview_query, {"input": {
        "interviewId": interview["id"], "expectedVersion": interview["version"],
        "scheduledAt": "2027-01-13T14:00:00Z",
    }})
    interview = rescheduled["updateInterview"]["interview"]
    graphql(update_interview_query, {"input": {
        "interviewId": interview["id"], "expectedVersion": interview["version"],
        "status": "COMPLETED", "feedback": "Explained the constraints and tested two alternatives.",
    }})

    interview_history = graphql("""
      query InterviewHistory($id: ID!, $after: String) {
        interview(id: $id) {
          changes(first: 20, after: $after) {
            edges { node { id changedAt actorUserId previousStatus status previousScheduledAt scheduledAt feedbackChanged } }
            pageInfo { hasNextPage endCursor }
          }
        }
      }
    """, {"id": interview["id"]})

    def follow_up(application, next_action, due_at):
        result = graphql("""
          mutation SaveFollowUp($input: UpdateJobCandidateFollowUpInput!) {
            updateJobCandidateFollowUp(input: $input) {
              jobCandidate { id version nextAction nextActionDueAt submittedAt }
            }
          }
        """, {"input": {
            "jobCandidateId": application["id"], "expectedVersion": application["version"],
            "nextAction": next_action, "nextActionDueAt": due_at,
        }})
        return result["updateJobCandidateFollowUp"]["jobCandidate"]

    application = follow_up(application, "Call Alex for a decision", "2027-01-15T14:00:00Z")
    # On Friday, Alex confirms they want to make an offer.
    application = follow_up(application, None, None)

    # Record the offer, then the hire and acceptance.
    application = move(application, "OFFERED")
    save_terms_query = """
      mutation SaveTerms($input: UpdatePlacementInput!) {
        updatePlacement(input: $input) {
          jobCandidate { id stage version placementVersion offerSalary currency placementFee startDate offerAcceptedAt }
        }
      }
    """
    terms = graphql(save_terms_query, {"input": {
        "jobCandidateId": application["id"], "expectedVersion": application["placementVersion"],
        "offerSalary": "85000.00", "currency": "GBP", "placementFee": "17000.00", "startDate": "2027-02-01",
    }})
    application = move(terms["updatePlacement"]["jobCandidate"], "HIRED")
    graphql(save_terms_query, {"input": {
        "jobCandidateId": application["id"], "expectedVersion": application["placementVersion"],
        "offerAcceptedAt": "2027-01-20",
    }})
    graphql("""
      mutation CloseJob($input: SetJobStatusInput!) {
        setJobStatus(input: $input) { job { id title status client { id } } }
      }
    """, {"input": {"jobId": job["id"], "status": "CLOSED"}})

    placement = graphql("""
      query ReadApplication($id: ID!, $after: String) {
        jobCandidate(id: $id) {
          id stage version placementVersion offerSalary currency placementFee startDate offerAcceptedAt
          candidate { id name }
          job { id title status client { id name } }
          interviews(first: 10, after: $after) {
            edges { node { id label scheduledAt status interviewer location feedback version } }
            pageInfo { endCursor hasNextPage }
          }
        }
      }
    """, {"id": application["id"]})
    history = graphql("""
      query ReadStageHistory($jobId: ID!, $candidateId: ID!, $after: String) {
        job(id: $jobId) {
          id status
          auditTrail(first: 20, after: $after, filter: {category: DECISIONS, candidateId: $candidateId}) {
            edges { node { id occurredAt stageEvent fromStage toStage decision reason actor { kind label user { id } } } }
            pageInfo { endCursor hasNextPage }
          }
        }
      }
    """, {"jobId": job["id"], "candidateId": candidate["id"]})
    print(json.dumps({"placement": placement["jobCandidate"], "history": history["job"]["auditTrail"],
                      "interviewHistory": interview_history["interview"]["changes"]}, indent=2))

if __name__ == "__main__":
    if len(sys.argv) != 2 or not os.getenv("KITH_ATS_API_KEY"):
        sys.exit("Set KITH_ATS_API_KEY and pass the ATS endpoint as the argument.")
    place_candidate()
