from flask import Flask, render_template, request, jsonify, send_from_directory, url_for
import os
from werkzeug.utils import secure_filename
from detector import CrackDetector

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'uploads')
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16 MB limit

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

detector = CrackDetector()

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

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'})
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'})
        
    if file:
        filename = secure_filename(file.filename)
        input_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        output_filename = 'processed_' + filename
        output_path = os.path.join(app.config['UPLOAD_FOLDER'], output_filename)
        
        file.save(input_path)
        
        try:
            is_cracked, severity, confidence, thickness_mm = detector.detect_and_draw(input_path, output_path)
            
            return jsonify({
                'success': True,
                'is_cracked': is_cracked,
                'severity': severity,
                'thickness_mm': f"{thickness_mm:.2f} mm" if is_cracked else "0.00 mm",
                'confidence': f"{confidence*100:.1f}%",
                'original_url': url_for('static', filename=f'uploads/{filename}'),
                'processed_url': url_for('static', filename=f'uploads/{output_filename}')
            })
        except Exception as e:
            return jsonify({'error': str(e)})

if __name__ == '__main__':
    # Local development only — cPanel Passenger runs the app directly
    app.run(debug=True, port=5000)
