from flask import render_template, request, jsonify, flash, redirect, url_for, current_app
from flask_wtf.csrf import CSRFError, generate_csrf
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm.exc import StaleDataError
from app.core import bp

@bp.app_errorhandler(404)
def page_not_found(e):
    # Check if the request expects JSON (API or AJAX request)
    if request.path.startswith('/api/') or \
       (request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html):
    
        return jsonify({
            "status": "error",
            "message": "Resource not found",
            "code": 404
        }), 404
    
    # Render 404.html page
    return render_template('errors/404.html'), 404

@bp.app_errorhandler(403)
def forbidden(e):
    if request.path.startswith('/api/') or \
       (request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html):
        return jsonify({
            "status": "error",
            "message": "Forbidden or Module Disabled",
            "code": 403
        }), 403
    return render_template('errors/403.html'), 403

@bp.app_errorhandler(405)
def handle_method_not_allowed(error):
    if request.path.startswith('/api') or \
       (request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html):
        allowed_methods = [str(m) for m in error.valid_methods] if hasattr(error, 'valid_methods') else []
        return jsonify({
            'status': 'error',
            'error': 'Method Not Allowed',
            'path': request.path,
            'allowed_methods': allowed_methods,
            'message': f'Only {allowed_methods} requests are supported.'
        }), 405
    return render_template('errors/405.html', error=error), 405

@bp.app_errorhandler(500)
def handle_internal_server_error(error):
    """
    Catches generic internal server errors (500) that are not specifically 
    caught by other handlers.
    """
    current_app.logger.error(f"Internal server error: {error}")
    
    if request.path.startswith('/api/') or \
       (request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html):
        return jsonify({
            "status": "error",
            "message": "Internal Server Error",
            "code": 500
        }), 500

    return render_template('errors/500.html'), 500

@bp.app_errorhandler(CSRFError)
def handle_csrf_error(e):
    """
    Handles CSRF errors intelligently for both AJAX and traditional form requests.
    """
    # [KEY LOGIC] Check if the client prefers JSON (AJAX) over HTML.
    # This is the most reliable way to detect requests from JavaScript.
    is_ajax = (
        request.accept_mimetypes.accept_json and
        not request.accept_mimetypes.accept_html
    )

    if is_ajax:
        # --- Flow for AJAX/Fetch ---
        # Send JSON response so it can be handled by JavaScript on the frontend.
        return jsonify({
            'message': 'Your security session has expired. The form has been updated, please try again.',
            'csrf_token': generate_csrf()
        }), 400
    else:
        # --- Flow for Traditional HTML Form ---
        # Show flash message and redirect back to the previous page.
        flash('Your security session expired. Please try submitting the form again.', 'warning')
        return redirect(request.referrer or url_for('core.index'))

@bp.app_errorhandler(OperationalError)
def handle_database_error(error):
    """
    Catches SQLAlchemy OperationalError globally, which is typically triggered 
    when the MySQL database is unreachable or the connection is actively refused.
    Returns a user-friendly error page with a 503 (Service Unavailable) status code.
    """
    # Best practice: Log the actual error to your terminal or log file
    current_app.logger.error(f"Database connection failed: {error}")
    
    # Check if the request expects JSON (API or AJAX request)
    if request.path.startswith('/api/') or \
       (request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html):
        return jsonify({
            "status": "error",
            "message": "Service Unavailable - Database connection failed",
            "code": 503
        }), 503

    # Render the custom UI/UX error page
    return render_template('errors/database_offline.html'), 503

@bp.app_errorhandler(StaleDataError)
def handle_stale_data_error(error):
    """
    Catches SQLAlchemy StaleDataError globally, which is triggered when
    optimistic locking fails (e.g., someone else updated the record while
    the current user was editing it).
    """
    current_app.logger.warning(f"Concurrency conflict detected: {error}")
    
    if request.path.startswith('/api/') or \
       (request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html):
        return jsonify({
            "status": "error",
            "message": "Data was modified by another user. Please refresh and try again.",
            "code": 409
        }), 409

    flash('The record you are trying to save was modified by another user since you opened it. Please refresh the page and apply your changes again to prevent overwriting their work.', 'danger')
    return redirect(request.referrer or url_for('core.index'))
