from flask import Flask, render_template, request, send_file, jsonify, redirect, url_for
from PIL import Image
import numpy as np
import io
import base64
import os
import uuid
import gc

app = Flask(__name__)

UPLOAD_FOLDER = "processed"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/upload", methods=["POST"])
def upload():
    if "image" not in request.files:
        return redirect(url_for("index"))

    file = request.files["image"]

    if file.filename == "":
        return redirect(url_for("index"))

    img = Image.open(file).convert("RGB")

    # PIL -> numpy
    arr = np.array(img)

    # grayscale sederhana
    gray = np.mean(arr, axis=2).astype(np.uint8)

    # numpy -> PIL
    result_img = Image.fromarray(gray)

    filename = f"{uuid.uuid4()}.png"
    filepath = os.path.join(UPLOAD_FOLDER, filename)
    result_img.save(filepath)

    # convert ke base64 buat preview
    buffer = io.BytesIO()
    result_img.save(buffer, format="PNG")
    encoded_img = base64.b64encode(buffer.getvalue()).decode("utf-8")

    gc.collect()

    return render_template(
        "index.html",
        image_data=encoded_img,
        filename=filename
    )


@app.route("/download/<filename>")
def download(filename):
    filepath = os.path.join(UPLOAD_FOLDER, filename)
    return send_file(filepath, as_attachment=True)


@app.route("/api/status")
def status():
    return jsonify({
        "status": "ok",
        "message": "Flask image processor aktif"
    })


if __name__ == "__main__":
    app.run(debug=True)