from flask import Flask, request, send_file, render_template, redirect, url_for
from PIL import Image
import os, zipfile
from io import BytesIO

app = Flask(__name__, static_url_path='/main/static', static_folder='static', template_folder='templates')
UPLOAD_FOLDER = "uploads"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

# Android Play Store required sizes
sizes = {
    "phone_portrait": (1080, 1920),
    "phone_landscape": (1920, 1080),
    "tablet7_portrait": (1200, 1920),
    "tablet10_landscape": (1920, 1200),
    "tv": (1920, 1080),
    "wear_square": (384, 384),
    "wear_rectangular": (640, 400)
}

@app.route('/main/')
def index():
    return render_template("index.html")

@app.route('/main/upload', methods=['POST'])
def upload():
    files = request.files.getlist("images")
    zip_buffer = BytesIO()

    with zipfile.ZipFile(zip_buffer, 'w') as zip_file:
        for file in files:
            if file and file.filename.lower().endswith(('.png', '.jpg', '.jpeg')):
                img = Image.open(file)
                base = os.path.splitext(file.filename)[0]
                for label, size in sizes.items():
                    resized_img = img.resize(size, resample=Image.Resampling.LANCZOS)
                    img_io = BytesIO()
                    resized_img.save(img_io, format='PNG')
                    img_io.seek(0)
                    zip_file.writestr(f"{base}_{label}.png", img_io.read())

    zip_buffer.seek(0)
    return send_file(zip_buffer, as_attachment=True, download_name="resized_screenshots.zip", mimetype='application/zip')

@app.route('/main/loading')
def loading():
    return render_template("loading.html")

@app.route('/main/submit_upload', methods=['GET', 'POST'])
def submit_upload():
    return redirect(url_for('index'))

if __name__ == "__main__":
    app.run(debug=True)
