#!/usr/bin/env python3

import argparse
from e3.gaia.api import GAIA
from e3.testsuite.report.rewriting import BaseBaselineRewriter, RewritingError
from e3.testsuite.utils import ColorConfig
import os.path
import tarfile
import tempfile

descr = """This script updates the outputs from a previous run of the
testsuite."""


def parse_options():
    args = None
    parser = argparse.ArgumentParser(description=descr)
    parser.add_argument(
        "-o",
        "--output-dir",
        dest="outputdir",
        help="Specify the output dir to read outputs from",
    )
    parser.add_argument(
        "--from-gaia",
        dest="gaia_id",
        help="Specify the GAIA event id to read outputs from",
    )
    parser.add_argument(
        "--from-gitlab",
        dest="gitlab_id",
        help="Specify the Gitlab pipeline id to read outputs from",
    )
    args = parser.parse_args()
    if (
        (args.outputdir and args.gitlab_id)
        or (args.outputdir and args.gaia_id)
        or (args.gitlab_id and args.gaia_id)
    ):
        print("please provide only one of (--output-dir, --from-gaia, --from-gitlab)")
        exit(1)
    return args


missing_package_msg = """
Could not find the remote_artifacts package. Do the following and try again:

    python -m pip install git+ssh://ssh.gitlab.adacore-it.com/kanig/remote_artifacts.git
"""


class BaselineRewriter(BaseBaselineRewriter):
    def baseline_filename(self, test_name: str) -> str:
        testdir = os.path.join("tests", test_name)
        if not os.path.exists(testdir):
            testdir = os.path.join("internal", test_name)
        if not os.path.exists(testdir):
            testdir = os.path.join("sparklib", test_name)
        if not os.path.exists(testdir):
            raise RewritingError(f"cannot find test {test_name!r}")
        return os.path.join(testdir, "test.out")


def get_single_subdir(d):
    entry = os.listdir(d)[0]
    return os.path.join(d, entry)


def download_from_gaia(gaia_id):
    g = GAIA()
    r = g.request("GET", f"event/attachment/{gaia_id}/tests_log")
    with tempfile.NamedTemporaryFile("wb", suffix=".tgz", delete=False) as f:
        for chunk in r:
            f.write(chunk)
        name = f.name
    tmpdir = tempfile.mkdtemp()
    with tarfile.open(name, mode="r:gz") as tar:
        tar.extractall(tmpdir)
    return get_single_subdir(tmpdir)


def main():
    args = parse_options()
    if args.gaia_id:
        tmpdir = download_from_gaia(args.gaia_id)
        outputdirs = [tmpdir]
    elif args.gitlab_id:
        try:
            from remote_artifacts import Gitlab, GitLabProjectDescription
        except ImportError:
            print(missing_package_msg)
            exit(1)
        p = GitLabProjectDescription("168", ["spark2014"])
        gl = Gitlab()
        outputdirs = gl.download_test_results(p, args.gitlab_id)
    elif args.outputdir:
        outputdirs = [args.outputdir]
    else:
        outputdirs = [os.path.join("out", "new")]
    BR = BaselineRewriter(ColorConfig())
    for d in outputdirs:
        summary = BR.rewrite(d)
        for elt in summary.new_baselines:
            print(f"updated baseline for {elt}")
        for elt in summary.deleted_baselines:
            print(f"deleted empty baseline for {elt}")
        for elt in summary.errors:
            print(f"error updating baseline for {elt}")


main()
