import sys
import os
from PIL import Image, ImageOps
import qrcode
from io import BytesIO
import shutil

# Tracking link
promo_url = "https://SmartPhotoCropper.com?from=negativeTool"

# Detect script directory
if getattr(sys, 'frozen', False):
    script_dir = os.path.dirname(sys.executable)
else:
    script_dir = os.path.dirname(os.path.abspath(__file__))

input_folder = os.path.join(script_dir, "SmartPhotoCropper")
output_folder = os.path.join(script_dir, "ConvertedPositive")

# Create output folder if it doesn't exist
os.makedirs(output_folder, exist_ok=True)

# Show welcome message
print("="*60)
print("📸 Negative Maker - Powered by SmartPhotoCropper.com")
print("Fast photo negative converter. Clean, simple, and free.")
print(f"➡️  {promo_url}")
print("="*60)
print("")

# Supported image types
image_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.tiff']

# Check input folder
if not os.path.exists(input_folder):
    print(f"❌ Input folder not found: {input_folder}")
    input("Press Enter to exit...")
    exit(1)

# Gather image list
image_files = [f for f in os.listdir(input_folder) if any(f.lower().endswith(ext) for ext in image_extensions)]

total = len(image_files)
if total == 0:
    print("⚠️ No images found in 'orig' folder.")
    input("Press Enter to exit...")
    exit(0)

# Process images with progress counter
for i, filename in enumerate(image_files, start=1):
    print(f"🔄 Processing {i} of {total}: {filename}")
    try:
        img_path = os.path.join(input_folder, filename)
        img = Image.open(img_path)

        if img.mode != 'RGB':
            img = img.convert('RGB')

        inverted_img = ImageOps.invert(img)
        output_path = os.path.join(output_folder, filename)
        inverted_img.save(output_path)
    except Exception as e:
        print(f"❌ Failed to process {filename}: {e}")

print("\n✅ All done!")
print(f"Saved {total} image(s) to: {output_folder}")

# Show QR code
print("\n🔗 Scan to visit SmartPhotoCropper.com:")
print("\n")

# Generate and print QR code
qr = qrcode.QRCode(border=1)
qr.add_data(promo_url)
qr.make()
qr.print_ascii(invert=True)
print("\n")
input("\nPress Enter to exit...")