#!/usr/bin/env python3

import os
import argparse
import shutil
import sys
import subprocess

def warning(msg: str) -> None:
    print('\033[1;93m' + msg + '\033[0m')

def error(msg: str) -> None:
    print('\033[1;31m' + msg + '\033[0m')

def executable(path: str) -> str:
    if not shutil.which(path):
        error(f"executable path '{path}' is not found")
        raise argparse.ArgumentTypeError

    return path

def main() -> None:
    parser = argparse.ArgumentParser(
                    prog='covreport',
                    description='Generate an HTML coverage report from an LCOV tracefile.')
    parser.add_argument('-g', '--genhtml', default="genhtml", type=executable, help="genhtml binary")
    parser.add_argument('-t', '--tracefile', help="Path to the LCOV tracefile")
    parser.add_argument('-o', '--output', required=True, help="Output directory")
    args = parser.parse_args()

    verbose = False
    if int(os.environ.get('VERBOSE', '0')):
        verbose = True

    if not os.path.exists(args.tracefile):
        warning(f"Tracefile '{args.tracefile}' not found, ignoring")
        sys.exit(0)

    cmd = [
        args.genhtml,
        '--output-directory', args.output,
        args.tracefile
    ]

    output = subprocess.run(cmd, capture_output=True)
    if output.returncode != 0:
        print(output.stderr.decode("utf-8"), end="\n")
        error("failed to generate the coverage report")
        sys.exit(-1)
    elif verbose:
        print(output.stdout.decode("utf-8"), end="\n")


if __name__ == '__main__':
    main()
