import os
import re
from pathlib import Path


def convert_svg_folder(input_folder, output_folder):
    # Create the output folder if it doesn't exist
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # Loop through all SVG files in the input folder
    for filename in os.listdir(input_folder):
        if filename.endswith(".svg"):
            input_path = os.path.join(input_folder, filename)
            output_path = os.path.join(output_folder, filename)
            convert_svg(input_path, output_path)
        elif os.path.isdir(os.path.join(input_folder, filename)):
            convert_svg_folder(os.path.join(input_folder, filename), os.path.join(output_folder, filename))


def convert_svg(input_path, output_path):
    try:
        with open(input_path, 'r') as f:
            svg_content = f.read()

        path_d = re.findall(r'\bd="([^"]+)"', svg_content)

        width = re.search(r'width="(\d+)"', svg_content).group(1)
        height = re.search(r'height="(\d+)"', svg_content).group(1)
        viewbox = re.search(r'viewBox="([^"]+)"', svg_content).group(1)

        # Constructing the new SVG string
        new_svg = f'<svg enable-background="new 0 0 {width} {height}" height="{height}" viewBox="{viewbox}" width="{width}" xmlns="http://www.w3.org/2000/svg">\n'
        for path_tag in path_d:
            new_svg += f'<path d="{path_tag}" fill="param(fill)" fill-opacity="param(fill-opacity)" stroke="param(outline)" stroke-opacity="param(outline-opacity)" stroke-width="param(outline-width)"/>\n'
        new_svg += '</svg>'

        # Writing the new SVG to the output file
        with open(output_path, 'w') as f:
            f.write(new_svg)
    except Exception as e:
        print(f"Error converting SVG: {e}")


# Example usage
output_folder = Path(os.path.dirname(os.path.abspath(__file__))) / "data/svgs/hydrants"
input_folder = Path(os.path.dirname(os.path.abspath(__file__))) / "data/raw_svgs/hydrants"
convert_svg_folder(input_folder, output_folder)
