# AUTOGENERATED! DO NOT EDIT! File to edit: action.ipynb (unless otherwise specified).

__all__ = ['get_repo', 'get_issues', 'create_issue']

# Cell
from github import Github, UnknownObjectException, Repository
from fastlinkcheck import link_check
from fastcore.all import *

# Cell
def get_repo(repo:str=None, token=None) -> Repository:
    "Get a `Repository` object.  Optionally supply a `token` for private repositories."
    repo=ifnone(repo, os.getenv('GITHUB_REPOSITORY'))
    token = ifnone(token, os.getenv('INPUT_TOKEN'))
    assert repo, 'You must specify the repo parameter or set the `GITHUB_REPOSITORY` the environment variable.'
    try:
        return Github(token).get_repo(repo)
    except UnknownObjectException as e:
        raise Exception(f'Repo: `{repo}` not found. If this is a private repo make sure you provide an appropriate token\n {e}')

# Cell
def get_issues(repo:str=None, state:str='open', token:str=None):
    "Get all issues for a repository"
    return [i for i in get_repo(repo).get_issues(state=state)]

# Cell
@call_parse
def create_issue(title:Param("If specified, open an issue with a title of `title` if broken links are found.", str)=None,
                 raise_error:Param("raise Exception if broken links are found", store_true)=False):
    """
    A GitHub Action utility that searches the `path` for broken links and opens an issue if an open issue with the same `title` is not found.
    """
    path = os.getenv('INPUT_PATH')
    repo = os.getenv('GITHUB_REPOSITORY')
    token = os.getenv('INPUT_TOKEN')
    assert path, "You must supply the environment variable `INPUT_PATH`"
    assert repo, "You must set the environment variable `GITHUB_REPOSITORY`."
    assert token, "You must supply the environment variable `INPUT_TOKEN`"
    host = ifnone(os.getenv('INPUT_HOST'), '')
    raise_error = os.getenv('INPUT_RAISE_ERROR')
    config_file = os.getenv('INPUT_CONFIG_FILE')
    title = os.getenv('INPUT_ISSUE_TITLE')

    for v in ['path', 'repo', 'host', 'raise_error', 'config_file', 'title']: print(f'{v}: {eval(v)}')
    l = link_check(path=path, host=host, config_file=config_file, actions_output=True, print_logs=True)
    r = get_repo(repo=repo, token=token)
    incumbent_issue = first([i for i in get_issues(repo=repo, state='open', token=token) if i.title == title])
    print(f"::set-output name=new_issue_created::{bool(not incumbent_issue  and title)}")
    if l:
        i = ifnone(incumbent_issue, r.create_issue(title, body=repr(l)) if title else None)
        if i:
            print(f"::set-output name=related_issue_num::{i.number}")
            print(f'Related: {i.html_url}')
    if raise_error: sys.exit(1)