import os
import uuid
import datetime
from flask import Flask, request, jsonify, send_from_directory, url_for
from werkzeug.utils import secure_filename
from rembg import remove
from PIL import Image
import pyrebase

app = Flask(__name__)

# --- CONFIGURATION ---
UPLOAD_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uploads')
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16 MB limit

# Firebase Configuration provided by user
firebase_config = {
    "apiKey": "AIzaSyBbvPXObwEAp4E71PYKLFRGykxOz7b1WV0",
    "authDomain": "siddhabot-5793f.firebaseapp.com",
    "databaseURL": "https://siddhabot-5793f-default-rtdb.firebaseio.com",
    "projectId": "siddhabot-5793f",
    "storageBucket": "siddhabot-5793f.firebasestorage.app",
    "messagingSenderId": "829875187117",
    "appId": "1:829875187117:web:a666089b7e61477b94c524",
    "measurementId": "G-D518WR94HL"
}

# Initialize Firebase
firebase = pyrebase.initialize_app(firebase_config)
db = firebase.database()

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'webp'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def index():
    return jsonify({"status": "Image upload and background removal API is running."})

@app.route('/uploads/<filename>')
def serve_image(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

@app.route('/upload', methods=['POST'])
def upload_image():
    if 'image' not in request.files:
        return jsonify({"error": "No image part in the request"}), 400
    
    file = request.files['image']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400
        
    if file and allowed_file(file.filename):
        # 1. Generate unique ID and secure filename
        image_id = str(uuid.uuid4())
        original_ext = file.filename.rsplit('.', 1)[1].lower()
        final_filename = f"{image_id}.png" # rembg outputs PNG for transparency
        
        # 2. Process image with rembg
        try:
            input_image = Image.open(file)
            output_image = remove(input_image)
            
            # 3. Save final image to uploads folder
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], final_filename)
            output_image.save(filepath, format="PNG")
            
            # Construct the public URL for the image
            # Note: For production cPanel, request.host_url works dynamically
            image_url = request.host_url.rstrip('/') + url_for('serve_image', filename=final_filename)
            
            # 4. Save metadata to Firebase Realtime Database
            metadata = {
                "id": image_id,
                "url": image_url,
                "created_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
                "original_filename": file.filename
            }
            
            # Push to a node called 'uploaded_images'
            db.child("uploaded_images").child(image_id).set(metadata)
            
            # 5. Return success response mirroring ImgBB structure for easier Flutter integration
            # We return a structure somewhat similar to what Flutter might expect, or just a direct data object.
            return jsonify({
                "data": {
                    "id": image_id,
                    "url": image_url,
                    "display_url": image_url
                },
                "success": True,
                "status": 200
            }), 200
            
        except Exception as e:
            return jsonify({"error": str(e)}), 500

    return jsonify({"error": "Invalid file type"}), 400

if __name__ == '__main__':
    # Run in development mode
    app.run(debug=True, host='0.0.0.0', port=5000)
