#!/usr/bin/env python3

import os
import sys

def modify_html_report(file_path, source_path_start, show_source_start = False):
    with open(file_path, 'r') as file:
        content = file.read()

    start_tag = "<div class='source-name-title'><pre>"
    end_tag = '</pre></div>'
    
    start_index = content.find(start_tag)
    end_index = content.find(end_tag, start_index)
    
    while start_index != -1 and end_index != -1:
        original_path = content[start_index + len(start_tag):end_index].strip()

        if original_path.find(".../") == -1:
            print(f"found: {original_path}")
            modified_path = original_path.split(f'/{source_path_start}/')[-1]

            if show_source_start:
                replacement = f".../{source_path_start}/{modified_path}"
            else:
                replacement = f".../{modified_path}"

            print(f"modified to: {replacement}")
            content = content[:start_index + len(start_tag)] + replacement + content[end_index:]
            start_index = content.find(start_tag, start_index + len(replacement))
            end_index = content.find(end_tag, start_index)

            with open(file_path, 'w') as file:
                file.write(content)
        else:
            print(f"  - Path already has leading .../")
            return

def main():
    if len(sys.argv) != 3:
        print("Usage: {} <reports_root_path> <source_path_start_at>".format(sys.argv[0]))
        sys.exit(1)

    reports_root = sys.argv[1]
    source_path_start = sys.argv[2]

    for root, _, files in os.walk(reports_root):
        for file in files:
            if file.endswith('.html'):
                print(f"Checking: {file}")
                file_path = os.path.join(root, file)
                modify_html_report(file_path, source_path_start)

if __name__ == "__main__":
    main()
