from flask import Flask, render_template, request, jsonify, send_from_directory, make_response
from qr_generator import generate_qr_images
import os
from werkzeug.utils import secure_filename
from PIL import Image
import traceback

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg'}

os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

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

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

@app.route('/upload', methods=['POST'])
def upload_image():
    if 'background' not in request.files:
        return jsonify({'error': 'No file uploaded'}), 400

    file = request.files['background']
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400

    if not allowed_file(file.filename):
        return jsonify({'error': 'Invalid file type'}), 400

    filename = secure_filename(file.filename)
    filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    file.save(filepath)

    with Image.open(filepath) as img:
        width, height = img.size

    return jsonify({
        'filename': filename,
        'url': f'/uploads/{filename}',
        'width': width,
        'height': height
    })

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

@app.route('/generate', methods=['POST'])
def generate_images():
    try:
        data = request.get_json()
        required = ['image', 'qrData', 'startNum', 'endNum', 'increment', 'canvasWidth', 'canvasHeight']
        if not all(key in data for key in required):
            return jsonify({'error': 'Missing required parameters'}), 400

        image_path = os.path.join(app.config['UPLOAD_FOLDER'], data['image'])
        if not os.path.exists(image_path):
            return jsonify({'error': 'Image not found'}), 404

        with Image.open(image_path) as img:
            original_width, original_height = img.size

        scale_x = original_width / data['canvasWidth']
        scale_y = original_height / data['canvasHeight']

        scaled_qr_data = []
        for qr in data['qrData']:
            scaled_qr_data.append({
                'x': int(qr['x'] * scale_x),
                'y': int(qr['y'] * scale_y),
                'width': int(qr['width'] * scale_x),
                'height': int(qr['height'] * scale_y)
            })

        leading_zeros = int(data.get('leadingZeros', 0))
        text_color = data.get('textColor', '#000000')  # Default to black if not provided

        zip_buffer = generate_qr_images(
            image_path=image_path,
            qr_data=scaled_qr_data,
            start_num=int(data['startNum']),
            end_num=int(data['endNum']),
            increment=int(data['increment']),
            show_text=data.get('showText', False),
            leading_zeros=leading_zeros + 1,
            text_color=text_color
        )

        zip_buffer.seek(0)
        response = make_response(zip_buffer.read())
        response.headers['Content-Type'] = 'application/zip'
        response.headers['Content-Disposition'] = 'attachment; filename=qr_images.zip'
        return response

    except Exception as e:
        return jsonify({
            'error': str(e),
            'traceback': traceback.format_exc()
        }), 500

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