from flask import Flask, render_template, send_from_directory
import os
import logging
from logging.handlers import RotatingFileHandler

app = Flask(__name__, static_folder="static", template_folder="templates")
application = app  # for WSGI hosts

# Setup logging
if not app.debug:
    if not os.path.exists('logs'):
        os.mkdir('logs')
    file_handler = RotatingFileHandler('logs/error.log', maxBytes=10240, backupCount=10)
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
    ))
    app.logger.addHandler(file_handler)
    app.logger.setLevel(logging.INFO)
    app.logger.info('Fractal Explorer Startup')

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico')

@app.route('/healthz')
def healthz():
    return "ok", 200

@app.after_request
def add_cache_headers(resp):
    # Cache static assets aggressively in production
    if "static/" in (resp.headers.get("Content-Location") or ""):
        resp.headers["Cache-Control"] = "public, max-age=31536000, immutable"
    return resp

#if __name__ == "__main__":
    #app.run(debug=True, port=5051)