import os
import sys
import logging
from datetime import datetime

# Add current directory to Python path to ensure modules can be imported
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from flask import Flask, render_template, session
from flask_session import Session
from werkzeug.middleware.proxy_fix import ProxyFix
from apscheduler.schedulers.background import BackgroundScheduler
from prometheus_flask_exporter import PrometheusMetrics

# Import our configuration and utilities
import config
from utils.backup import create_backup

# Import error handling system
from core.error_handlers import init_error_handlers
from core.logging_config import setup_logging
from core.monitoring import init_monitoring
from middleware.error_middleware import ErrorHandlingMiddleware

app = Flask(__name__)

# Initialize Prometheus metrics
metrics = PrometheusMetrics(app)
metrics.info('admin_panel_info', 'Admin Panel Information', version='1.0.0')
# Load configuration from config module
app.config['SECRET_KEY'] = config.SECRET_KEY
app.config['SESSION_TYPE'] = config.SESSION_TYPE
app.config['JSON_AS_ASCII'] = config.JSON_AS_ASCII
app.config['JSONIFY_MIMETYPE'] = config.JSONIFY_MIMETYPE
app.config['PERMANENT_SESSION_LIFETIME'] = config.PERMANENT_SESSION_LIFETIME
app.config['SESSION_COOKIE_HTTPONLY'] = config.SESSION_COOKIE_HTTPONLY
app.config['SESSION_COOKIE_SECURE'] = config.SESSION_COOKIE_SECURE
app.config['SESSION_COOKIE_SAMESITE'] = config.SESSION_COOKIE_SAMESITE
app.config['SESSION_COOKIE_NAME'] = config.SESSION_COOKIE_NAME
app.config['SESSION_REFRESH_EACH_REQUEST'] = config.SESSION_REFRESH_EACH_REQUEST
Session(app)

# ProxyFix für korrekte IP-Adressen hinter Nginx
app.wsgi_app = ProxyFix(
    app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1
)

# Configuration is now loaded from config module

# Initialize error handling system
setup_logging(app)
init_error_handlers(app)
init_monitoring(app)
ErrorHandlingMiddleware(app)

# Logging konfigurieren
logging.basicConfig(level=logging.INFO)

# Initialize scheduler from scheduler module
from scheduler import init_scheduler
scheduler = init_scheduler()

# Import and register blueprints
try:
    from routes.auth_routes import auth_bp
    from routes.admin_routes import admin_bp
    from routes.api_routes import api_bp
    from routes.batch_routes import batch_bp
    from routes.customer_routes import customer_bp
    from routes.export_routes import export_bp
    from routes.license_routes import license_bp
    from routes.resource_routes import resource_bp
    from routes.session_routes import session_bp
    from routes.monitoring_routes import monitoring_bp
    from leads import leads_bp
    print("All blueprints imported successfully!")
except Exception as e:
    print(f"Blueprint import error: {str(e)}")
    import traceback
    traceback.print_exc()

# Register all blueprints
app.register_blueprint(auth_bp)
app.register_blueprint(admin_bp)
app.register_blueprint(api_bp)
app.register_blueprint(batch_bp)
app.register_blueprint(customer_bp)
app.register_blueprint(export_bp)
app.register_blueprint(license_bp)
app.register_blueprint(resource_bp)
app.register_blueprint(session_bp)
app.register_blueprint(monitoring_bp)
app.register_blueprint(leads_bp, url_prefix='/leads')

# Template filters
@app.template_filter('nl2br')
def nl2br_filter(s):
    """Convert newlines to <br> tags"""
    return s.replace('\n', '<br>\n') if s else ''

# Debug routes to test
@app.route('/test-customers-licenses')
def test_route():
    return "Test route works! If you see this, routing is working."

@app.route('/direct-customers-licenses')
def direct_customers_licenses():
    """Direct route without blueprint"""
    try:
        return render_template("customers_licenses.html", customers=[])
    except Exception as e:
        return f"Error: {str(e)}"

@app.route('/debug-routes')
def debug_routes():
    """Show all registered routes"""
    routes = []
    for rule in app.url_map.iter_rules():
        routes.append(f"{rule.endpoint}: {rule.rule}")
    return "<br>".join(sorted(routes))

# Scheduled backup job is now handled by scheduler module


# Error handlers are now managed by the error handling system in core/error_handlers.py


# Context processors
@app.context_processor
def inject_global_vars():
    """Inject global variables into all templates"""
    return {
        'current_year': datetime.now().year,
        'app_version': '2.0.0',
        'is_logged_in': session.get('logged_in', False),
        'username': session.get('username', '')
    }


# Simple test route that should always work
@app.route('/simple-test')
def simple_test():
    return "Simple test works!"

@app.route('/test-db')
def test_db():
    """Test database connection"""
    try:
        import psycopg2
        conn = psycopg2.connect(
            host=os.getenv("POSTGRES_HOST", "postgres"),
            port=os.getenv("POSTGRES_PORT", "5432"),
            dbname=os.getenv("POSTGRES_DB"),
            user=os.getenv("POSTGRES_USER"),
            password=os.getenv("POSTGRES_PASSWORD")
        )
        cur = conn.cursor()
        cur.execute("SELECT COUNT(*) FROM customers")
        count = cur.fetchone()[0]
        cur.close()
        conn.close()
        return f"Database works! Customers count: {count}"
    except Exception as e:
        import traceback
        return f"Database error: {str(e)}<br><pre>{traceback.format_exc()}</pre>"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)