"""Flask web application for Parish Family Directory Data Collection (Souvenir Edition)."""

from __future__ import annotations

import io
import json
import os
import re
import secrets
import uuid
import zipfile
from datetime import date, datetime, timedelta, timezone
from functools import wraps
from typing import Any

from flask import (
    Flask,
    Response,
    abort,
    flash,
    jsonify,
    redirect,
    render_template,
    request,
    send_file,
    send_from_directory,
    session,
    url_for,
)
from openpyxl import Workbook
from openpyxl.styles import Alignment, Font, PatternFill
from openpyxl.utils import get_column_letter
from PIL import Image, ImageOps, UnidentifiedImageError

import db

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEFAULT_UPLOAD_DIR = os.path.join(BASE_DIR, "data", "uploads")
ALLOWED_EXTENSIONS = {"jpg", "jpeg", "png", "webp", "bmp"}
MAX_PHOTOS_PER_FAMILY = 1
PHOTO_MIN_DPI = 150
PHOTO_TARGET_DPI = 300
PHOTO_MIN_LONG_PX = 900   # 6 in * 150 DPI
PHOTO_MIN_SHORT_PX = 600  # 4 in * 150 DPI
MAX_UPLOAD_BYTES = 25 * 1024 * 1024  # 25 MB for single family photo
ALLOWED_WARD_UNITS = (
    "Queen of the Rosary Unit",
    "Little Flower Unit",
    "St. Alphonsa Unit",
    "St. Antony Unit",
    "St. Joseph Unit",
    "St. Peter Unit",
    "St. Jude Unit",
    "St. Rose Venerini Unit",
    "Vimala Matha Unit (Immaculate Mother)",
)
INDIAN_STATES_AND_UTS = (
    "Andhra Pradesh",
    "Arunachal Pradesh",
    "Assam",
    "Bihar",
    "Chhattisgarh",
    "Goa",
    "Gujarat",
    "Haryana",
    "Himachal Pradesh",
    "Jharkhand",
    "Karnataka",
    "Madhya Pradesh",
    "Maharashtra",
    "Manipur",
    "Meghalaya",
    "Mizoram",
    "Nagaland",
    "Odisha",
    "Punjab",
    "Rajasthan",
    "Sikkim",
    "Tamil Nadu",
    "Telangana",
    "Tripura",
    "Uttar Pradesh",
    "Uttarakhand",
    "West Bengal",
    "Andaman & Nicobar Islands",
    "Chandigarh",
    "Dadra & Nagar Haveli and Daman & Diu",
    "Delhi (NCT)",
    "Jammu & Kashmir",
    "Ladakh",
    "Lakshadweep",
    "Puducherry",
)


def _load_dotenv_if_present() -> None:
    env_path = os.path.join(BASE_DIR, ".env")
    if not os.path.isfile(env_path):
        return
    with open(env_path, "r", encoding="utf-8") as fh:
        for raw_line in fh:
            line = raw_line.strip()
            if not line or line.startswith("#") or "=" not in line:
                continue
            key, val = line.split("=", 1)
            key = key.strip()
            val = val.strip().strip('"').strip("'")
            if key and key not in os.environ:
                os.environ[key] = val


def _get_or_create_secret_key(testing: bool = False) -> str:
    env_secret = os.environ.get("PARISH_SECRET_KEY", "").strip()
    if env_secret:
        return env_secret
    if testing:
        return secrets.token_hex(32)
    key_file = os.path.join(BASE_DIR, "data", ".secret_key")
    if os.path.isfile(key_file):
        with open(key_file, "r", encoding="utf-8") as fh:
            existing = fh.read().strip()
            if existing:
                return existing
    os.makedirs(os.path.dirname(key_file), exist_ok=True)
    generated = secrets.token_hex(32)
    with open(key_file, "w", encoding="utf-8") as fh:
        fh.write(generated)
    return generated


def create_app(test_config: dict[str, Any] | None = None) -> Flask:
    _load_dotenv_if_present()
    app = Flask(__name__)
    is_testing = bool(test_config and test_config.get("TESTING"))
    app.config.update(
        SECRET_KEY=_get_or_create_secret_key(testing=is_testing),
        ADMIN_PASSWORD=os.environ.get("PARISH_ADMIN_PASSWORD", "parish2026"),
        UPLOAD_FOLDER=os.environ.get("PARISH_UPLOAD_DIR", DEFAULT_UPLOAD_DIR),
        DB_PATH=os.environ.get("PARISH_DB_PATH", db.DEFAULT_DB_PATH),
        SUBMISSION_DEADLINE=os.environ.get("PARISH_SUBMISSION_DEADLINE", ""),
        MAX_CONTENT_LENGTH=MAX_UPLOAD_BYTES,
    )
    if test_config:
        app.config.update(test_config)

    os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True)
    os.makedirs(os.path.join(app.config["UPLOAD_FOLDER"], "thumbs"), exist_ok=True)
    db.init_db(app.config["DB_PATH"])

    IST = timezone(timedelta(hours=5, minutes=30))

    @app.template_filter("format_ist")
    def format_ist(iso_str: str) -> str:
        if not iso_str:
            return ""
        try:
            dt = datetime.fromisoformat(iso_str)
            if dt.tzinfo is None:
                dt = dt.replace(tzinfo=timezone.utc)
            return dt.astimezone(IST).strftime("%Y-%m-%d %I:%M:%S %p IST")
        except ValueError:
            return iso_str

    @app.context_processor
    def inject_form_options():
        return {
            "ward_units": ALLOWED_WARD_UNITS,
            "indian_states": INDIAN_STATES_AND_UTS,
            "asset_v": "2026120305",
        }

    def _client_meta() -> tuple[str, str]:
        forwarded = (request.headers.get("X-Forwarded-For") or "").split(",")[0].strip()
        ip_addr = forwarded or (request.remote_addr or "")
        user_agent = (request.headers.get("User-Agent") or "")[:300]
        return ip_addr, user_agent

    def _log_phone(
        phone_number: str,
        event_type: str,
        *,
        reference_code: str = "",
        details: str = "",
    ) -> None:
        ip_addr, ua = _client_meta()
        db.log_phone_activity(
            phone_number,
            event_type,
            reference_code=reference_code,
            details=details,
            ip_address=ip_addr,
            user_agent=ua,
            db_path=app.config["DB_PATH"],
        )

    def _log_admin(
        action: str,
        *,
        target_type: str = "",
        target_id: str = "",
        details: str = "",
    ) -> None:
        ip_addr, ua = _client_meta()
        db.log_admin_activity(
            action,
            target_type=target_type,
            target_id=str(target_id),
            details=details,
            ip_address=ip_addr,
            user_agent=ua,
            db_path=app.config["DB_PATH"],
        )

    def login_required(view):
        @wraps(view)
        def wrapped(*args, **kwargs):
            if not session.get("is_admin"):
                return redirect(url_for("admin_login", next=request.path))
            return view(*args, **kwargs)

        return wrapped

    def _process_uploaded_photo(file_storage) -> dict[str, Any]:
        """Validate 6x4 in @ 300 DPI resolution, orient, save print-ready JPEG and thumbnail."""
        if not file_storage or not file_storage.filename:
            return {}

        original_name = file_storage.filename
        ext = original_name.rsplit(".", 1)[-1].lower() if "." in original_name else ""
        if ext not in ALLOWED_EXTENSIONS:
            raise ValueError(
                "Unsupported image format. Please upload JPG, PNG, or WEBP."
            )

        raw_bytes = file_storage.read()
        if not raw_bytes:
            return {}

        try:
            img = Image.open(io.BytesIO(raw_bytes))
            img = ImageOps.exif_transpose(img)
        except (UnidentifiedImageError, OSError) as exc:
            raise ValueError("The uploaded file could not be read as a valid image.") from exc

        if img.mode not in ("RGB", "L"):
            # Flatten alpha onto white background for clean print-ready JPEG
            background = Image.new("RGB", img.size, (255, 255, 255))
            if img.mode == "RGBA":
                background.paste(img, mask=img.split()[3])
            else:
                background.paste(img.convert("RGB"))
            img = background
        elif img.mode == "L":
            img = img.convert("RGB")

        width, height = img.size
        long_side = max(width, height)
        short_side = min(width, height)
        if long_side < PHOTO_MIN_LONG_PX or short_side < PHOTO_MIN_SHORT_PX:
            raise ValueError(
                f"Photo resolution is too low ({width}×{height} px). "
                f"Please upload a 6 × 4 in (Postcard size) photo at {PHOTO_MIN_DPI}–{PHOTO_TARGET_DPI} DPI "
                f"(minimum {PHOTO_MIN_LONG_PX} × {PHOTO_MIN_SHORT_PX} px), "
                "or share the original file via WhatsApp \"Document\" mode to your Unit President."
            )

        effective_dpi = min(
            PHOTO_TARGET_DPI,
            max(PHOTO_MIN_DPI, min(round(long_side / 6), round(short_side / 4))),
        )

        unique_id = uuid.uuid4().hex[:12]
        filename = f"family_{unique_id}.jpg"
        thumb_filename = f"thumb_{unique_id}.jpg"

        full_path = os.path.join(app.config["UPLOAD_FOLDER"], filename)
        thumb_path = os.path.join(app.config["UPLOAD_FOLDER"], "thumbs", thumb_filename)

        # Save high-quality print-ready JPEG with DPI in 150-300 range
        img.save(
            full_path,
            format="JPEG",
            quality=92,
            optimize=True,
            dpi=(effective_dpi, effective_dpi),
        )

        # Save thumbnail for fast web preview
        thumb = img.copy()
        thumb.thumbnail((600, 450), Image.Resampling.LANCZOS)
        thumb.save(thumb_path, format="JPEG", quality=85, optimize=True)

        return {
            "photo_filename": filename,
            "photo_thumb_filename": thumb_filename,
            "photo_original_name": original_name,
            "photo_width": width,
            "photo_height": height,
        }

    def _parse_uploaded_photos(req_files, existing_count: int = 0) -> list[dict[str, Any]]:
        """Process uploaded family photo, enforcing MAX_PHOTOS_PER_FAMILY (1 photo)."""
        candidates = [
            f
            for f in (req_files.getlist("family_photos") + req_files.getlist("family_photo"))
            if f and f.filename
        ]
        if existing_count + len(candidates) > MAX_PHOTOS_PER_FAMILY:
            raise ValueError(
                f"Only {MAX_PHOTOS_PER_FAMILY} Family Photo is allowed per family "
                f"(currently {existing_count}, attempting to add {len(candidates)})."
            )
        processed: list[dict[str, Any]] = []
        for file_storage in candidates:
            meta = _process_uploaded_photo(file_storage)
            if meta:
                processed.append(meta)
        return processed

    def _delete_photo_files(photo_records: list[dict[str, Any]]) -> None:
        for ph in photo_records:
            for rel_path in (
                ph.get("photo_filename"),
                os.path.join("thumbs", ph.get("photo_thumb_filename") or "")
                if ph.get("photo_thumb_filename")
                else "",
            ):
                if rel_path:
                    full = os.path.join(app.config["UPLOAD_FOLDER"], rel_path)
                    if os.path.isfile(full):
                        os.remove(full)

    def _parse_form_submission(
        req_form,
        req_files,
        existing_photo_count: int = 0,
        require_location_details: bool = True,
    ) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
        """Extract and normalize fields from multipart form submission."""
        ward_unit = (req_form.get("ward_unit") or "").strip()
        house_name = (req_form.get("house_name") or "").strip()
        head_of_family = (req_form.get("head_of_family") or "").strip()
        address = (req_form.get("address") or "").strip()
        raw_phone = (req_form.get("whatsapp_phone") or "").strip()
        whatsapp_phone = ""
        email = (req_form.get("email") or "").strip()

        errors = []
        if not ward_unit:
            errors.append("Ward / Unit & No. is required.")
        elif ward_unit not in ALLOWED_WARD_UNITS:
            errors.append(
                "Invalid Ward / Unit & No. Please select one of the allowed parish units."
            )
        if not house_name:
            errors.append("House Name (കുടുംബപ്പേര് / വീട്ടുപേര്) is required.")
        if not head_of_family:
            errors.append("Head of Family (കുടുംബനാഥന്റെ പേര്) is required.")
        if not address:
            errors.append("Address (മേൽവിലാസം) is required.")
        if not raw_phone:
            errors.append("WhatsApp Phone Number is required.")
        else:
            try:
                whatsapp_phone = db.normalize_phone(raw_phone)
            except ValueError as exc:
                errors.append(str(exc))
        if email and not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", email):
            errors.append("Please enter a valid Email ID or leave it blank.")
        if not req_form.get("declaration_accepted"):
            errors.append("Please accept the Declaration (സാക്ഷ്യപ്പെടുത്തൽ) before submitting.")

        # Parse dynamic family member rows
        names = req_form.getlist("member_name[]")
        relationships = req_form.getlist("member_relationship[]")
        dob_types = req_form.getlist("member_dob_type[]")
        dobs = req_form.getlist("member_dob[]")
        ages = req_form.getlist("member_age[]")
        qualifications = req_form.getlist("member_qualification[]")
        professions = req_form.getlist("member_profession[]")
        edu_jobs = req_form.getlist("member_edu_job[]")
        contacts = req_form.getlist("member_contact[]")
        residents = req_form.getlist("member_resident[]")
        kerala_locations = req_form.getlist("member_kerala_location[]")
        states = req_form.getlist("member_state[]")
        state_others = req_form.getlist("member_state_other[]")
        countries = req_form.getlist("member_country[]")

        row_count = max(
            len(names),
            len(relationships),
            len(dob_types),
            len(dobs),
            len(ages),
            len(qualifications),
            len(professions),
            len(edu_jobs),
            len(contacts),
            len(residents),
            len(kerala_locations),
            len(states),
            len(state_others),
            len(countries),
            0,
        )
        members: list[dict[str, Any]] = []
        for idx in range(row_count):
            full_name = names[idx].strip() if idx < len(names) else ""
            if not full_name:
                continue

            dob_type = (dob_types[idx].strip().lower() if idx < len(dob_types) else "")
            raw_dob = dobs[idx].strip() if idx < len(dobs) else ""
            raw_age = ages[idx].strip() if idx < len(ages) else ""

            if dob_type == "age" or (not raw_dob and raw_age):
                dob_val = ""
                age_val = raw_age
                if age_val:
                    if not age_val.isdigit() or not (0 <= int(age_val) <= 130):
                        errors.append(
                            f"Invalid age '{age_val}' for family member '{full_name}'. Enter an age between 0 and 130."
                        )
            else:
                dob_val = raw_dob
                age_val = ""

            qual_val = qualifications[idx].strip() if idx < len(qualifications) else ""
            prof_val = professions[idx].strip() if idx < len(professions) else ""
            legacy_edu_job = edu_jobs[idx].strip() if idx < len(edu_jobs) else ""
            if not qual_val and not prof_val and legacy_edu_job:
                edu_job_val = legacy_edu_job
            else:
                edu_job_val = " / ".join(x for x in (qual_val, prof_val) if x)

            res_status = residents[idx].strip() if idx < len(residents) else ""
            res_lower = res_status.lower()
            is_out_of_kerala = "out of kerala" in res_lower or "പുറത്ത്" in res_status
            is_nri = "nri" in res_lower or "out of india" in res_lower or "വിദേശ" in res_status
            is_in_kerala = (
                ("in kerala" in res_lower or "കേരളത്തിൽ" in res_status or "നാട്ടിൽ" in res_status)
                and not is_out_of_kerala
                and not is_nri
            )

            location_val = ""
            state_val = ""
            country_val = ""
            if is_in_kerala:
                location_val = (
                    kerala_locations[idx].strip() if idx < len(kerala_locations) else ""
                )
            elif is_out_of_kerala:
                raw_state = states[idx].strip() if idx < len(states) else ""
                other_state = state_others[idx].strip() if idx < len(state_others) else ""
                state_val = other_state if raw_state == "__OTHER__" else raw_state
                if require_location_details and not state_val:
                    errors.append(
                        f"Please select or type the State for '{full_name}' (Out of Kerala)."
                    )
            elif is_nri:
                country_val = countries[idx].strip() if idx < len(countries) else ""
                if require_location_details and not country_val:
                    errors.append(
                        f"Please type the Country for '{full_name}' (NRI / Out of India)."
                    )

            members.append(
                {
                    "full_name": full_name,
                    "relationship": relationships[idx].strip() if idx < len(relationships) else "",
                    "date_of_birth": dob_val,
                    "age": age_val,
                    "qualification": qual_val,
                    "profession": prof_val,
                    "education_job": edu_job_val,
                    "contact_no": contacts[idx].strip() if idx < len(contacts) else "",
                    "resident_status": res_status,
                    "resident_location": location_val,
                    "resident_state": state_val,
                    "resident_country": country_val,
                }
            )

        if errors:
            raise ValueError(" ".join(errors))

        # Parse priests / religious rows
        p_names = req_form.getlist("priest_name[]")
        p_congs = req_form.getlist("priest_congregation[]")
        p_postings = req_form.getlist("priest_posting[]")
        p_count = max(len(p_names), len(p_congs), len(p_postings), 0)
        priests: list[dict[str, Any]] = []
        for idx in range(p_count):
            p_name = p_names[idx].strip() if idx < len(p_names) else ""
            p_cong = p_congs[idx].strip() if idx < len(p_congs) else ""
            p_post = p_postings[idx].strip() if idx < len(p_postings) else ""
            if not (p_name or p_cong or p_post):
                continue
            priests.append(
                {
                    "name": p_name,
                    "congregation_diocese": p_cong,
                    "current_posting": p_post,
                }
            )

        photos = _parse_uploaded_photos(req_files, existing_count=existing_photo_count)

        data: dict[str, Any] = {
            "ward_unit": ward_unit,
            "house_name": house_name,
            "head_of_family": head_of_family,
            "address": address,
            "whatsapp_phone": whatsapp_phone,
            "alt_phone": (req_form.get("alt_phone") or "").strip(),
            "email": email,
            "photo_via_whatsapp": bool(req_form.get("photo_via_whatsapp")),
            "in_memoriam_page": bool(req_form.get("in_memoriam_page")),
            "family_greeting_page": bool(req_form.get("family_greeting_page")),
            "business_ad_page": bool(req_form.get("business_ad_page")),
            "in_memoriam_names": (req_form.get("in_memoriam_names") or "").strip(),
            "declaration_accepted": bool(req_form.get("declaration_accepted")),
            "submission_date": (req_form.get("submission_date") or "").strip()
            or date.today().isoformat(),
            "committee_notes": (req_form.get("committee_notes") or "").strip(),
            "verification_status": (req_form.get("verification_status") or "Pending").strip(),
        }
        return data, members, priests, photos

    def _remember_submitted_ref(ref_code: str) -> None:
        refs = list(session.get("submitted_refs") or [])
        if ref_code not in refs:
            refs.append(ref_code)
            session["submitted_refs"] = refs

    def _can_access_family(reference_code: str) -> bool:
        if session.get("is_admin"):
            return True
        return reference_code in (session.get("submitted_refs") or [])

    # ------------------------------------------------------------------
    # PWA & Public Routes
    # ------------------------------------------------------------------

    @app.get("/manifest.webmanifest")
    def web_manifest():
        return send_from_directory(
            app.static_folder,
            "manifest.webmanifest",
            mimetype="application/manifest+json",
        )

    @app.get("/sw.js")
    def service_worker():
        resp = send_from_directory(
            app.static_folder,
            "sw.js",
            mimetype="application/javascript",
        )
        resp.headers["Service-Worker-Allowed"] = "/"
        resp.headers["Cache-Control"] = "no-cache"
        return resp

    @app.get("/")
    def index():
        return render_template(
            "index.html",
            today=date.today().isoformat(),
            deadline=app.config["SUBMISSION_DEADLINE"],
        )

    @app.post("/submit")
    def submit_form():
        try:
            data, members, priests, photos = _parse_form_submission(
                request.form, request.files
            )
            _, ref_code = db.create_family(
                data, members, priests, photos=photos, db_path=app.config["DB_PATH"]
            )
        except ValueError as exc:
            flash(str(exc), "error")
            return render_template(
                "index.html",
                today=date.today().isoformat(),
                deadline=app.config["SUBMISSION_DEADLINE"],
                form_data=request.form,
            ), 400

        _remember_submitted_ref(ref_code)
        _log_phone(
            data["whatsapp_phone"],
            "FORM_SUBMITTED",
            reference_code=ref_code,
            details=(
                f"Submitted family form: {data['house_name']} ({data['ward_unit']}), "
                f"members={len(members)}, photos={len(photos)}"
            ),
        )
        return redirect(url_for("submission_success", reference_code=ref_code))

    @app.post("/api/submit")
    def api_submit():
        try:
            data, members, priests, photos = _parse_form_submission(
                request.form, request.files
            )
            family_id, ref_code = db.create_family(
                data, members, priests, photos=photos, db_path=app.config["DB_PATH"]
            )
        except ValueError as exc:
            return jsonify({"ok": False, "error": str(exc)}), 400

        _remember_submitted_ref(ref_code)
        _log_phone(
            data["whatsapp_phone"],
            "FORM_SUBMITTED",
            reference_code=ref_code,
            details=(
                f"Submitted family form via API: {data['house_name']} ({data['ward_unit']}), "
                f"members={len(members)}, photos={len(photos)}"
            ),
        )
        return jsonify(
            {
                "ok": True,
                "family_id": family_id,
                "reference_code": ref_code,
                "photo_count": len(photos),
                "redirect_url": url_for("submission_success", reference_code=ref_code),
            }
        ), 201

    @app.get("/submission/<reference_code>")
    def submission_success(reference_code: str):
        family = db.get_family(reference_code=reference_code, db_path=app.config["DB_PATH"])
        if not family:
            abort(404)

        is_admin = bool(session.get("is_admin"))
        if not _can_access_family(reference_code):
            abort(403)

        if is_admin:
            _log_admin(
                "VIEW_SUBMISSION",
                target_type="family",
                target_id=reference_code,
                details=f"Viewed submission confirmation page for {family['house_name']}",
            )
        else:
            _log_phone(
                family["whatsapp_phone"],
                "FORM_VIEWED",
                reference_code=reference_code,
                details="Viewed submitted family details",
            )
        return render_template("success.html", family=family, view_only=True)

    @app.get("/submission/<reference_code>/print")
    def submission_print(reference_code: str):
        family = db.get_family(reference_code=reference_code, db_path=app.config["DB_PATH"])
        if not family:
            abort(404)

        is_admin = bool(session.get("is_admin"))
        if not _can_access_family(reference_code):
            abort(403)

        if is_admin:
            _log_admin(
                "PRINT_FAMILY",
                target_type="family",
                target_id=reference_code,
                details=f"Opened print view for {family['house_name']}",
            )
        else:
            _log_phone(
                family["whatsapp_phone"],
                "PRINT_VIEWED",
                reference_code=reference_code,
                details="Opened printable official form",
            )
        return render_template(
            "print_form.html",
            family=family,
            deadline=app.config["SUBMISSION_DEADLINE"],
        )

    @app.get("/uploads/<path:filename>")
    def uploaded_file(filename: str):
        is_admin = bool(session.get("is_admin"))
        submitted_refs = session.get("submitted_refs") or []
        if not is_admin and not db.refs_own_photo(
            submitted_refs, filename, db_path=app.config["DB_PATH"]
        ):
            abort(403)
        return send_from_directory(app.config["UPLOAD_FOLDER"], filename)

    # ------------------------------------------------------------------
    # Admin / Committee Routes
    # ------------------------------------------------------------------

    @app.route("/admin/login", methods=["GET", "POST"])
    def admin_login():
        if request.method == "POST":
            password = request.form.get("password") or ""
            if secrets.compare_digest(password, app.config["ADMIN_PASSWORD"]):
                session["is_admin"] = True
                _log_admin("ADMIN_LOGIN_SUCCESS", target_type="auth", details="Admin signed in")
                next_url = request.args.get("next") or url_for("admin_dashboard")
                return redirect(next_url)
            _log_admin("ADMIN_LOGIN_FAILED", target_type="auth", details="Invalid admin password attempt")
            flash("Invalid committee password. Please try again.", "error")
        return render_template("admin_login.html")

    @app.get("/admin/logout")
    def admin_logout():
        if session.get("is_admin"):
            _log_admin("ADMIN_LOGOUT", target_type="auth", details="Admin signed out")
        session.pop("is_admin", None)
        return redirect(url_for("index"))

    @app.get("/admin")
    @login_required
    def admin_dashboard():
        search = request.args.get("q", "").strip()
        ward = request.args.get("ward", "").strip()
        souvenir = request.args.get("souvenir", "").strip()
        photo = request.args.get("photo", "").strip()
        status = request.args.get("status", "").strip()

        families = db.list_families(
            search=search,
            ward=ward,
            souvenir_filter=souvenir,
            photo_filter=photo,
            status_filter=status,
            db_path=app.config["DB_PATH"],
        )
        stats = db.get_dashboard_stats(db_path=app.config["DB_PATH"])
        active_filters = {
            k: v
            for k, v in (
                ("q", search),
                ("ward", ward),
                ("souvenir", souvenir),
                ("photo", photo),
                ("status", status),
            )
            if v
        }
        _log_admin(
            "VIEW_DASHBOARD",
            target_type="dashboard",
            details=f"Listed {len(families)} families"
            + (f" with filters {active_filters}" if active_filters else ""),
        )
        return render_template(
            "admin.html",
            families=families,
            stats=stats,
            filters={
                "q": search,
                "ward": ward,
                "souvenir": souvenir,
                "photo": photo,
                "status": status,
            },
        )

    @app.route("/admin/family/<int:family_id>", methods=["GET", "POST"])
    @login_required
    def admin_family_detail(family_id: int):
        family = db.get_family(family_id=family_id, db_path=app.config["DB_PATH"])
        if not family:
            abort(404)

        if request.method == "POST":
            try:
                # Admin edit does not require re-checking declaration checkbox if already accepted
                form_copy = request.form.to_dict(flat=False)
                if "declaration_accepted" not in form_copy:
                    form_copy["declaration_accepted"] = ["on"]

                class _MultiDict(dict):
                    def get(self, key, default=None):
                        vals = super().get(key)
                        return vals[0] if vals else default

                    def getlist(self, key):
                        return super().get(key, [])

                delete_photo_ids = [
                    int(pid)
                    for pid in request.form.getlist("delete_photo_ids[]")
                    if str(pid).isdigit()
                ]
                remaining_photos = len(
                    [p for p in family.get("photos", []) if p["id"] not in delete_photo_ids]
                )
                data, members, priests, new_photos = _parse_form_submission(
                    _MultiDict(form_copy),
                    request.files,
                    existing_photo_count=remaining_photos,
                    require_location_details=False,
                )
                removed_photos = db.update_family(
                    family_id,
                    data,
                    members,
                    priests,
                    new_photos=new_photos,
                    delete_photo_ids=delete_photo_ids,
                    db_path=app.config["DB_PATH"],
                )
                _delete_photo_files(removed_photos)
                _log_admin(
                    "EDIT_FAMILY",
                    target_type="family",
                    target_id=family["reference_code"],
                    details=(
                        f"Updated {family['reference_code']} ({data['house_name']}), "
                        f"status={data['verification_status']}, "
                        f"photos_added={len(new_photos)}, photos_removed={len(removed_photos)}"
                    ),
                )
                flash("Family record updated successfully.", "success")
                return redirect(url_for("admin_family_detail", family_id=family_id))
            except ValueError as exc:
                _log_admin(
                    "EDIT_FAMILY_FAILED",
                    target_type="family",
                    target_id=family["reference_code"],
                    details=str(exc),
                )
                flash(str(exc), "error")
        else:
            _log_admin(
                "VIEW_FAMILY",
                target_type="family",
                target_id=family["reference_code"],
                details=f"Opened detail view for {family['house_name']}",
            )

        return render_template("admin_detail.html", family=family)

    @app.post("/admin/family/<int:family_id>/delete")
    @login_required
    def admin_delete_family(family_id: int):
        deleted = db.delete_family(family_id, db_path=app.config["DB_PATH"])
        if not deleted:
            abort(404)
        _delete_photo_files(deleted.get("photos") or [deleted])
        _log_admin(
            "DELETE_FAMILY",
            target_type="family",
            target_id=deleted["reference_code"],
            details=f"Deleted {deleted['reference_code']} ({deleted['house_name']}, phone={deleted['whatsapp_phone']})",
        )
        flash(
            f"Deleted submission {deleted['reference_code']} ({deleted['house_name']}).",
            "success",
        )
        return redirect(url_for("admin_dashboard"))

    @app.get("/admin/logs")
    @login_required
    def admin_logs():
        tab = request.args.get("tab", "phone").strip() or "phone"
        q = request.args.get("q", "").strip()
        event_type = request.args.get("event_type", "").strip()
        action = request.args.get("action", "").strip()

        _log_admin(
            "VIEW_LOGS",
            target_type="logs",
            details=f"Viewed activity logs (tab={tab}, q={q!r})",
        )
        phone_logs = db.list_phone_activity_logs(
            search=q if tab == "phone" else "",
            event_type=event_type if tab == "phone" else "",
            db_path=app.config["DB_PATH"],
        )
        admin_activity = db.list_admin_activity_logs(
            search=q if tab == "admin" else "",
            action=action if tab == "admin" else "",
            db_path=app.config["DB_PATH"],
        )
        return render_template(
            "admin_logs.html",
            tab=tab,
            q=q,
            event_type=event_type,
            action=action,
            phone_logs=phone_logs,
            admin_logs=admin_activity,
        )

    # ------------------------------------------------------------------
    # Export Routes
    # ------------------------------------------------------------------

    @app.get("/admin/export/excel")
    @login_required
    def export_excel():
        families = db.get_all_full_families(db_path=app.config["DB_PATH"])
        _log_admin(
            "EXPORT_EXCEL",
            target_type="export",
            details=f"Exported Excel workbook ({len(families)} families)",
        )

        wb = Workbook()
        header_fill = PatternFill(start_color="7C1D26", end_color="7C1D26", fill_type="solid")
        header_font = Font(color="FFFFFF", bold=True, size=11)

        def style_header(ws):
            for cell in ws[1]:
                cell.fill = header_fill
                cell.font = header_font
                cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
            ws.freeze_panes = "A2"

        def autosize(ws):
            for col in ws.columns:
                max_len = 12
                col_letter = get_column_letter(col[0].column)
                for cell in col:
                    val = str(cell.value or "")
                    max_len = max(max_len, min(len(val) + 3, 45))
                ws.column_dimensions[col_letter].width = max_len

        # Sheet 1: Families
        ws1 = wb.active
        ws1.title = "Families"
        ws1.append(
            [
                "Reference Code",
                "Ward / Unit",
                "House Name",
                "Head of Family",
                "Address",
                "WhatsApp Phone",
                "Alt Mobile",
                "Email ID",
                "Members Count",
                "Priests/Religious Count",
                "Photos Count",
                "Photo Via WhatsApp",
                "Photo Files",
                "In Memoriam Page",
                "Family Greeting Page",
                "Business Ad Page",
                "Names for In Memoriam",
                "Submission Date",
                "Verification Status",
                "Committee Notes",
            ]
        )
        for f in families:
            photo_names = ", ".join(p["photo_filename"] for p in f.get("photos", []))
            ws1.append(
                [
                    f["reference_code"],
                    f["ward_unit"],
                    f["house_name"],
                    f["head_of_family"],
                    f["address"],
                    f["whatsapp_phone"],
                    f["alt_phone"],
                    f.get("email", ""),
                    len(f["members"]),
                    len(f["priests"]),
                    len(f.get("photos", [])),
                    "Yes" if f["photo_via_whatsapp"] else "No",
                    photo_names,
                    "Yes" if f["in_memoriam_page"] else "No",
                    "Yes" if f["family_greeting_page"] else "No",
                    "Yes" if f["business_ad_page"] else "No",
                    f["in_memoriam_names"],
                    f["submission_date"],
                    f["verification_status"],
                    f["committee_notes"],
                ]
            )
        style_header(ws1)
        autosize(ws1)

        # Sheet 2: Family Members
        ws2 = wb.create_sheet("Family Members")
        ws2.append(
            [
                "Reference Code",
                "Ward / Unit",
                "House Name",
                "Head of Family",
                "Sl. No.",
                "Full Name (with Christian Name)",
                "Relationship",
                "Date of Birth",
                "Age",
                "Qualification",
                "Profession",
                "Contact No.",
                "Resident Status",
                "Location (If In Kerala)",
                "State (If Out of Kerala)",
                "Country (If NRI)",
            ]
        )
        for f in families:
            for m in f["members"]:
                qual = m.get("qualification") or ""
                prof = m.get("profession") or ""
                if not qual and not prof and m.get("education_job"):
                    qual = m["education_job"]
                ws2.append(
                    [
                        f["reference_code"],
                        f["ward_unit"],
                        f["house_name"],
                        f["head_of_family"],
                        m["member_order"],
                        m["full_name"],
                        m["relationship"],
                        m["date_of_birth"],
                        m.get("age", ""),
                        qual,
                        prof,
                        m["contact_no"],
                        m["resident_status"],
                        m.get("resident_location", ""),
                        m.get("resident_state", ""),
                        m.get("resident_country", ""),
                    ]
                )
        style_header(ws2)
        autosize(ws2)

        # Sheet 3: Priests & Religious
        ws3 = wb.create_sheet("Priests & Religious")
        ws3.append(
            [
                "Reference Code",
                "Ward / Unit",
                "House Name",
                "Head of Family",
                "Entry No.",
                "Priest / Sister / Brother Name",
                "Congregation / Diocese",
                "Current Posting",
            ]
        )
        for f in families:
            for p in f["priests"]:
                ws3.append(
                    [
                        f["reference_code"],
                        f["ward_unit"],
                        f["house_name"],
                        f["head_of_family"],
                        p["entry_order"],
                        p["name"],
                        p["congregation_diocese"],
                        p["current_posting"],
                    ]
                )
        style_header(ws3)
        autosize(ws3)

        # Sheet 4: Souvenir & In Memoriam
        ws4 = wb.create_sheet("Souvenir & In Memoriam")
        ws4.append(
            [
                "Reference Code",
                "Ward / Unit",
                "House Name",
                "Head of Family",
                "WhatsApp Phone",
                "In Memoriam Page",
                "Family Greeting Page",
                "Business Ad Page",
                "Names for In Memoriam",
            ]
        )
        for f in families:
            if (
                f["in_memoriam_page"]
                or f["family_greeting_page"]
                or f["business_ad_page"]
                or f["in_memoriam_names"]
            ):
                ws4.append(
                    [
                        f["reference_code"],
                        f["ward_unit"],
                        f["house_name"],
                        f["head_of_family"],
                        f["whatsapp_phone"],
                        "Yes" if f["in_memoriam_page"] else "No",
                        "Yes" if f["family_greeting_page"] else "No",
                        "Yes" if f["business_ad_page"] else "No",
                        f["in_memoriam_names"],
                    ]
                )
        style_header(ws4)
        autosize(ws4)

        buf = io.BytesIO()
        wb.save(buf)
        buf.seek(0)
        filename = f"parish_family_directory_{date.today().isoformat()}.xlsx"
        return send_file(
            buf,
            as_attachment=True,
            download_name=filename,
            mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        )

    @app.get("/admin/export/photos")
    @login_required
    def export_photos():
        families = db.get_all_full_families(db_path=app.config["DB_PATH"])
        _log_admin(
            "EXPORT_PHOTOS_ZIP",
            target_type="export",
            details=f"Exported photos ZIP ({len(families)} families)",
        )
        buf = io.BytesIO()

        def _slug(val: str) -> str:
            cleaned = re.sub(r"[^\w\-]+", "_", val.strip(), flags=re.UNICODE)
            return cleaned.strip("_") or "item"

        with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
            for f in families:
                photos = f.get("photos") or []
                for idx, ph in enumerate(photos, start=1):
                    fname = ph.get("photo_filename")
                    if not fname:
                        continue
                    full_path = os.path.join(app.config["UPLOAD_FOLDER"], fname)
                    if not os.path.isfile(full_path):
                        continue
                    suffix = f"_{idx}" if len(photos) > 1 else ""
                    arcname = (
                        f"{_slug(f['ward_unit'])}/"
                        f"{_slug(f['house_name'])}_{_slug(f['head_of_family'])}_{f['reference_code']}{suffix}.jpg"
                    )
                    zf.write(full_path, arcname=arcname)

        buf.seek(0)
        return send_file(
            buf,
            as_attachment=True,
            download_name=f"parish_family_photos_{date.today().isoformat()}.zip",
            mimetype="application/zip",
        )

    @app.get("/admin/export/json")
    @login_required
    def export_json():
        families = db.get_all_full_families(db_path=app.config["DB_PATH"])
        _log_admin(
            "EXPORT_JSON",
            target_type="export",
            details=f"Exported JSON backup ({len(families)} families)",
        )
        payload = json.dumps(families, ensure_ascii=False, indent=2)
        return Response(
            payload,
            mimetype="application/json",
            headers={
                "Content-Disposition": (
                    f"attachment; filename=parish_family_directory_{date.today().isoformat()}.json"
                )
            },
        )

    return app


app = create_app()

if __name__ == "__main__":
    port = int(os.environ.get("PORT", "5000"))
    debug = os.environ.get("FLASK_DEBUG", "0") == "1"
    app.run(host="0.0.0.0", port=port, debug=debug)
