import os
import sys
import argparse
import xml.etree.ElementTree as ET

def calculate_overall_coverage(xml_file):
    tree = ET.parse(xml_file)
    root = tree.getroot()

    total_lines = 0
    covered_lines = 0

    for package in root.findall('packages/package'):
        for classes in package.findall('classes/class'):
            for lines in classes.findall('lines/line'):
                total_lines += 1
                if lines.get('hits') != '0':
                    covered_lines += 1

    overall_coverage = (covered_lines / total_lines) * 100 if total_lines > 0 else 0
    return overall_coverage

def write_summery_file_content(content, summery_env_variable_name):
    try:
        summery_file = os.environ.get(summery_env_variable_name)
        with open(summery_file, "a") as file:
            file.write(content)
    except FileNotFoundError:
        print(f"File '{file_path}' not found.")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Parse XML file with optional folder.')
    parser.add_argument('--cobertura_xml_file', help='Path to the cobertura XML file.', required=True)
    parser.add_argument('--coverage_threshold', type=int, nargs='?', help='Code coverage minimal threshold.', default=70)
    parser.add_argument('--summery_env_variable_name', type=str, nargs='?', help='Github action job summery file environment variable name.', default="GITHUB_STEP_SUMMARY")
    parser.add_argument('--fail_pipeline', type=str, nargs='?', help='Force pipeline fail if coverage failed.', default="true")
    args = parser.parse_args()

    xml_file_path = args.cobertura_xml_file
    coverage_threshold = args.coverage_threshold
    summery_env_variable_name = args.summery_env_variable_name
    fail_pipeline = args.fail_pipeline.lower()

    overall_coverage = int(calculate_overall_coverage(xml_file_path))

    print(f'Overall Coverage: {overall_coverage}%')

    if 30 < overall_coverage < coverage_threshold:
       color = "yellow"
    elif overall_coverage >= coverage_threshold:
       color = "green"
    else:
       color = "red"

    content = f'![Coverage](https://img.shields.io/badge/coverage-{overall_coverage}%25-{color})'

    write_summery_file_content(content, summery_env_variable_name)

    if overall_coverage < coverage_threshold and fail_pipeline == "true":
        sys.exit(f"CodeCoverage Error: Code coverage is less than {coverage_threshold}%.")
