"""Admin section: /admin"""
import csv
import io
import os
import tempfile
import zipfile
from datetime import datetime, timedelta, date

from utils import today_local
from functools import wraps

import pyotp
import segno
from flask import (Blueprint, render_template, request, redirect, url_for, flash, abort,
                   current_app, session, jsonify, Response, send_file, after_this_request)
from flask_login import login_user, logout_user, login_required, current_user

import config
import mailer
import media
from models import (db, User, ContentBlock, ContentVersion, BoardMember, Event, Album, Photo,
                    Slide, Message, Activity, get_setting, set_setting)
from utils import clean_html, slugify, client_ip

bp = Blueprint("admin", __name__, template_folder="templates")

MAX_ATTEMPTS = 5
LOCK_MINUTES = 15
_ip_failures = {}  # ip -> [timestamps]   (per worker; DB lockout is the main guard)


# ---------------------------------------------------------------- helpers
def log(action):
    db.session.add(Activity(username=current_user.username if current_user.is_authenticated else "-",
                            action=action[:255], ip=client_ip()))


def super_required(fn):
    @wraps(fn)
    def wrapper(*a, **kw):
        if not current_user.is_authenticated or not current_user.is_super:
            flash("Only Super Admins can open that page.", "error")
            return redirect(url_for("admin.dashboard"))
        return fn(*a, **kw)
    return wrapper


def uploads():
    return current_app.config["UPLOADS_DIR"]


def form_bool(name):
    return request.form.get(name) in ("1", "on", "true", "yes")


def parse_date(s):
    try:
        return datetime.strptime(s, "%Y-%m-%d").date()
    except (TypeError, ValueError):
        return None


@bp.before_request
def guard():
    open_eps = {"admin.login", "admin.two_factor"}
    if request.endpoint in open_eps:
        return None
    if not current_user.is_authenticated:
        nxt = request.full_path.rstrip("?") if request.method == "GET" else None
        return redirect(url_for("admin.login", next=nxt))
    session.permanent = True
    return None


@bp.context_processor
def admin_ctx():
    unread = Message.query.filter_by(is_read=False).count() if current_user.is_authenticated else 0
    return dict(unread_count=unread, media_url=lambda r: url_for("media", filename=r) if r else "")


# ---------------------------------------------------------------- auth
@bp.route("/login", methods=["GET", "POST"])
def login():
    if current_user.is_authenticated:
        return redirect(url_for("admin.dashboard"))
    if request.method == "POST":
        ip = client_ip()
        now = datetime.utcnow()
        recent = [t for t in _ip_failures.get(ip, []) if t > now - timedelta(minutes=LOCK_MINUTES)]
        _ip_failures[ip] = recent
        username = (request.form.get("username") or "").strip()
        password = request.form.get("password") or ""
        user = User.query.filter_by(username=username).first()
        if len(recent) >= 20:
            flash("Too many failed attempts from your connection. Try again in 15 minutes.", "error")
        elif user and user.locked_until and user.locked_until > now:
            mins = int((user.locked_until - now).total_seconds() // 60) + 1
            flash(f"This account is locked after too many failed attempts. Try again in {mins} minute(s).", "error")
        elif user and user.check_password(password):
            user.failed_attempts, user.locked_until = 0, None
            db.session.commit()
            if user.totp_enabled:
                session["2fa_uid"] = user.id
                session["2fa_next"] = request.args.get("next") or ""
                return redirect(url_for("admin.two_factor"))
            return _finish_login(user)
        else:
            _ip_failures[ip].append(now)
            if user:
                user.failed_attempts = (user.failed_attempts or 0) + 1
                if user.failed_attempts >= MAX_ATTEMPTS:
                    user.locked_until = now + timedelta(minutes=LOCK_MINUTES)
                    user.failed_attempts = 0
                db.session.add(Activity(username=username[:64], action="Failed login", ip=ip))
                db.session.commit()
            flash("Incorrect username or password.", "error")
    return render_template("admin/login.html")


def _finish_login(user):
    session.clear()
    login_user(user)
    session.permanent = True
    user.last_login = datetime.utcnow()
    log("Signed in")
    db.session.commit()
    nxt = request.args.get("next") or session.pop("2fa_next", "")
    if nxt and nxt.startswith("/admin") and not nxt.startswith("//"):
        return redirect(nxt)
    return redirect(url_for("admin.dashboard"))


@bp.route("/2fa", methods=["GET", "POST"])
def two_factor():
    uid = session.get("2fa_uid")
    user = db.session.get(User, uid) if uid else None
    if not user:
        return redirect(url_for("admin.login"))
    if request.method == "POST":
        code = (request.form.get("code") or "").replace(" ", "")
        if pyotp.TOTP(user.totp_secret).verify(code, valid_window=1):
            nxt = session.get("2fa_next", "")
            resp = _finish_login(user)
            if nxt.startswith("/admin"):
                return redirect(nxt)
            return resp
        user.failed_attempts = (user.failed_attempts or 0) + 1
        if user.failed_attempts >= MAX_ATTEMPTS:
            user.locked_until = datetime.utcnow() + timedelta(minutes=LOCK_MINUTES)
            user.failed_attempts = 0
            session.pop("2fa_uid", None)
            db.session.commit()
            flash("Too many wrong codes. The account is locked for 15 minutes.", "error")
            return redirect(url_for("admin.login"))
        db.session.commit()
        flash("That code is not valid. Check your authenticator app and try again.", "error")
    return render_template("admin/two_factor.html")


@bp.route("/logout", methods=["POST"])
def logout():
    log("Signed out")
    db.session.commit()
    logout_user()
    session.clear()
    flash("You are signed out.", "success")
    return redirect(url_for("admin.login"))


# ---------------------------------------------------------------- dashboard
@bp.route("/")
def dashboard():
    stats = dict(
        photos=Photo.query.filter_by(kind="image").count(),
        videos=Photo.query.filter_by(kind="video").count(),
        albums=Album.query.count(),
        slides=Slide.query.count(),
        upcoming=Event.query.filter(Event.event_date >= today_local()).count(),
        board=BoardMember.query.count(),
        messages=Message.query.count(),
    )
    next_events = Event.query.filter(Event.event_date >= today_local()).order_by(Event.event_date).limit(3).all()
    recent_msgs = Message.query.order_by(Message.created_at.desc()).limit(5).all()
    activity = Activity.query.order_by(Activity.created_at.desc()).limit(8).all()
    smtp_ok = bool(config.smtp_settings().get("password"))
    return render_template("admin/dashboard.html", stats=stats, next_events=next_events,
                           recent_msgs=recent_msgs, activity=activity, smtp_ok=smtp_ok)


# ---------------------------------------------------------------- page content
@bp.route("/content")
def content_list():
    blocks = ContentBlock.query.order_by(ContentBlock.sort).all()
    groups = {}
    for b in blocks:
        groups.setdefault(b.group, []).append(b)
    return render_template("admin/content_list.html", groups=groups)


@bp.route("/content/<key>", methods=["GET", "POST"])
def content_edit(key):
    b = ContentBlock.query.filter_by(key=key).first_or_404()
    if request.method == "POST":
        en = request.form.get("en", "")
        fr = request.form.get("fr", "")
        if b.kind == "html":
            en, fr = clean_html(en), clean_html(fr)
        else:
            en, fr = en.strip(), fr.strip()
        if en != b.en or fr != b.fr:
            db.session.add(ContentVersion(block_key=b.key, en=b.en, fr=b.fr, saved_by=b.updated_by or ""))
            b.en, b.fr = en, fr
            b.updated_by = current_user.username
            log(f"Edited text: {b.group} › {b.label}")
            db.session.commit()
            flash("Saved. The change is live on the website.", "success")
        else:
            flash("No changes to save.", "info")
        return redirect(url_for("admin.content_edit", key=key))
    versions = (ContentVersion.query.filter_by(block_key=key)
                .order_by(ContentVersion.saved_at.desc()).limit(20).all())
    return render_template("admin/content_edit.html", b=b, versions=versions)


@bp.route("/content/<key>/revert/<int:vid>", methods=["POST"])
def content_revert(key, vid):
    b = ContentBlock.query.filter_by(key=key).first_or_404()
    v = ContentVersion.query.get_or_404(vid)
    if v.block_key != key:
        abort(404)
    db.session.add(ContentVersion(block_key=b.key, en=b.en, fr=b.fr, saved_by=b.updated_by or ""))
    b.en, b.fr, b.updated_by = v.en, v.fr, current_user.username
    log(f"Restored earlier version: {b.group} › {b.label}")
    db.session.commit()
    flash("Earlier version restored.", "success")
    return redirect(url_for("admin.content_edit", key=key))


@bp.route("/content/president-photo", methods=["POST"])
def president_photo():
    f = request.files.get("photo")
    if not f or media.kind_of(f.filename) != "image":
        flash("Please choose an image file (JPG or PNG).", "error")
    else:
        try:
            r = media.process_image(f.stream, uploads(), "site", filename=f.filename, web_max=1000, thumb_max=500)
            set_setting("president_photo", r["web"])
            log("Replaced the president's photo")
            db.session.commit()
            flash("President photo updated.", "success")
        except Exception as exc:  # noqa: BLE001
            flash(f"Could not read that image: {exc}", "error")
    return redirect(url_for("admin.content_list"))


# ---------------------------------------------------------------- board
@bp.route("/board")
def board_list():
    which = "past" if request.args.get("board") == "past" else "current"
    members = (BoardMember.query.filter_by(board=which)
               .order_by(BoardMember.sort, BoardMember.id).all())
    counts = {w: BoardMember.query.filter_by(board=w).count() for w in ("current", "past")}
    return render_template("admin/board_list.html", members=members, which=which, counts=counts)


@bp.route("/board/new", methods=["GET", "POST"])
@bp.route("/board/<int:mid>", methods=["GET", "POST"])
def board_edit(mid=None):
    m = db.session.get(BoardMember, mid) if mid else BoardMember(
        board="past" if request.args.get("board") == "past" else "current", visible=True)
    if mid and not m:
        abort(404)
    if request.method == "POST":
        old_board = m.board
        m.board = "past" if request.form.get("board") == "past" else "current"
        m.name = request.form.get("name", "").strip()
        m.title_en = request.form.get("title_en", "").strip()
        m.title_fr = request.form.get("title_fr", "").strip()
        m.visible = form_bool("visible")
        if not m.name or not m.title_en:
            flash("Name and English title are required.", "error")
            return render_template("admin/board_edit.html", m=m)
        f = request.files.get("photo")
        if f and f.filename:
            if media.kind_of(f.filename) != "image":
                flash("The photo must be an image (JPG or PNG).", "error")
                return render_template("admin/board_edit.html", m=m)
            try:
                r = media.process_image(f.stream, uploads(), "board", filename=f.filename, web_max=1000, thumb_max=600)
                m.photo = r["web"]
            except Exception as exc:  # noqa: BLE001
                flash(f"Could not read that image: {exc}", "error")
                return render_template("admin/board_edit.html", m=m)
        if not mid or old_board != m.board:
            mx = db.session.query(db.func.max(BoardMember.sort)).filter(BoardMember.board == m.board).scalar()
            m.sort = (mx if mx is not None else -1) + 1
        if not mid:
            db.session.add(m)
        log(f"{'Updated' if mid else 'Added'} {m.board} board member: {m.name}")
        db.session.commit()
        flash("Board member saved.", "success")
        return redirect(url_for("admin.board_list", board=m.board))
    return render_template("admin/board_edit.html", m=m)


@bp.route("/board/<int:mid>/delete", methods=["POST"])
def board_delete(mid):
    m = db.session.get(BoardMember, mid) or abort(404)
    which = m.board or "current"
    log(f"Removed {which} board member: {m.name}")
    db.session.delete(m)
    db.session.commit()
    flash("Board member removed.", "success")
    return redirect(url_for("admin.board_list", board=which))


# ---------------------------------------------------------------- events
@bp.route("/events")
def events_list():
    up = Event.query.filter(Event.event_date >= today_local()).order_by(Event.event_date).all()
    past = Event.query.filter(Event.event_date < today_local()).order_by(Event.event_date.desc()).all()
    return render_template("admin/events_list.html", upcoming=up, past=past)


@bp.route("/events/new", methods=["GET", "POST"])
@bp.route("/events/<int:eid>", methods=["GET", "POST"])
def event_edit(eid=None):
    e = db.session.get(Event, eid) if eid else Event(published=True)
    if eid and not e:
        abort(404)
    if request.method == "POST":
        for fld in ("title_en", "title_fr", "time_text", "location_en", "location_fr", "link_url"):
            setattr(e, fld, (request.form.get(fld) or "").strip())
        e.description_en = clean_html(request.form.get("description_en", ""))
        e.description_fr = clean_html(request.form.get("description_fr", ""))
        e.published = form_bool("published")
        d = parse_date(request.form.get("event_date"))
        if not e.title_en or not d:
            flash("An English title and a date are required.", "error")
            return render_template("admin/event_edit.html", e=e)
        e.event_date = d
        if e.link_url and not e.link_url.startswith(("http://", "https://")):
            e.link_url = "https://" + e.link_url
        if form_bool("remove_image"):
            e.image = ""
        f = request.files.get("image")
        if f and f.filename:
            try:
                e.image = media.process_image(f.stream, uploads(), "events", filename=f.filename, web_max=1400)["web"]
            except Exception as exc:  # noqa: BLE001
                flash(f"Could not read that image: {exc}", "error")
                return render_template("admin/event_edit.html", e=e)
        if not eid:
            db.session.add(e)
        log(f"{'Updated' if eid else 'Created'} event: {e.title_en}")
        db.session.commit()
        flash("Event saved.", "success")
        return redirect(url_for("admin.events_list"))
    return render_template("admin/event_edit.html", e=e)


@bp.route("/events/<int:eid>/delete", methods=["POST"])
def event_delete(eid):
    e = db.session.get(Event, eid) or abort(404)
    log(f"Deleted event: {e.title_en}")
    db.session.delete(e)
    db.session.commit()
    flash("Event deleted.", "success")
    return redirect(url_for("admin.events_list"))


# ---------------------------------------------------------------- galleries
@bp.route("/albums")
def albums_list():
    albums = Album.query.order_by(Album.sort, Album.id).all()
    return render_template("admin/albums_list.html", albums=albums)


@bp.route("/albums/new", methods=["GET", "POST"])
@bp.route("/albums/<int:aid>/settings", methods=["GET", "POST"])
def album_settings(aid=None):
    a = db.session.get(Album, aid) if aid else Album(visible=True)
    if aid and not a:
        abort(404)
    if request.method == "POST":
        a.title_en = request.form.get("title_en", "").strip()
        a.title_fr = request.form.get("title_fr", "").strip()
        a.description_en = request.form.get("description_en", "").strip()
        a.description_fr = request.form.get("description_fr", "").strip()
        a.visible = form_bool("visible")
        if not a.title_en:
            flash("The album needs an English name.", "error")
            return render_template("admin/album_settings.html", a=a)
        if not aid:
            base = slugify(a.title_en)
            slug, i = base, 2
            while Album.query.filter_by(slug=slug).first():
                slug, i = f"{base}-{i}", i + 1
            a.slug = slug
            a.sort = (db.session.query(db.func.max(Album.sort)).scalar() or 0) + 1
            db.session.add(a)
        log(f"{'Updated' if aid else 'Created'} album: {a.title_en}")
        db.session.commit()
        flash("Album saved." + ("" if aid else " Now add some photos."), "success")
        return redirect(url_for("admin.album_photos", aid=a.id))
    return render_template("admin/album_settings.html", a=a)


@bp.route("/albums/<int:aid>/delete", methods=["POST"])
def album_delete(aid):
    a = db.session.get(Album, aid) or abort(404)
    for p in a.photos:
        media.delete_files(uploads(), p.original, p.web, p.thumb)
    log(f"Deleted album: {a.title_en} ({a.photos.count()} files)")
    db.session.delete(a)
    db.session.commit()
    flash("Album and its photos deleted.", "success")
    return redirect(url_for("admin.albums_list"))


@bp.route("/albums/<int:aid>")
def album_photos(aid):
    a = db.session.get(Album, aid) or abort(404)
    photos = a.photos.order_by(Photo.sort, Photo.id).all()
    others = Album.query.filter(Album.id != aid).order_by(Album.sort).all()
    return render_template("admin/album_photos.html", a=a, photos=photos, others=others)


@bp.route("/albums/<int:aid>/upload", methods=["POST"])
def album_upload(aid):
    a = db.session.get(Album, aid) or abort(404)
    allow_dups = form_bool("allow_duplicates")
    existing = [p.phash for p in a.photos if p.phash]
    nxt = (db.session.query(db.func.max(Photo.sort)).filter(Photo.album_id == aid).scalar() or 0) + 1
    added, dups, errors = 0, [], []
    for f in request.files.getlist("files"):
        if not f or not f.filename:
            continue
        kind = media.kind_of(f.filename)
        try:
            if kind == "image":
                img = media.open_image(f.stream)
                ph = media.dhash(img)
                if not allow_dups and media.is_duplicate(ph, existing):
                    dups.append(f.filename)
                    continue
                r = media.process_image(f.stream, uploads(), f"gallery/{a.slug}", filename=f.filename, img=img)
                existing.append(ph)
            elif kind == "video":
                r = media.process_video(f.stream, uploads(), f"gallery/{a.slug}", filename=f.filename)
            else:
                errors.append(f"{f.filename}: not a supported photo or video type")
                continue
        except Exception:  # noqa: BLE001
            errors.append(f"{f.filename}: could not be read (damaged or not a real image/video)")
            continue
        db.session.add(Photo(album_id=a.id, sort=nxt, **r))
        nxt += 1
        added += 1
    if added:
        log(f"Uploaded {added} file(s) to album: {a.title_en}")
    db.session.commit()
    return jsonify(added=added, duplicates=dups, errors=errors)


@bp.route("/albums/<int:aid>/bulk", methods=["POST"])
def album_bulk(aid):
    a = db.session.get(Album, aid) or abort(404)
    ids = [int(i) for i in request.form.getlist("ids") if i.isdigit()]
    action = request.form.get("action")
    photos = Photo.query.filter(Photo.album_id == aid, Photo.id.in_(ids)).all() if ids else []
    if not photos:
        flash("Select at least one photo first.", "error")
        return redirect(url_for("admin.album_photos", aid=aid))
    if action == "hide":
        for p in photos:
            p.hidden = True
    elif action == "show":
        for p in photos:
            p.hidden = False
    elif action == "delete":
        for p in photos:
            media.delete_files(uploads(), p.original, p.web, p.thumb)
            if a.cover_id == p.id:
                a.cover_id = None
            db.session.delete(p)
    elif action == "move":
        target = db.session.get(Album, int(request.form.get("target") or 0))
        if not target:
            flash("Choose the album to move the photos to.", "error")
            return redirect(url_for("admin.album_photos", aid=aid))
        for p in photos:
            p.album_id = target.id
            if a.cover_id == p.id:
                a.cover_id = None
    elif action == "cover" and photos:
        a.cover_id = photos[0].id
    elif action == "slideshow":
        nxt = (db.session.query(db.func.max(Slide.sort)).scalar() or 0) + 1
        for p in photos:
            if p.kind != "image":
                continue
            r = _slide_from_photo(p)
            db.session.add(Slide(image=r["web"], thumb=r["thumb"], sort=nxt))
            nxt += 1
    else:
        abort(400)
    labels = dict(hide="Hid", show="Showed", delete="Deleted", move="Moved", cover="Set cover for",
                  slideshow="Added to slideshow")
    log(f"{labels.get(action, action)} {len(photos)} photo(s) in album: {a.title_en}")
    db.session.commit()
    flash(f"Done: {labels.get(action, action).lower()} {len(photos)} item(s).", "success")
    return redirect(url_for("admin.album_photos", aid=aid))


@bp.route("/photos/<int:pid>/caption", methods=["POST"])
def photo_caption(pid):
    p = db.session.get(Photo, pid) or abort(404)
    p.caption_en = (request.form.get("caption_en") or "").strip()[:255]
    p.caption_fr = (request.form.get("caption_fr") or "").strip()[:255]
    db.session.commit()
    return jsonify(ok=True)


@bp.route("/reorder/<kind>", methods=["POST"])
def reorder(kind):
    model = {"photos": Photo, "slides": Slide, "board": BoardMember, "albums": Album}.get(kind)
    if not model:
        abort(404)
    ids = (request.get_json(silent=True) or {}).get("ids", [])
    for i, oid in enumerate(ids):
        obj = db.session.get(model, int(oid))
        if obj:
            obj.sort = i
    db.session.commit()
    return jsonify(ok=True)


# ---------------------------------------------------------------- slideshow
def _slide_from_photo(p):
    src = os.path.join(uploads(), p.original or p.web)
    if not os.path.isfile(src):
        src = os.path.join(uploads(), p.web)
    return media.process_image(src, uploads(), "slides", keep_original=False, web_max=2200)


@bp.route("/slides", methods=["GET", "POST"])
def slides():
    if request.method == "POST":
        nxt = (db.session.query(db.func.max(Slide.sort)).scalar() or 0) + 1
        added = 0
        for f in request.files.getlist("files"):
            if not f or media.kind_of(f.filename) != "image":
                continue
            try:
                r = media.process_image(f.stream, uploads(), "slides", filename=f.filename, web_max=2200)
            except Exception as exc:  # noqa: BLE001
                flash(f"{f.filename}: could not be read ({exc})", "error")
                continue
            db.session.add(Slide(image=r["web"], thumb=r["thumb"], sort=nxt))
            nxt += 1
            added += 1
        if added:
            log(f"Added {added} slideshow image(s)")
            flash(f"{added} image(s) added to the slideshow.", "success")
        db.session.commit()
        return redirect(url_for("admin.slides"))
    items = Slide.query.order_by(Slide.sort, Slide.id).all()
    albums = Album.query.order_by(Album.sort).all()
    return render_template("admin/slides.html", slides=items, albums=albums)


@bp.route("/slides/<int:sid>", methods=["POST"])
def slide_update(sid):
    s = db.session.get(Slide, sid) or abort(404)
    action = request.form.get("action")
    if action == "delete":
        media.delete_files(uploads(), s.image, s.thumb)
        db.session.delete(s)
        log("Removed a slideshow image")
        flash("Slide removed.", "success")
    elif action == "replace":
        f = request.files.get("file")
        if f and media.kind_of(f.filename) == "image":
            try:
                r = media.process_image(f.stream, uploads(), "slides", filename=f.filename, web_max=2200)
                media.delete_files(uploads(), s.image, s.thumb)
                s.image, s.thumb = r["web"], r["thumb"]
                log("Replaced a slideshow image")
                flash("Slide image replaced.", "success")
            except Exception as exc:  # noqa: BLE001
                flash(f"Could not read that image: {exc}", "error")
    else:
        s.caption_en = (request.form.get("caption_en") or "").strip()[:255]
        s.caption_fr = (request.form.get("caption_fr") or "").strip()[:255]
        s.visible = form_bool("visible")
        log("Updated a slideshow image")
        flash("Slide saved.", "success")
    db.session.commit()
    return redirect(url_for("admin.slides"))


@bp.route("/slides/from-gallery", methods=["POST"])
def slide_from_gallery():
    p = db.session.get(Photo, int(request.form.get("photo_id") or 0)) or abort(404)
    r = _slide_from_photo(p)
    nxt = (db.session.query(db.func.max(Slide.sort)).scalar() or 0) + 1
    db.session.add(Slide(image=r["web"], thumb=r["thumb"], sort=nxt))
    log("Added a gallery photo to the slideshow")
    db.session.commit()
    flash("Photo added to the slideshow.", "success")
    return redirect(url_for("admin.slides"))


@bp.route("/albums/<int:aid>/picker")
def album_picker(aid):
    a = db.session.get(Album, aid) or abort(404)
    return jsonify([{"id": p.id, "thumb": url_for("media", filename=p.thumb)}
                    for p in a.photos.filter_by(kind="image").order_by(Photo.sort, Photo.id)])


# ---------------------------------------------------------------- messages
@bp.route("/messages")
def messages():
    msgs = Message.query.order_by(Message.created_at.desc()).all()
    return render_template("admin/messages.html", msgs=msgs)


@bp.route("/messages/<int:mid>", methods=["GET", "POST"])
def message_view(mid):
    m = db.session.get(Message, mid) or abort(404)
    if request.method == "POST":
        if request.form.get("action") == "delete":
            db.session.delete(m)
            log(f"Deleted message from {m.name}")
            db.session.commit()
            flash("Message deleted.", "success")
            return redirect(url_for("admin.messages"))
        m.is_read = request.form.get("action") != "unread"
        db.session.commit()
        return redirect(url_for("admin.messages"))
    if not m.is_read:
        m.is_read = True
        db.session.commit()
    return render_template("admin/message_view.html", m=m)


@bp.route("/messages/export.csv")
def messages_export():
    buf = io.StringIO()
    w = csv.writer(buf)
    w.writerow(["Date (UTC)", "Name", "Email", "Phone", "City", "Subject", "Message", "Language", "Email status"])
    for m in Message.query.order_by(Message.created_at.desc()):
        w.writerow([m.created_at.strftime("%Y-%m-%d %H:%M"), m.name, m.email, m.phone, m.city,
                    m.subject, m.body, m.lang, m.email_status])
    log("Exported messages to CSV")
    db.session.commit()
    return Response("﻿" + buf.getvalue(), mimetype="text/csv",
                    headers={"Content-Disposition": f"attachment; filename=bct-messages-{date.today()}.csv"})


# ---------------------------------------------------------------- settings
SITE_KEYS = ["contact_email", "identification_form_url", "zelle_email", "zelle_name", "ein",
             "slideshow_interval", "random_banner"]


@bp.route("/settings", methods=["GET", "POST"])
@super_required
def settings():
    cp = config.load()
    if request.method == "POST":
        section = request.form.get("section")
        if section == "site":
            for k in SITE_KEYS:
                v = (request.form.get(k) or "").strip()
                if k == "random_banner":
                    v = "1" if form_bool(k) else "0"
                if k == "slideshow_interval":
                    v = str(max(2, min(30, int(v)))) if v.isdigit() else "5"
                set_setting(k, v)
            if form_bool("remove_qr"):
                set_setting("zelle_qr", "")
            f = request.files.get("zelle_qr")
            if f and f.filename:
                try:
                    r = media.process_image(f.stream, uploads(), "site", filename=f.filename, web_max=800)
                    set_setting("zelle_qr", r["web"])
                except Exception as exc:  # noqa: BLE001
                    flash(f"Could not read the QR image: {exc}", "error")
            log("Updated site settings")
            db.session.commit()
            flash("Site settings saved.", "success")
        elif section == "smtp":
            vals = {k: (request.form.get(k) or "").strip() for k in
                    ("host", "port", "username", "security", "from_email", "from_name", "recipient")}
            if not vals["port"].isdigit():
                flash("SMTP port must be a number (usually 587 or 465).", "error")
                return redirect(url_for("admin.settings"))
            if vals["security"] not in ("starttls", "ssl", "none"):
                vals["security"] = "starttls"
            pw = request.form.get("password") or ""
            if pw:
                vals["password"] = pw.replace(" ", "") if "gmail" in vals["host"] else pw
            config.update_smtp(vals)
            log("Updated SMTP settings")
            db.session.commit()
            flash("Email (SMTP) settings saved to settings.ini.", "success")
        elif section == "test":
            to = (request.form.get("to") or "").strip() or None
            try:
                mailer.send_mail("[BCT Website] Test email",
                                 "This is a test message from the Bandjoun Community of Texas (BCT) website.\n\n"
                                 "If you received it, the email (SMTP) settings are working.", to=to)
                flash(f"Test email sent to {to or config.smtp_settings().get('recipient')}.", "success")
                log("Sent SMTP test email")
            except Exception as exc:  # noqa: BLE001
                flash(f"Test email failed: {exc}", "error")
            db.session.commit()
        return redirect(url_for("admin.settings"))
    site = {k: get_setting(k) for k in SITE_KEYS + ["zelle_qr"]}
    return render_template("admin/settings.html", site=site, smtp=dict(cp.items("smtp")),
                           server=dict(cp.items("server")), base_url=cp.get("site", "base_url"),
                           settings_path=config.SETTINGS_PATH)


# ---------------------------------------------------------------- users
@bp.route("/users", methods=["GET", "POST"])
@super_required
def users():
    if request.method == "POST":
        action = request.form.get("action")
        if action == "create":
            username = (request.form.get("username") or "").strip()
            pw = request.form.get("password") or ""
            role = request.form.get("role") if request.form.get("role") in ("superadmin", "editor") else "editor"
            if not username or len(pw) < 10:
                flash("Username required; password must be at least 10 characters.", "error")
            elif User.query.filter_by(username=username).first():
                flash("That username already exists.", "error")
            else:
                u = User(username=username, email=(request.form.get("email") or "").strip(), role=role)
                u.set_password(pw)
                db.session.add(u)
                log(f"Created admin user: {username} ({role})")
                flash(f"User {username} created.", "success")
        else:
            u = db.session.get(User, int(request.form.get("uid") or 0)) or abort(404)
            if action == "delete":
                if u.id == current_user.id:
                    flash("You cannot delete your own account.", "error")
                elif u.is_super and User.query.filter_by(role="superadmin").count() <= 1:
                    flash("At least one Super Admin must remain.", "error")
                else:
                    db.session.delete(u)
                    log(f"Deleted admin user: {u.username}")
                    flash(f"User {u.username} deleted.", "success")
            elif action == "role":
                role = request.form.get("role")
                if role in ("superadmin", "editor"):
                    if u.is_super and role == "editor" and User.query.filter_by(role="superadmin").count() <= 1:
                        flash("At least one Super Admin must remain.", "error")
                    else:
                        u.role = role
                        log(f"Changed role of {u.username} to {role}")
                        flash("Role updated.", "success")
            elif action == "reset":
                pw = request.form.get("password") or ""
                if len(pw) < 10:
                    flash("New password must be at least 10 characters.", "error")
                else:
                    u.set_password(pw)
                    u.failed_attempts, u.locked_until = 0, None
                    log(f"Reset password for {u.username}")
                    flash(f"Password reset for {u.username}.", "success")
            elif action == "unlock":
                u.failed_attempts, u.locked_until = 0, None
                flash(f"{u.username} unlocked.", "success")
            elif action == "disable2fa":
                u.totp_enabled, u.totp_secret = False, ""
                log(f"Turned off 2-step login for {u.username}")
                flash("Two-step login turned off for that user.", "success")
        db.session.commit()
        return redirect(url_for("admin.users"))
    return render_template("admin/users.html", users=User.query.order_by(User.username).all(),
                           now=datetime.utcnow())


@bp.route("/account", methods=["GET", "POST"])
def account():
    u = current_user
    qr_svg = None
    if request.method == "POST":
        action = request.form.get("action")
        if action == "password":
            if not u.check_password(request.form.get("current") or ""):
                flash("Your current password is not correct.", "error")
            elif len(request.form.get("new") or "") < 10:
                flash("The new password must be at least 10 characters.", "error")
            elif request.form.get("new") != request.form.get("confirm"):
                flash("The two new passwords do not match.", "error")
            else:
                u.set_password(request.form["new"])
                log("Changed own password")
                flash("Password changed.", "success")
        elif action == "email":
            u.email = (request.form.get("email") or "").strip()
            flash("Email saved.", "success")
        elif action == "2fa-start":
            u.totp_secret = pyotp.random_base32()
            u.totp_enabled = False
        elif action == "2fa-confirm":
            if u.totp_secret and pyotp.TOTP(u.totp_secret).verify((request.form.get("code") or "").replace(" ", ""),
                                                                    valid_window=1):
                u.totp_enabled = True
                log("Turned on 2-step login")
                flash("Two-step login is on. You will need your authenticator app at each sign-in.", "success")
            else:
                flash("That code did not match. Scan the QR code again and enter the current 6-digit code.", "error")
        elif action == "2fa-off":
            if u.check_password(request.form.get("current") or ""):
                u.totp_enabled, u.totp_secret = False, ""
                log("Turned off 2-step login")
                flash("Two-step login turned off.", "success")
            else:
                flash("Enter your current password to turn off two-step login.", "error")
        db.session.commit()
        if action not in ("2fa-start",) and not (action == "2fa-confirm" and not u.totp_enabled):
            return redirect(url_for("admin.account"))
    if u.totp_secret and not u.totp_enabled:
        uri = pyotp.TOTP(u.totp_secret).provisioning_uri(name=u.username, issuer_name="BCT Website")
        qr_svg = segno.make(uri).svg_inline(scale=5, dark="#3A3839")
    return render_template("admin/account.html", qr_svg=qr_svg)


@bp.route("/activity")
@super_required
def activity():
    items = Activity.query.order_by(Activity.created_at.desc()).limit(500).all()
    return render_template("admin/activity.html", items=items)


@bp.route("/backup", methods=["GET", "POST"])
@super_required
def backup():
    if request.method == "GET":
        size = 0
        for dp, _, fns in os.walk(uploads()):
            size += sum(os.path.getsize(os.path.join(dp, f)) for f in fns)
        return render_template("admin/backup.html", size_mb=size / 1024 / 1024)
    include_originals = form_bool("originals")
    tmp = tempfile.NamedTemporaryFile(prefix="bct-backup-", suffix=".zip", delete=False)
    tmp.close()
    db_path = db.engine.url.database
    with zipfile.ZipFile(tmp.name, "w", zipfile.ZIP_DEFLATED) as z:
        import sqlite3
        snap = tmp.name + ".db"
        src = sqlite3.connect(db_path)
        dst = sqlite3.connect(snap)
        src.backup(dst)
        dst.close()
        src.close()
        z.write(snap, "instance/bct.db")
        os.remove(snap)
        if os.path.exists(config.SETTINGS_PATH):
            z.write(config.SETTINGS_PATH, "settings.ini")
        root = uploads()
        for dp, _, fns in os.walk(root):
            if not include_originals and os.sep + "original" in dp:
                continue
            for fn in fns:
                full = os.path.join(dp, fn)
                z.write(full, os.path.join("uploads", os.path.relpath(full, root)),
                        compress_type=zipfile.ZIP_STORED)
    log("Downloaded a backup" + (" (with originals)" if include_originals else ""))
    db.session.commit()

    @after_this_request
    def cleanup(resp):
        try:
            os.remove(tmp.name)
        except OSError:
            pass
        return resp
    return send_file(tmp.name, as_attachment=True,
                     download_name=f"bct-website-backup-{datetime.now():%Y%m%d-%H%M}.zip")
