"""site-ng — the Flask rebuild of arpartsfinder.com (Perl CGI -> Flask).

App factory. Server-rendered (Jinja2) + htmx for dynamic UX without an
SPA, so pages stay crawlable (SEO = the commission acquisition channel).
See memory: site-migration-perl-to-flask, feature-site-share-builds.
"""

import secrets
from pathlib import Path

from flask import Flask, request


# Sticky dev fallback for the Flask session signing key. Generated on
# first run and cached to .flask-secret-key (gitignored) — survives
# Werkzeug reloads so the in-progress working build doesn't get wiped
# every time a .py file is saved during development. Prod uses an
# explicit config.ini / NGSITE_SECRET_KEY value and never touches this.
_DEV_KEY_FILE = Path(__file__).resolve().parent.parent / ".flask-secret-key"


def _sticky_dev_secret() -> str:
    if _DEV_KEY_FILE.exists():
        return _DEV_KEY_FILE.read_text().strip()
    key = secrets.token_hex(32)
    _DEV_KEY_FILE.write_text(key)
    try:
        _DEV_KEY_FILE.chmod(0o600)
    except OSError:
        pass        # fs may not support chmod (e.g., some shared FS); fine
    return key


def create_app(config_overrides: dict = None) -> Flask:
    app = Flask(__name__)

    from .settings import load_config
    app.config.update(load_config())
    if config_overrides:
        app.config.update(config_overrides)

    # Session signing key. Configured key (config.ini [app] secret_key /
    # NGSITE_SECRET_KEY) wins; otherwise generate a random per-process
    # key so dev sessions still work (invalidated on every restart).
    app.secret_key = app.config.get("SECRET_KEY") or _sticky_dev_secret()

    # Debug / debugger gating. The Werkzeug interactive debugger exposes
    # file paths, usernames, and an authenticated arbitrary-code-execution
    # console — it must NEVER be live in prod. Be explicit (don't rely
    # on `app.run(debug=True)` being passed in only one path) so any
    # future entry point that forgets this still won't leak the debugger.
    is_dev = app.config.get("NGSITE_ENV") == "dev"
    app.debug = is_dev
    app.config["PROPAGATE_EXCEPTIONS"] = is_dev

    # H1 — CSRF mitigation via cookie attributes. Modern browsers default
    # SameSite to Lax when unset, but being explicit closes the gap on
    # older / non-default-Lax browsers AND documents the intent. Lax
    # blocks the session cookie from being sent on cross-site POSTs —
    # which closes nearly all CSRF against /build/<id>/delete, /rename,
    # /claim, /logout etc. without needing per-form tokens.
    app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
    # Secure flag — only relevant in prod (dev runs on plain HTTP). Set
    # in the prod branch below.

    if not is_dev:
        # H2 — refuse to start without PUBLIC_URL_ROOT. Without it,
        # auth.py builds magic-link URLs from request.host_url, which
        # is attacker-controllable via the Host: header → exploitable
        # for token theft. Failing loud at boot is cheaper than a
        # silent vuln. Dev mode is exempt (not reachable to attackers).
        if not app.config.get("PUBLIC_URL_ROOT"):
            raise RuntimeError(
                "PUBLIC_URL_ROOT is required in non-dev mode. Set "
                "[app] public_url_root = https://arpartsfinder.com in "
                "config.ini (or NGSITE_PUBLIC_URL_ROOT env var). "
                "Without it, magic-link emails build URLs from the "
                "request's Host: header, which an attacker can spoof "
                "to redirect the click → token leak → account "
                "takeover. See cutover-checklist.md section B.")
        # H1 (prod half) — cookies only over HTTPS. Pair.com serves
        # arpartsfinder.com over TLS so this is safe; the consequence
        # of setting it on a plain-HTTP request would be the cookie
        # silently failing to set, which is loud-enough during testing.
        app.config["SESSION_COOKIE_SECURE"] = True

    if is_dev:
        # Dev preview of the branded 500 page. In dev, real errors
        # render Werkzeug's interactive debugger (intended — we WANT
        # the stack trace), so the branded 500 from the prod handler
        # below is never exercised on dev. This route lets us eyeball
        # 500.html without faking an error. Registered ONLY in dev so
        # it doesn't expose anywhere on prod. Mike 2026-05-30.
        from flask import render_template as _render_template
        @app.route("/__500-preview")
        def _500_preview():
            return _render_template("500.html"), 500

    if not is_dev:
        # Prod: any unhandled exception renders the branded 500.html
        # (base.html chrome + nav + go-home/browse CTAs). The traceback
        # is still logged to stderr (mod_passenger captures it), so we
        # don't lose diagnostics — we just don't leak them to the
        # visitor. 500.html parallels 404.html on purpose — visitor on
        # the broken page still gets a way back into the catalog.
        from flask import render_template
        @app.errorhandler(Exception)
        def _branded_500(e):
            app.logger.exception("Unhandled exception")
            try:
                return render_template("500.html"), 500
            except Exception:
                # If 500.html itself fails to render (broken base.html,
                # missing template loader, etc.) fall back to a minimal
                # inline page rather than recursing into the handler.
                return (
                    "<!doctype html><meta charset=utf-8>"
                    "<title>Server error</title>"
                    "<h1>Something went wrong on our end.</h1>"
                    "<p>The error has been logged. Please try again shortly.</p>",
                    500)

    # Branded 404 — Werkzeug's default is unstyled and has no nav, which
    # is the worst kind of dead-end on share-URL surfaces (mistyped /b/
    # codes, expired links). Render base.html chrome + a "go home /
    # browse" pair of CTAs. The from_build_url flag tailors the copy
    # when the bad URL was a /b/<code>; saves.public_view sets it via
    # abort(404, description="from_build_url") and we read it here.
    from flask import render_template
    @app.errorhandler(404)
    def _branded_404(e):
        from_build_url = (request.path.startswith("/b/")
                          if request else False)
        return render_template("404.html",
                               from_build_url=from_build_url), 404

    from .db import init_app as init_db
    init_db(app)

    from .labels import type_label, type_description
    app.jinja_env.filters["type_label"] = type_label
    app.jinja_env.filters["type_description"] = type_description

    from .product_url import product_slug
    app.jinja_env.filters["product_slug"] = product_slug

    from .views.main import bp as main_bp
    app.register_blueprint(main_bp)

    from .views.build import bp as build_bp
    app.register_blueprint(build_bp)

    from .views.auth import bp as auth_bp
    app.register_blueprint(auth_bp)

    from .views.saves import bp as saves_bp
    app.register_blueprint(saves_bp)

    from .views.seo import bp as seo_bp
    app.register_blueprint(seo_bp)

    from .views.jump import bp as jump_bp
    app.register_blueprint(jump_bp)

    from .views.product import bp as product_bp
    app.register_blueprint(product_bp)

    from . import auth as _auth
    _auth.init_app(app)

    # Surface the logged-in user (if any) to every template so the
    # header can render account links + the build chip can hint at
    # "save this build" affordances. Cheap: pulls from session +
    # caches on flask.g.
    @app.context_processor
    def _inject_user():
        return {"current_user": _auth.current_user()}

    # Recent saved builds — used by the chip dropdown's "Saved"
    # mini-section. Caps at 5; if the user has more, the dropdown
    # shows a "See all (N) →" link to /my-builds. Only fires for
    # logged-in users; anonymous users see a "Sign in to save"
    # affordance instead. One small indexed lookup per page; not
    # worth caching at this scale.
    @app.context_processor
    def _inject_recent_saved():
        from . import saves as _saves
        user = _auth.current_user()
        if not user:
            return {"recent_saved": [], "saved_count": 0}
        return {
            "recent_saved": _saves.list_recent_saved_for_user(user["id"], 5),
            "saved_count": _saves.count_saved_for_user(user["id"]),
        }

    # Inject the current working-build summary into every template so the
    # header chip can render on every page without each view having to
    # pass it. Cheap: empty session = no DB hit; non-empty = one small
    # `id IN (...)` lookup.
    @app.context_processor
    def _inject_build():
        from .build import build_summary
        return {"build": build_summary()}

    # Static-file URL helper with mtime-based cache busting. Templates
    # use `{{ static_v('js/browse.js') }}` instead of the raw
    # url_for('static', ...) so the URL gets a `?v=<mtime>` suffix
    # that changes whenever the file on disk changes. The visitor's
    # browser sees a "new" URL on each deploy and fetches fresh; no
    # hard refresh required, no manual version bumps. Falls back to
    # an unversioned URL if the file is missing (404 will surface in
    # the browser, not crash the page render).
    @app.context_processor
    def _inject_static_v():
        from pathlib import Path as _Path
        from flask import url_for as _url_for
        _static_dir = _Path(app.static_folder)
        def static_v(filename):
            url = _url_for("static", filename=filename)
            try:
                mtime = int((_static_dir / filename).stat().st_mtime)
                sep = "&" if "?" in url else "?"
                return f"{url}{sep}v={mtime}"
            except (OSError, FileNotFoundError):
                return url
        return {"static_v": static_v}

    # Inject the changelog's newest-date + badge-active flag into
    # every template so the home page can render a "What's new" pill
    # without each view needing to pull it explicitly. Cheap: one
    # mtime-cached YAML read for the first request per process,
    # in-memory on every request after.
    @app.context_processor
    def _inject_changelog_badge():
        from .changelog import newest_date, badge_active, badge_token
        nd = newest_date()
        return {
            "changelog_newest": nd,
            "changelog_newest_iso": nd.isoformat() if nd else "",
            # The 'seen' token: a content fingerprint of the recent entries, so
            # same-day additions / in-place edits re-fire the pill (not a bare
            # date). index.html (data-newest) + changelog.html both use it.
            "changelog_token": badge_token(),
            "changelog_badge": badge_active(),
        }

    # Pagination URL helper: rebuild the CURRENT query string with `page` set to
    # a target, so page navigation preserves EVERY active filter rather than a
    # hand-maintained subset that silently drops some.
    @app.context_processor
    def _inject_page_qs():
        from urllib.parse import urlencode
        from flask import request

        def page_qs(target):
            args = request.args.to_dict(flat=False)
            args["page"] = [str(target)]
            return urlencode(args, doseq=True)
        return {"page_qs": page_qs}

    # Current year for the footer copyright — kept dynamic so it never
    # goes stale.
    @app.context_processor
    def _inject_year():
        from datetime import date as _date
        return {"current_year": _date.today().year}

    # Expose PUBLIC_URL_ROOT to every template so canonical / Open
    # Graph / JSON-LD URLs in base.html can be absolute without
    # relying on request.host (which could be wrong behind a proxy or
    # under a `Host:` header attack). See seo.md and the H2 enforcement
    # comment above. In dev where PUBLIC_URL_ROOT is empty, fall back
    # to request.host_url at render time (fine — dev isn't crawled).
    @app.context_processor
    def _inject_public_url_root():
        from flask import request as _req
        root = (app.config.get("PUBLIC_URL_ROOT") or "").rstrip("/")
        if not root:
            try:
                root = _req.host_url.rstrip("/")
            except RuntimeError:
                # outside a request context (e.g. shell); harmless empty
                root = ""
        return {"public_url_root": root}

    # The browse default sort lives in ONE place (queries.DEFAULT_SORT).
    # Inject it so templates can ask "is the current sort the default?"
    # (the chip strip + paginator omit the sort param when it's the
    # default) without hardcoding the value — it used to be scattered as
    # the literal 'newest'. A context_processor reaches OOB fragment
    # renders too, so /browse/parts swaps stay consistent.
    @app.context_processor
    def _inject_default_sort():
        from .queries import DEFAULT_SORT
        return {"default_sort": DEFAULT_SORT}

    # Inject the navigable type sections (Lower / Upper / Other) into
    # every template — used by the shared category-report modal in
    # base.html so its <select> shows the same categories as the
    # sidebar (NOT the Recent / saved-query slugs).
    @app.context_processor
    def _inject_nav_types():
        from .labels import TYPE_LABELS, TYPE_SECTIONS
        sections = []
        for sec_name, codes in TYPE_SECTIONS:
            sections.append({
                "section": sec_name,
                "types": [{"code": c, "label": TYPE_LABELS.get(c, c)}
                          for c in codes],
            })
        return {"nav_sections": sections}

    # Sister-site network for cross-promotion (Tier 0). Exposes the OTHER
    # sites in the family to the footer/header/more-sheet (registry-derived;
    # see network.py). Injected as a CALLABLE so each surface can tag its
    # own UTM medium: network_sisters('footer'|'nav'|'more'). Links carry
    # UTM so referral views are attributable per placement.
    @app.context_processor
    def _inject_sister_sites():
        from .network import sisters
        return {"network_sisters": sisters}

    return app
