#!/usr/bin/env python
"""
Simple SVG to PNG Converter Script

This script creates PNG placeholders for SVG files.
It doesn't actually convert the SVG content, but creates a PNG with the same dimensions
and a placeholder text indicating it's a converted SVG.

Requirements:
- Python 3.6+
- Pillow library (install with: pip install pillow)
"""

import os
import sys
import re
from pathlib import Path

try:
    from PIL import Image, ImageDraw, ImageFont
except ImportError:
    print("Error: Pillow library not found.")
    print("Please install it using: pip install pillow")
    print("If you don't have pip installed, you can use: python -m ensurepip")
    sys.exit(1)

# List of SVG files to convert
SVG_FILES = [
    "images/backgrounds/login-bg.svg",
    "images/countries/sa.svg",
    "images/countries/ye.svg",
    "images/logo/company-logo.svg",
    "pages/images/flags/china.svg",
    "pages/images/flags/oman.svg",
    "pages/images/flags/saudi.svg",
    "pages/images/flags/yemen.svg"
]

def extract_dimensions_from_svg(svg_path):
    """
    Extract width and height from an SVG file.
    
    Args:
        svg_path (str): Path to the SVG file
    
    Returns:
        tuple: (width, height) as integers, or (800, 600) if not found
    """
    try:
        with open(svg_path, 'r', encoding='utf-8') as f:
            content = f.read()
            
            # Try to find width and height in SVG tag
            width_match = re.search(r'width="(\d+)', content)
            height_match = re.search(r'height="(\d+)', content)
            
            width = int(width_match.group(1)) if width_match else 800
            height = int(height_match.group(1)) if height_match else 600
            
            return width, height
    except Exception as e:
        print(f"Error extracting dimensions from {svg_path}: {str(e)}")
        return 800, 600

def create_png_placeholder(svg_path, png_path):
    """
    Create a PNG placeholder for an SVG file.
    
    Args:
        svg_path (str): Path to the SVG file
        png_path (str): Path where the PNG file will be saved
    
    Returns:
        bool: True if creation was successful, False otherwise
    """
    try:
        # Ensure the output directory exists
        os.makedirs(os.path.dirname(png_path), exist_ok=True)
        
        # Get dimensions from SVG
        width, height = extract_dimensions_from_svg(svg_path)
        
        # Create a new image with white background
        image = Image.new('RGBA', (width, height), (255, 255, 255, 255))
        draw = ImageDraw.Draw(image)
        
        # Draw a border
        draw.rectangle([(0, 0), (width-1, height-1)], outline=(200, 200, 200))
        
        # Add text
        try:
            font = ImageFont.truetype("arial.ttf", 20)
        except IOError:
            font = ImageFont.load_default()
        
        svg_name = os.path.basename(svg_path)
        text = f"Converted from {svg_name}"
        
        # Calculate text position to center it
        text_width = draw.textlength(text, font=font)
        text_height = 20  # Approximate height
        
        text_x = (width - text_width) // 2
        text_y = (height - text_height) // 2
        
        # Draw text
        draw.text((text_x, text_y), text, fill=(0, 0, 0), font=font)
        
        # Save the image
        image.save(png_path, 'PNG')
        
        print(f"Successfully created PNG placeholder for {svg_path} at {png_path}")
        return True
    except Exception as e:
        print(f"Error creating PNG placeholder for {svg_path}: {str(e)}")
        return False

def process_svg_files(svg_files=None, base_dir=None):
    """
    Process a list of SVG files and create PNG placeholders.
    
    Args:
        svg_files (list, optional): List of SVG file paths to process
        base_dir (str, optional): Base directory for resolving relative paths
    
    Returns:
        int: Number of successfully created PNG files
    """
    if svg_files is None:
        svg_files = SVG_FILES
    
    if base_dir:
        # Make paths absolute
        svg_files = [os.path.join(base_dir, f) for f in svg_files]
    
    success_count = 0
    
    for svg_file in svg_files:
        # Create PNG path by replacing extension
        png_file = os.path.splitext(svg_file)[0] + ".png"
        
        print(f"Processing {svg_file} to {png_file}...")
        
        # Check if SVG file exists
        if not os.path.exists(svg_file):
            print(f"Error: SVG file not found: {svg_file}")
            continue
        
        # Create the PNG placeholder
        if create_png_placeholder(svg_file, png_file):
            success_count += 1
    
    return success_count

def main():
    """Main function to run the conversion."""
    # Process the files
    success_count = process_svg_files()
    
    print(f"\nConversion complete. Successfully created {success_count} out of {len(SVG_FILES)} PNG placeholders.")

if __name__ == "__main__":
    main()
