from PIL import Image
import os
import shutil

BASE_PATH = "/Users/chudy/Library/Application Support/Kodi/addons/plugin.video.milionar/resources/media"

# Cards to fix (remove white borders)
GOOD_CARD = "ai_card_movies.png"
BAD_CARDS = [
    "ai_card_series.png",
    "ai_card_actors.png",
    "ai_card_collections.png",
    "ai_card_history.png"
]

def clean_borders():
    # 1. Get Reference Color from Good Card
    good_path = os.path.join(BASE_PATH, GOOD_CARD)
    with Image.open(good_path) as ref_img:
        ref_img = ref_img.convert("RGBA")
        # Sample center pixel
        cx, cy = ref_img.width // 2, ref_img.height // 2
        bg_color = ref_img.getpixel((cx, cy))
        print(f"Sampled Background Color from {GOOD_CARD}: {bg_color}")

    # 2. Process Bad Cards
    margin = 15 # Crop 15px from each side to remove artifacts
    
    for card_name in BAD_CARDS:
        card_path = os.path.join(BASE_PATH, card_name)
        if not os.path.exists(card_path):
            continue
            
        print(f"Cleaning {card_name}...")
        try:
            with Image.open(card_path) as img:
                img = img.convert("RGBA")
                w, h = img.size
                
                # Create a new solid background canvas
                clean_img = Image.new("RGBA", (w, h), bg_color)
                
                # Crop the content to remove bad edges
                # box = (left, top, right, bottom)
                content = img.crop((margin, margin, w - margin, h - margin))
                
                # Paste content into center of new canvas
                clean_img.paste(content, (margin, margin))
                
                # Save
                clean_img.save(card_path)
                print(f" -> Fixed borders for {card_name}")
                
        except Exception as e:
            print(f"Error fixing {card_name}: {e}")

if __name__ == "__main__":
    clean_borders()
