"""The Flask application object and its configuration."""
import os
import secrets
from datetime import timedelta
from flask import Flask

from nexora.config import BASE_DIR, MAX_CONTENT_LENGTH, UPLOAD_DIR


# NOTE: this object used to be created in app.py, where `__name__` resolved
# to the project root. Now that it lives in the `nexora` package, `__name__`
# would point Flask at nexora/templates and nexora/static. The import name
# and root_path are pinned so templates, static files and url_for("static")
# resolve to exactly the same folders as before.
app = Flask("app", root_path=str(BASE_DIR))


# â”€â”€ Secret key: never use a hardcoded fallback in production â”€â”€
_secret = os.environ.get("SECRET_KEY", "")


if not _secret:
    _secret_file = BASE_DIR / ".secret_key"
    if _secret_file.exists():
        _secret = _secret_file.read_text().strip()
    if not _secret:
        _secret = secrets.token_hex(32)
        try:
            _secret_file.write_text(_secret)
        except OSError:
            pass


app.config["SECRET_KEY"] = _secret


app.config["UPLOAD_FOLDER"] = str(UPLOAD_DIR)


app.config["MAX_CONTENT_LENGTH"] = MAX_CONTENT_LENGTH


# â”€â”€ Session cookie hardening â”€â”€
app.config["SESSION_COOKIE_HTTPONLY"] = True


app.config["SESSION_COOKIE_SAMESITE"] = "Lax"


app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(hours=8)


# Environment-aware Secure flag: the site serves both plain-HTTP (:5000) and an
# HTTPS mirror (:5443) on the LAN, so a static Secure=True would break every
# HTTP login. Instead the cookie stays usable over HTTP and the `Secure`
# attribute is appended per-response whenever the request actually arrived via
# HTTPS (see _secure_cookie_flag below). An environment override is available
# for pure-HTTPS production deployments.
app.config["SESSION_COOKIE_SECURE"] = os.environ.get("FORCE_SECURE_COOKIES", "") == "1"
