"""Web app factory for SmartTools UI."""

from __future__ import annotations

import os
import secrets

from flask import Flask, session

from smarttools.registry import app as registry_app

from . import web_bp
from .auth import login, register, logout
from .filters import register_filters
from .seo import sitemap_response, robots_txt
from .sessions import SQLiteSessionInterface, cleanup_expired_sessions


def create_web_app() -> Flask:
    app = registry_app.create_app()

    # Import routes BEFORE registering blueprint
    from . import routes  # noqa: F401

    app.register_blueprint(web_bp)

    # Session configuration
    app.session_interface = SQLiteSessionInterface(cookie_name="smarttools_session")
    app.config["SESSION_COOKIE_NAME"] = "smarttools_session"
    app.config["SESSION_COOKIE_SECURE"] = os.environ.get("SMARTTOOLS_ENV") == "production"
    app.config["SHOW_ADS"] = os.environ.get("SMARTTOOLS_SHOW_ADS", "").lower() == "true"

    # CSRF token generator
    app.config["CSRF_GENERATOR"] = lambda: secrets.token_urlsafe(32)

    # Jinja globals
    def _csrf_token():
        token = session.get("csrf_token")
        if not token:
            token = app.config["CSRF_GENERATOR"]()
            session["csrf_token"] = token
        return token

    app.jinja_env.globals["csrf_token"] = _csrf_token
    register_filters(app)

    cleanup_expired_sessions()

    # SEO routes
    app.add_url_rule("/sitemap.xml", endpoint="web.sitemap", view_func=sitemap_response)
    app.add_url_rule("/robots.txt", endpoint="web.robots", view_func=robots_txt)

    return app


if __name__ == "__main__":
    create_web_app().run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))
