# Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
import os
import tempfile

import dateutil.parser
import magic
import requests

from platforms.common import ReleaseException, run

MESSAGE_PROMPT_TEMPLATE = """\
# Add release notes below. Any lines starting with '#' will be ignored.
{default_message}

# Commits since last release:
#
{commit_messages}
"""

MESSAGE_TEMPLATE = """\
Includes various improvements and bug fixes, viewable here: {html_url}
"""


def get_version_and_timestamp_from_release(release):
    """ Returns the version (without a 'v' prefix) and the timestamp of the release """
    release_version = release["tag_name"].lstrip("v")
    release_timestamp = dateutil.parser.parse(release["created_at"]).strftime("%s")
    return release_version, release_timestamp


def get_token(token_file):
    """
    Reads the first line from token_file to get a token
    """
    with open(token_file, "r") as fin:
        ret = fin.read().strip()
    if not ret:
        raise ReleaseException("No valid token found in {}".format(token_file))
    return ret


def get_current_user(github_token, prefer_fb_email=True):
    """ Gets info about the current github user """
    url = "https://api.github.com/user"
    emails_url = "https://api.github.com/user/emails"
    headers = get_headers(github_token)
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    ret = response.json()
    if not ret["email"].endswith("@fb.com") and prefer_fb_email:
        while emails_url:
            response = requests.get(emails_url, headers=headers)
            response.raise_for_status()
            fb_email = next(
                (
                    email["email"]
                    for email in response.json()
                    if email["verified"] and email["email"].endswith("@fb.com")
                ),
                None,
            )
            if fb_email:
                ret["email"] = fb_email
                break
            else:
                emails_url = response.links.get("next", {}).get("url")
    return ret


def get_commit(repository, github_token, commit):
    """ Gets a specific commit's info from github """
    url = "https://api.github.com/repos/{}/commits/{}".format(repository, commit)
    headers = get_headers(github_token)
    logging.info("Fetching commit {} for {}".format(commit, repository))
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    return response.json()["sha"]


def get_latest_release(repository, github_token):
    """ Gets the latest release object from github or None if there are no releases """
    url = "https://api.github.com/repos/{}/releases/latest".format(repository)
    headers = get_headers(github_token)
    logging.info("Fetching latest release for {}".format(repository))
    response = requests.get(url, headers=headers)
    if response.status_code == 404:
        return None
    response.raise_for_status()
    ret = response.json()
    return ret


def get_summary_from_commit(commit):