import requests
from PIL import Image
from io import BytesIO
import os

def validate_image(url):
    try:
        r = requests.get(url)
        if r.status_code != 200 or len(r.content) > 5 * 1024 * 1024:
            return False
        img = Image.open(BytesIO(r.content))
        if img.format.lower() not in ["jpg", "jpeg", "png", "webp", "gif"]:
            return False
        return img
    except Exception:
        return False

def resize_image(img, target_width=1200, target_height=627):
    w, h = img.size
    ratio_target = target_width / target_height
    ratio_current = w / h

    if (w, h) != (target_width, target_height):
        if ratio_current > ratio_target:
            new_h = target_height
            new_w = int(new_h * ratio_current)
        else:
            new_w = target_width
            new_h = int(new_w / ratio_current)

        img = img.resize((new_w, new_h), Image.Resampling.LANCZOS)
        left = (new_w - target_width) // 2
        top = (new_h - target_height) // 2
        img = img.crop((left, top, left + target_width, top + target_height))

    return img
