#!/usr/bin/env python3
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file accompanying this file. This file 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 json
import time

from lib import litani


SLEEP_INTERVAL = 5
TIMEOUT = 1
cache_dir = litani.get_cache_dir()

ret = {
    "cache-dir": str(cache_dir),
    "successful": [],
    "failed": [],
    "in-progress": [],
}

pipelines = {}

run_json = None

timer = 0
while not (cache_dir / "run.json").exists():
    time.sleep(SLEEP_INTERVAL)
    timer += SLEEP_INTERVAL
    if timer > TIMEOUT:
        raise Exception(
            f"Timed out waiting for run.json to be generated. "
            f"Could not find file {cache_dir / 'run.json'}")

with open(cache_dir / "run.json") as f:
    run_json = json.load(f)
if not run_json:
    raise Exception("Failed to parse run.json")

for pipeline in run_json["pipelines"]:
    if pipeline["status"] == "success":
        ret["successful"].append(pipeline["name"])
    elif pipeline["status"] == "fail":
        ret["failed"].append(pipeline["name"])
    elif pipeline["status"] == "in_progress":
        ret["in-progress"].append(pipeline["name"])
    else:
        raise Exception(pipeline["status"])

print(json.dumps(ret, indent=2))
