from flask import Flask, request, jsonify, send_from_directory
import fitz  # PyMuPDF
import os
import uuid

app = Flask(__name__)

# ইমেজ সেভ করার ফোল্ডার নাম
UPLOAD_FOLDER = 'extracted_images'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# ব্রাউজারে টেস্ট করার জন্য রুট ইউআরএল
@app.route('/', methods=['GET'])
def home():
    return jsonify({"success": True, "message": "Python API Server is Running Successfully!"})

@app.route('/imageextract/', methods=['POST'])
def image_extract():
    if 'file' not in request.files:
        return jsonify({"success": False, "error": "No file part"}), 400
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({"success": False, "error": "No selected file"}), 400

    if file and file.filename.lower().endswith('.pdf'):
        pdf_name = f"{uuid.uuid4().hex}.pdf"
        pdf_path = os.path.join(app.config['UPLOAD_FOLDER'], pdf_name)
        file.save(pdf_path)

        try:
            doc = fitz.open(pdf_path)
            images_found = {}
            image_count = 0
            
            # ইউআরএল-এর শেষে অতিরিক্ত স্ল্যাশ (/) থাকলে তা কেটে নেওয়া (ডাবল স্ল্যাশ এড়াতে)
            base_url = request.host_url.rstrip('/')

            for page_num in range(len(doc)):
                page = doc[page_num]
                # আধুনিক PyMuPDF-এর সাথে সামঞ্জস্যপূর্ণ মেথড
                image_list = page.get_images(full=True)
                
                for img_index, img in enumerate(image_list):
                    xref = img[0]
                    base_image = doc.extract_image(xref)
                    image_bytes = base_image["image"]
                    image_ext = base_image["ext"]

                    img_name = f"img_{uuid.uuid4().hex}.{image_ext}"
                    img_path = os.path.join(app.config['UPLOAD_FOLDER'], img_name)
                    
                    with open(img_path, "wb") as f:
                        f.write(image_bytes)

                    # সঠিক ও পরিচ্ছন্ন ইউআরএল ফরম্যাট তৈরি
                    if image_count == 0:
                        images_found["user-image"] = f"{base_url}/images/{img_name}"
                    elif image_count == 1:
                        images_found["sign-image"] = f"{base_url}/images/{img_name}"
                    
                    image_count += 1
                    if image_count >= 2:
                        break
                if image_count >= 2:
                    break

            doc.close()  # ডিলিট করার আগে ফাইলটি ক্লোজ করা বাধ্যতামূলক
            os.remove(pdf_path)

            return jsonify({
                "success": True,
                "images": images_found
            })

        except Exception as e:
            if 'doc' in locals():
                doc.close()
            if os.path.exists(pdf_path):
                os.remove(pdf_path)
            return jsonify({"success": False, "error": str(e)}), 500

    return jsonify({"success": False, "error": "Invalid file type"}), 400

@app.route('/images/<filename>')
def serve_image(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

if __name__ == '__main__':
    pass