import sys

from .utils import MirrorException


def get_repo_api(config):
    global parse_conda
    try:
        from anaconda_enterprise.cli.parse import parse_conda
        from anaconda_enterprise.cli import config as ap_config
        from anaconda_enterprise.cli import api as ap_api
    except ImportError:
        raise MirrorException("Please install the 'anaconda-enterprise-cli' package.")
    ap_config.config.load_schema()
    ap_config.config.load_files()
    ap_config.config.component = [
        "sites",
        config.dest_site or ap_config.config["default_site"],
    ]
    ap_tokens = ap_api.TokenStore(ap_config.config.token_path)
    api = ap_api.ApiClient(ap_config.config, ap_tokens)
    if config.verify_ssl_dst:
        config.verify_ssl_dst = ap_config.config["ssl_verify"]
    ssl_verify = config.verify_ssl_mode("dst")
    api.session.verify = api.file_session.verify = ssl_verify
    # The anaconda-enterprise-cli api object provides a retry capability
    # so we can simply feed it our configurable max_attempts value
    ap_api.RETRIES = config.max_attempts or 5
    api.check()
    config.dest_channel_alias = api.make_absolute(api.links["conda"].url)
    config.valid_formats = ("tarbz2",)
    return api


def begin_channel(api, cname, dry_run):
    for channel in api._json_api("channels"):
        if channel["attributes"]["name"] == cname:
            api.channel_record = channel
            return
    raise MirrorException("Channel not found: %s" % cname)


def del_object(api, cname, platform, fn, metadata=None):
    try:
        api._json_api("files/" + metadata["extra"]["id"], method="DELETE")
    except Exception as exc:
        if "404 (Not Found)" not in str(exc):
            raise MirrorException(str(exc))


def put_object(api, cname, platform, fn, path_or_data=None, metadata=None):
    attrs = parse_conda(path_or_data)
    adict = metadata.copy()
    adict["fn"] = fn
    attrs["index-attributes"] = adict
    try:
        response = api.stage_file(api.channel_record, attrs)
        if "has-icon" in attrs["recipe-attributes"]:
            api.upload_icon(response, path_or_data)
        with open(path_or_data, "rb") as fd:
            api.upload_file(response, fd)
    except Exception as exc:
        message = getattr(exc, "message", None) or str(exc)
        status = getattr(exc, "status", 0)
        if status == 409 or "409" in message:
            return
        if status != 0:
            message = "status %d, %s" % (status, message)
        raise MirrorException(message)


def main():
    from .common import main as _main

    _main(sys.modules[__name__])
