from flask import Flask, jsonify, request, url_for, redirect, session, render_template, g, send_file
import pymysql
import os
pymysql.install_as_MySQLdb()
from flask import * 
from blueprints.accounts import accounts_bp  # Import accounts blueprint
from blueprints.devices import devices_bp 
from blueprints.logout import logout_bp 
from blueprints.report_excel import report_excel_bp
from blueprints.report import report_bp
from blueprints.utilDashboard import utilDashboard_bp
from blueprints.login import login_bp
from blueprints.home import home_bp
from blueprints.mqtt_device import mqtt_device_bp, start_mqtt_thread
from blueprints.settings import settings_bp
from blueprints.auth import auth_bp
from blueprints.dashboard import dashboard_bp
from blueprints.power_monitor import power_monitor_bp
from blueprints.summary_power import summary_power_bp
from config.db import get_db_connection  # Import centralized DB connection
from config.mail import init_mail
from blueprints.power_monitor import power_monitor_bp, start_power_thread




app = Flask(__name__)

init_mail(app)

# Secret key for session security (supports environment configuration)
app.secret_key = os.environ.get('SECRET_KEY', 'your_secret_key_change_me_in_production_123!')

# Session Cookie Security Configurations
app.config.update(
    SESSION_COOKIE_SECURE=True,       # Ensures session cookies are only sent over HTTPS (highly relevant for monitor.silvestersila.my.id)
    SESSION_COOKIE_HTTPONLY=True,     # Prevents client-side scripts from reading session cookies (mitigates XSS cookie theft)
    SESSION_COOKIE_SAMESITE='Lax',    # Mitigates Cross-Site Request Forgery (CSRF)
)

# Register blueprints
app.register_blueprint(accounts_bp)
app.register_blueprint(devices_bp)
app.register_blueprint(logout_bp)
app.register_blueprint(report_excel_bp)
app.register_blueprint(report_bp)
app.register_blueprint(utilDashboard_bp)
app.register_blueprint(home_bp)
app.register_blueprint(login_bp)
app.register_blueprint(mqtt_device_bp)
app.register_blueprint(settings_bp)
app.register_blueprint(auth_bp)
app.register_blueprint(dashboard_bp)
app.register_blueprint(power_monitor_bp)
app.register_blueprint(summary_power_bp)

@app.before_request
def prevent_cache():
    if 'loggedin' not in session and request.endpoint not in ['login.login', 'static']:
        return redirect(url_for('login.login'))
    
    response = make_response()
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "0"

@app.after_request
def add_cache_control_and_security_headers(response):
    # Cache Control (prevent session backward tracking)
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate, max-age=0"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "0"
    
    # Common Security Headers
    response.headers["X-Frame-Options"] = "SAMEORIGIN"          # Prevents Clickjacking
    response.headers["X-Content-Type-Options"] = "nosniff"      # Prevents MIME Sniffing
    response.headers["X-XSS-Protection"] = "1; mode=block"      # Mitigates Cross-Site Scripting (XSS)
    return response

import os

# Only start MQTT threads if configured to run inside the web process (defaults to True for local development)
if os.environ.get("RUN_MQTT_IN_WEB", "true").lower() == "true":
    start_mqtt_thread()
    start_power_thread()

if __name__ == '__main__':
    app.run(debug=True)