import os
from flask import Flask
from dotenv import load_dotenv
from .utils.extensions import login_manager
from .blueprints.auth.routes import auth_bp
from .blueprints.main.routes import main_bp

from flask import g
from flask_login import current_user
from .utils.tokens import ensure_fresh_appwrite_jwt

# load_dotenv()
from .utils.settings import get_settings

settings = get_settings()

def create_app():
    app = Flask(__name__, template_folder="templates")
    app.config.update(
        SECRET_KEY=settings.flask_secret_key,
        APPWRITE_ENDPOINT=settings.appwrite_endpoint,
        APPWRITE_PROJECT_ID=settings.appwrite_project_id,
        APPWRITE_API_KEY=settings.appwrite_api_key,
        SESSION_COOKIE_SECURE = False,
        SESSION_COOKIE_SAMESITE = "Lax",
        REMEMBER_COOKIE_SAMESITE = "Lax",
        REMEMBER_COOKIE_SECURE = False
    )

    if not app.config["APPWRITE_ENDPOINT"] or not app.config["APPWRITE_PROJECT_ID"]:
        raise RuntimeError("Missing APPWRITE_ENDPOINT or APPWRITE_PROJECT_ID")

    # Extensions
    login_manager.init_app(app)
    login_manager.login_view = "auth.login"

    # Blueprints
    app.register_blueprint(auth_bp)
    app.register_blueprint(main_bp)

    @app.before_request
    def _refresh_jwt_if_needed():
        # Only when logged in; ignore static files etc.
        if getattr(current_user, "is_authenticated", False):
            try:
                # mint if near expiry; otherwise no-op
                g.appwrite_jwt = ensure_fresh_appwrite_jwt()
            except Exception:
                # If the Appwrite session is gone, we don't crash the page;
                # your protected routes will redirect to login as usual.
                pass

    @app.context_processor
    def inject_globals():
        """Add variables available to all Jinja templates."""
        return dict(
            app_name=settings.app_name,
            app_version=settings.app_version
            )

    return app
