"""
Project:    PARTS Website
Author:     Edward Middleton-Smith
            Precision And Research Technology Systems Limited

Technology: App General
Feature:    App

Description:
Initialises the Flask application, sets the configuration based on the environment, and defines two routes (/ and /about) that render templates with the specified titles.
"""

# IMPORTS
# VARIABLE INSTANTIATION
# METHODS

# IMPORTS
# internal
from config import app_config, Config
from controllers.legal.legal import routes_legal
from controllers.tcg.mtg_game import routes_mtg_game
from controllers.user.user import routes_user
from extensions import db, csrf, mail, oauth
from helpers.helper_app import Helper_App
# external
from flask import Flask, render_template, jsonify, request,  render_template_string, send_from_directory, redirect, url_for, session
# from flask_appconfig import AppConfig
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail, Message
from flask_wtf.csrf import CSRFProtect
from werkzeug.exceptions import HTTPException
from authlib.integrations.flask_client import OAuth
import os
import sys
from logging.handlers import RotatingFileHandler
import traceback
import logging

sys.path.insert(0, os.path.dirname(__file__)) # Todo: why?


app = Flask(__name__)
app.secret_key = os.getenv('KEY_SECRET_FLASK')

# AppConfig(app)
app.config.from_object(app_config) # for db init with required keys
app.app_config = app_config
# app.config["config"] = app_config()

# logging
handler = RotatingFileHandler('app.log', maxBytes=10_000_000, backupCount=16)
handler.setLevel(logging.DEBUG)
app.logger.addHandler(handler)

@app.errorhandler(Exception)
def internal_server_error(error):
    if isinstance(error, HTTPException) and error.code == 404:
        return "Not Found", 404

    app.logger.error('Server Error: %s', (error))
    app.logger.error('Request: %s %s %s %s %s',
                     request.remote_addr,
                     request.method,
                     request.scheme,
                     request.full_path,
                     request.headers)
    app.logger.error('Request data: %s', request.get_data())
    app.logger.error('Traceback: %s', traceback.format_exc())
    return "Internal Server Error", 500

"""
@app.before_first_request
def clear_session():
    session.clear()
"""

@app.before_request
def make_session_permanent():
    session.permanent = True

csrf = CSRFProtect()
cors = CORS(app, resources={
    r"/static/*": {
        "origins": [app.config["URL_HOST"]],
        "methods": ["GET"],
        "max_age": 3600
    }
})

csrf.init_app(app)
cors.init_app(app)
db.init_app(app)
mail.init_app(app)
oauth.init_app(app)

with app.app_context():
    # config = app.config["config"]
    db.create_all()
    db.engine.url = app.config['SQLALCHEMY_DATABASE_URI']

    oauth.register(
        "auth0",
        client_id = app.config['ID_AUTH0_CLIENT'],
        client_secret = app.config['ID_AUTH0_CLIENT_SECRET'],
        client_kwargs={
            "scope": "openid profile email",
        },
        server_metadata_url=f'https://{app.config["DOMAIN_AUTH0"]}/.well-known/openid-configuration',
        api_base_url = f'https://{app.config["DOMAIN_AUTH0"]}',
        authorize_url = f'https://{app.config["DOMAIN_AUTH0"]}/authorize',
        access_token_url = f'https://{app.config["DOMAIN_AUTH0"]}/oauth/token',
    )

    print(f"Registered clients: {list(oauth._clients.keys())}")

app.register_blueprint(routes_legal)
app.register_blueprint(routes_user)
app.register_blueprint(routes_mtg_game)


@app.template_filter('console_log')
def console_log(value):
    Helper_App.console_log(value)
    return value

@app.after_request
def add_cache_headers(response):
    if request.path.startswith('/static/'):
        # Cache static assets
        response.headers['Cache-Control'] = 'public, max-age=31536000'
    else:
        # No caching for dynamic content
        response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'
    return response