# assets/python/svgLinksToPath.py
import sys
import os
from lxml import etree
from urllib.parse import urlparse

class LinkToPathConverter:
    def __init__(self, wp_content_path):
        self.wp_content_path = wp_content_path
        self.namespaces = {
            'svg': 'http://www.w3.org/2000/svg',
            'xlink': 'http://www.w3.org/1999/xlink'
        }

    def getPath(self, url):
        urlSplitter = '/wp-content/'
        splitUrl = url.split(urlSplitter)

        if len(splitUrl) != 2:
            return False

        new_path = self.wp_content_path + splitUrl[1]

        if os.path.exists(new_path):
            print('path exists')
        else:
            print('path doesnt exist')

        print(f"New Path: {new_path}")

        return new_path

    def saveFile(self,data, new_file_path):
        try:
            with open(new_file_path, 'wb') as f:
                f.write(data)
            print(f"Saved result to: {new_file_path}")

            # Log file sizes for comparison
            new_size = os.path.getsize(new_file_path)
            print(f"New size: {new_size} bytes")

        except Exception as e:
            print(f"Error saving file: {e}")
            sys.exit(1)

    def processLinks(self, file_path):
        try:
            if not os.path.exists(file_path):
                print(f"File not found {file_path}")
                return False

            parser = etree.XMLParser(strip_cdata=False, recover=True, huge_tree=True)
            tree = etree.parse(file_path, parser)
            root = tree.getroot()

            print(f"Successfully parsed SVG: {file_path}")
            print(f"Root tag: {root.tag}")

            images = root.xpath('//svg:image[@xlink:href or @href]', namespaces=self.namespaces)
            print(f"Found {len(images)} image elements")

            processed_count = 0

            for image in images:
                href = image.get('{http://www.w3.org/1999/xlink}href') or image.get('href')

                # Skip if already a data URI
                if href and href.startswith('data:'):
                    print(f"Skipping already embedded data URI")
                    continue

                print(f"Processing image href: {href}")

                local_file_path = self.getPath(href)

                if local_file_path:

                    if image.get('{http://www.w3.org/1999/xlink}href'):
                        image.set('{http://www.w3.org/1999/xlink}href', local_file_path)
                    processed_count += 1
                else:
                    print(f"Could not resolve local path for: {href}")

            print(f"Successfully processed {processed_count} images")
            result = etree.tostring(root, encoding='UTF-8', method='xml')

            return result

        except etree.XMLSyntaxError as e:
            print(f"XML parsing error: {e}")
            return None
        except Exception as e:
            print(f"Error processing SVG: {e}")
            return None

def main():
    print('starting link conversion')

    if len(sys.argv) < 2:
        print("Usage: python svg_processor.py <file_path> <new_path> <relative_wp_upload_path> [output_path]", file=sys.stderr)
        sys.exit(1)

    file_path = sys.argv[1]
    new_path = sys.argv[2]
    standard_relative_path = '../wp-content/'
    relative_wp_uploads = sys.argv[3] if len(sys.argv) > 3 else standard_relative_path

    converter_class = LinkToPathConverter(relative_wp_uploads)
    svg_with_paths = converter_class.processLinks(file_path)

    if svg_with_paths:
        converter_class.saveFile(svg_with_paths, new_path)
        print("Processing successful!")
    else:
        print("Processing failed!")
        sys.exit(1)


if __name__ == "__main__":
    main()

