import argparse
from PIL import Image, ImageDraw, ImageFont
import textwrap
import os
from typing import Optional

def generate_og_image(title: str, subtitle: str, output_path: str = "og_image.png") -> None:
    """
    Generates an Open Graph image with a gradient background, title, and subtitle.

    Args:
        title: The title of the blog post.
        subtitle: The subtitle of the blog post.
        output_path: The path where the image will be saved. Defaults to "og_image.png".
    """

    width = 1200
    height = 630
    
    try:
        # Create a new image with a gradient background
        image = Image.new("RGB", (width, height), "white")
        draw = ImageDraw.Draw(image)

        # Define gradient colors
        color1 = (66, 135, 245)  # Light blue
        color2 = (173, 216, 230)  # Light gray-blue

        # Create the gradient
        for i in range(height):
            r = int(color1[0] + (color2[0] - color1[0]) * i / height)
            g = int(color1[1] + (color2[1] - color1[1]) * i / height)
            b = int(color1[2] + (color2[2] - color1[2]) * i / height)
            draw.line([(0, i), (width, i)], fill=(r, g, b))

        # Load fonts
        title_font_size = 80
        subtitle_font_size = 36
        try:
            title_font = ImageFont.truetype("arial.ttf", title_font_size)
            subtitle_font = ImageFont.truetype("arial.ttf", subtitle_font_size)
        except IOError:
            print("Arial font not found. Using default font.")
            title_font = ImageFont.load_default()
            subtitle_font = ImageFont.load_default()
            
        # Calculate title position
        title_width, title_height = draw.textsize(title, font=title_font)
        title_x = (width - title_width) / 2
        title_y = (height - title_height - subtitle_font_size - 20) / 2

        # Calculate subtitle position
        subtitle_width, subtitle_height = draw.textsize(subtitle, font=subtitle_font)
        subtitle_x = (width - subtitle_width) / 2
        subtitle_y = title_y + title_height + 10
        
        # Wrap the title text if it's too long
        max_title_width = width * 0.8  # Limit title width to 80% of image width
        wrapped_title = textwrap.wrap(title, width=int(max_title_width / title_font_size * 1.5)) # Adjust multiplier as needed
        
        # Draw the wrapped title
        current_y = title_y
        for line in wrapped_title:
            line_width, line_height = draw.textsize(line, font=title_font)
            line_x = (width - line_width) / 2
            draw.text((line_x, current_y), line, font=title_font, fill="black")
            current_y += line_height
        
        # Draw the subtitle
        draw.text((subtitle_x, subtitle_y), subtitle, font=subtitle_font, fill="black")

        # Save the image
        image.save(output_path, "PNG")
        print(f"Open Graph image saved to {output_path}")

    except Exception as e:
        print(f"Error generating Open Graph image: {e}")

def main():
    """
    Main function to parse arguments and generate the Open Graph image.
    """
    parser = argparse.ArgumentParser(description="Generate Open Graph images for blog posts.")
    parser.add_argument("title", help="The title of the blog post.")
    parser.add_argument("subtitle", help="The subtitle of the blog post.")
    parser.add_argument("-o", "--output", help="The output path for the image (default: og_image.png)", default="og_image.png")

    args = parser.parse_args()

    generate_og_image(args.title, args.subtitle, args.output)

if __name__ == "__main__":
    main()