# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you 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.
# pylint: disable=superfluous-parens, redefined-outer-name, redefined-outer-name,pointless-string-statement
# pylint: disable=consider-using-enumerate,invalid-name
"""Tuning record and serialization format"""

import argparse
import base64
import logging
import multiprocessing
import pickle
import json
import time
import os
import itertools
from collections import OrderedDict
import numpy as np

from .. import build, lower
from ..target import Target
from .. import __version__
from . import task
from .task import ConfigEntity, ApplyHistoryBest
from .measure import MeasureInput, MeasureResult

AUTOTVM_LOG_VERSION = 0.2
_old_version_warning = True
logger = logging.getLogger("autotvm")

try:  # convert unicode to str for python2
    _unicode = unicode
except NameError:
    _unicode = ()

try:
    _long = long
except NameError:
    _long = int


def measure_str_key(inp, include_config=True):
    """get unique str key for MeasureInput

    Parameters
    ----------
    inp: autotvm.measure.MeasureInput
        input for the measure
    include_config: bool, optional
        whether includes config in the str key

    Returns
    -------
    key: str
        The str representation of key
    """
    config_str = str(inp.config) if include_config else ""
    return "".join(
        [str(inp.target), inp.task.name, str(inp.task.args), str(inp.task.kwargs), config_str]
    )


def encode(inp, result, protocol="json"):
    """encode (MeasureInput, MeasureResult) pair to a string

    Parameters
    ----------
    inp: autotvm.measure.MeasureInput
    result: autotvm.measure.MeasureResult
        pair of input/result
    protocol: str
        log protocol, json or pickle

    Returns
    -------
    row: str
        a row in the logger file
    """

    if protocol == "json":
        json_dict = {
            "input": (str(inp.target), inp.task.name, inp.task.args, inp.task.kwargs),
            "config": inp.config.to_json_dict(),
            "result": (
                result.costs if result.error_no == 0 else (1e9,),
                result.error_no,
                result.all_cost,
                result.timestamp,
            ),
            "version": AUTOTVM_LOG_VERSION,
            "tvm_version": __version__,
        }
        return json.dumps(json_dict)
    if protocol == "pickle":
        row = (
            str(inp.target),
            str(
                base64.b64encode(
                    pickle.dumps([inp.task.name, inp.task.args, inp.task.kwargs])
                ).decode()
            ),
            str(base64.b64encode(pickle.dumps(inp.config)).decode()),
            str(base64.b64encode(pickle.dumps(tuple(result))).decode()),
            str(AUTOTVM_LOG_VERSION),
            str(__version__),
        )
        return "\t".join(row)

    raise RuntimeError("Invalid log protocol: " + protocol)


def decode(row, protocol="json"):
    """Decode encoded record string to python object

    Parameters
    ----------
    row : str
        a row in the logger file

    protocol : str
        log protocol, json or pickle

    Returns
    -------
    ret : tuple(autotvm.measure.MeasureInput, autotvm.measure.MeasureResult), or None
        The tuple of input and result, or None if input uses old version log format.
    """
    # pylint: disable=unused-variable
    global _old_version_warning

    if protocol == "json":
        row = json.loads(row)
        if "v" in row and row["v"] == 0.1:
            if _old_version_warning:
                logger.warning("AutoTVM log version 0.1 is no longer supported.")
                _old_version_warning = False
            return None

        tgt, task_name, task_args, task_kwargs = row["input"]
        tgt = str(tgt)
        if "-target" in tgt: