#!/usr/bin/python3
# SPDX-License-Identifier: Apache-2.0

import enarxbot
import itertools

# We don't want to copy all labels on linked issues; ignore those in this subset.
BLOCKED_LABELS = {
    "meta",
    "question",
    "help wanted",
    "good first issue",
    "duplicate",
}

github = enarxbot.connect()

for issue in github.search_issues(f"org:enarx is:pr is:public is:open linked:issue"):
    # Some attributes change when converting to PR; get them beforehand.
    repo = issue.repository

    # Convert to a PR.
    pr = issue.as_pull_request()

    # Get a list of related issues to the PR.
    related = {i: repo.get_issue(i) for i in enarxbot.get_related_issues(pr)}

    # Copy relevant labels from the issue to the PR.
    issues_labels = [n.labels for (k, n) in related.items()]
    issues_labels = {l.name for l in itertools.chain(*issues_labels)}
    pr_labels = {label.name for label in pr.labels}

    # Find the set of all labels we want to copy that aren't already set on the PR.
    unset_labels = issues_labels - BLOCKED_LABELS - pr_labels

    # Print status.
    to_set = pr_labels | unset_labels
    print(f"{repo.name}#{pr.number}:", end="")
    for label in sorted(to_set):
        state = "" if label in pr_labels else "+"
        print(f" {state}'{label}'", end="")
    print()

    # If there are any labels we need to add, add them.
    if len(unset_labels) > 0:
        pr.set_labels(*list(to_set))
