"""SQLite database layer for the Parish Family Directory Data Collection app."""

from __future__ import annotations

import os
import re
import sqlite3
import uuid
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from typing import Any, Iterator

DEFAULT_DB_PATH = os.path.join(
    os.path.dirname(os.path.abspath(__file__)), "data", "parish_directory.db"
)


def normalize_phone(raw_phone: str) -> str:
    """Validate and normalize a phone number into canonical E.164 format."""
    text = (raw_phone or "").strip()
    if text.lower().startswith("whatsapp:"):
        text = text[9:].strip()
    cleaned = re.sub(r"[\s\-\(\)\.]+", "", text)
    if not cleaned:
        raise ValueError("Please enter a valid WhatsApp phone number.")

    if cleaned.startswith("00"):
        cleaned = "+" + cleaned[2:]

    if re.fullmatch(r"[6-9]\d{9}", cleaned):
        return "+91" + cleaned
    if re.fullmatch(r"0[6-9]\d{9}", cleaned):
        return "+91" + cleaned[1:]
    if re.fullmatch(r"91[6-9]\d{9}", cleaned):
        return "+" + cleaned
    if re.fullmatch(r"\+[1-9]\d{7,14}", cleaned):
        return cleaned

    raise ValueError(
        "Invalid phone number. Enter a 10-digit Indian mobile number or an "
        "international number with country code (e.g. +919847012345)."
    )


def normalize_webhook_sender(raw_sender: str) -> str:
    """Normalize incoming WhatsApp webhook sender IDs (including Meta wa_id without '+')."""
    try:
        return normalize_phone(raw_sender)
    except ValueError:
        cleaned = re.sub(r"[\s\-\(\)\.]+", "", (raw_sender or "").strip())
        if re.fullmatch(r"[1-9]\d{7,14}", cleaned):
            return "+" + cleaned
        raise


def phone_lookup_variants(normalized_phone: str) -> list[str]:
    """Return canonical and legacy Indian formatting variants for DB lookups."""
    variants = [normalized_phone]
    if normalized_phone.startswith("+91") and len(normalized_phone) == 13:
        local10 = normalized_phone[3:]
        variants.extend([local10, "91" + local10, "0" + local10])
    return variants


def get_db_path() -> str:
    return os.environ.get("PARISH_DB_PATH", DEFAULT_DB_PATH)


@contextmanager
def get_connection(db_path: str | None = None) -> Iterator[sqlite3.Connection]:
    path = db_path or get_db_path()
    os.makedirs(os.path.dirname(path), exist_ok=True)
    conn = sqlite3.connect(path)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA foreign_keys = ON;")
    try:
        yield conn
        conn.commit()
    except Exception:
        conn.rollback()
        raise
    finally:
        conn.close()


def init_db(db_path: str | None = None) -> None:
    """Initialize database tables if they do not already exist."""
    with get_connection(db_path) as conn:
        conn.executescript(
            """
            CREATE TABLE IF NOT EXISTS families (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                reference_code TEXT UNIQUE NOT NULL,
                ward_unit TEXT NOT NULL,
                house_name TEXT NOT NULL,
                head_of_family TEXT NOT NULL,
                address TEXT NOT NULL,
                whatsapp_phone TEXT NOT NULL,
                alt_phone TEXT DEFAULT '',
                email TEXT DEFAULT '',
                photo_filename TEXT DEFAULT '',
                photo_thumb_filename TEXT DEFAULT '',
                photo_original_name TEXT DEFAULT '',
                photo_width INTEGER DEFAULT 0,
                photo_height INTEGER DEFAULT 0,
                photo_via_whatsapp INTEGER DEFAULT 0,
                in_memoriam_page INTEGER DEFAULT 0,
                family_greeting_page INTEGER DEFAULT 0,
                business_ad_page INTEGER DEFAULT 0,
                in_memoriam_names TEXT DEFAULT '',
                declaration_accepted INTEGER NOT NULL DEFAULT 1,
                submission_date TEXT NOT NULL,
                ward_animator_name TEXT DEFAULT '',
                ward_animator_signature TEXT DEFAULT '',
                head_signature_name TEXT DEFAULT '',
                head_signature_data TEXT DEFAULT '',
                committee_notes TEXT DEFAULT '',
                verification_status TEXT DEFAULT 'Pending',
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL
            );

            CREATE TABLE IF NOT EXISTS family_photos (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                family_id INTEGER NOT NULL,
                photo_order INTEGER NOT NULL,
                photo_filename TEXT NOT NULL,
                photo_thumb_filename TEXT DEFAULT '',
                photo_original_name TEXT DEFAULT '',
                photo_width INTEGER DEFAULT 0,
                photo_height INTEGER DEFAULT 0,
                FOREIGN KEY (family_id) REFERENCES families(id) ON DELETE CASCADE
            );

            CREATE TABLE IF NOT EXISTS family_members (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                family_id INTEGER NOT NULL,
                member_order INTEGER NOT NULL,
                full_name TEXT NOT NULL,
                relationship TEXT DEFAULT '',
                date_of_birth TEXT DEFAULT '',
                age TEXT DEFAULT '',
                qualification TEXT DEFAULT '',
                profession TEXT DEFAULT '',
                education_job TEXT DEFAULT '',
                contact_no TEXT DEFAULT '',
                resident_status TEXT DEFAULT '',
                resident_location TEXT DEFAULT '',
                resident_state TEXT DEFAULT '',
                resident_country TEXT DEFAULT '',
                FOREIGN KEY (family_id) REFERENCES families(id) ON DELETE CASCADE
            );

            CREATE TABLE IF NOT EXISTS priests_religious (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                family_id INTEGER NOT NULL,
                entry_order INTEGER NOT NULL,
                name TEXT NOT NULL,
                congregation_diocese TEXT DEFAULT '',
                current_posting TEXT DEFAULT '',
                FOREIGN KEY (family_id) REFERENCES families(id) ON DELETE CASCADE
            );

            CREATE INDEX IF NOT EXISTS idx_families_ward ON families(ward_unit);
            CREATE INDEX IF NOT EXISTS idx_families_house ON families(house_name);
            CREATE INDEX IF NOT EXISTS idx_families_ref ON families(reference_code);
            CREATE INDEX IF NOT EXISTS idx_families_phone ON families(whatsapp_phone);
            CREATE INDEX IF NOT EXISTS idx_photos_family ON family_photos(family_id);
            CREATE INDEX IF NOT EXISTS idx_members_family ON family_members(family_id);
            CREATE INDEX IF NOT EXISTS idx_priests_family ON priests_religious(family_id);

            CREATE TABLE IF NOT EXISTS otp_challenges (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                challenge_id TEXT UNIQUE NOT NULL,
                phone_number TEXT NOT NULL,
                otp_code TEXT NOT NULL,
                status TEXT NOT NULL DEFAULT 'pending',
                expires_at TEXT NOT NULL,
                verified_at TEXT DEFAULT '',
                consumed_at TEXT DEFAULT '',
                sender_reported TEXT DEFAULT '',
                ip_address TEXT DEFAULT '',
                user_agent TEXT DEFAULT '',
                created_at TEXT NOT NULL
            );

            CREATE INDEX IF NOT EXISTS idx_otp_phone_status ON otp_challenges(phone_number, status);
            CREATE INDEX IF NOT EXISTS idx_otp_challenge_id ON otp_challenges(challenge_id);

            CREATE TABLE IF NOT EXISTS phone_activity_logs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                phone_number TEXT NOT NULL,
                event_type TEXT NOT NULL,
                reference_code TEXT DEFAULT '',
                details TEXT DEFAULT '',
                ip_address TEXT DEFAULT '',
                user_agent TEXT DEFAULT '',
                created_at TEXT NOT NULL
            );

            CREATE INDEX IF NOT EXISTS idx_phone_logs_phone ON phone_activity_logs(phone_number);
            CREATE INDEX IF NOT EXISTS idx_phone_logs_event ON phone_activity_logs(event_type);
            CREATE INDEX IF NOT EXISTS idx_phone_logs_created ON phone_activity_logs(created_at);

            CREATE TABLE IF NOT EXISTS admin_activity_logs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                action TEXT NOT NULL,
                target_type TEXT DEFAULT '',
                target_id TEXT DEFAULT '',
                details TEXT DEFAULT '',
                ip_address TEXT DEFAULT '',
                user_agent TEXT DEFAULT '',
                created_at TEXT NOT NULL
            );

            CREATE INDEX IF NOT EXISTS idx_admin_logs_action ON admin_activity_logs(action);
            CREATE INDEX IF NOT EXISTS idx_admin_logs_created ON admin_activity_logs(created_at);
            """
        )
        # Migrate existing families table with new columns if missing
        existing_family_cols = {
            row["name"]
            for row in conn.execute("PRAGMA table_info(families)").fetchall()
        }
        if "email" not in existing_family_cols:
            conn.execute("ALTER TABLE families ADD COLUMN email TEXT DEFAULT ''")

        # Migrate existing family_members table with new columns if missing
        existing_member_cols = {
            row["name"]
            for row in conn.execute("PRAGMA table_info(family_members)").fetchall()
        }
        for col_name, col_def in (
            ("age", "TEXT DEFAULT ''"),
            ("qualification", "TEXT DEFAULT ''"),
            ("profession", "TEXT DEFAULT ''"),
            ("resident_location", "TEXT DEFAULT ''"),
            ("resident_state", "TEXT DEFAULT ''"),
            ("resident_country", "TEXT DEFAULT ''"),
        ):
            if col_name not in existing_member_cols:
                conn.execute(
                    f"ALTER TABLE family_members ADD COLUMN {col_name} {col_def}"
                )

        # Backfill any legacy single-photo rows into family_photos
        conn.execute(
            """
            INSERT INTO family_photos (
                family_id, photo_order, photo_filename, photo_thumb_filename,
                photo_original_name, photo_width, photo_height
            )
            SELECT
                f.id, 1, f.photo_filename, f.photo_thumb_filename,
                f.photo_original_name, f.photo_width, f.photo_height
            FROM families f
            WHERE f.photo_filename != ''
              AND NOT EXISTS (
                  SELECT 1 FROM family_photos p WHERE p.family_id = f.id
              )
            """
        )


def _generate_reference_code(conn: sqlite3.Connection) -> str:
    row = conn.execute("SELECT COALESCE(MAX(id), 0) + 1 AS next_id FROM families").fetchone()
    next_id = int(row["next_id"])
    year = datetime.now(timezone.utc).year
    return f"FAM-{year}-{next_id:04d}"


def _sync_primary_photo_columns(conn: sqlite3.Connection, family_id: int) -> None:
    first = conn.execute(
        "SELECT * FROM family_photos WHERE family_id = ? ORDER BY photo_order ASC, id ASC LIMIT 1",
        (family_id,),
    ).fetchone()
    if first:
        conn.execute(
            """
            UPDATE families SET
                photo_filename = ?,
                photo_thumb_filename = ?,
                photo_original_name = ?,
                photo_width = ?,
                photo_height = ?
            WHERE id = ?
            """,
            (
                first["photo_filename"],
                first["photo_thumb_filename"],
                first["photo_original_name"],
                first["photo_width"],
                first["photo_height"],
                family_id,
            ),
        )
    else:
        conn.execute(
            """
            UPDATE families SET
                photo_filename = '',
                photo_thumb_filename = '',
                photo_original_name = '',
                photo_width = 0,
                photo_height = 0
            WHERE id = ?
            """,
            (family_id,),
        )


def create_family(
    data: dict[str, Any],
    members: list[dict[str, Any]],
    priests: list[dict[str, Any]],
    photos: list[dict[str, Any]] | None = None,
    db_path: str | None = None,
) -> tuple[int, str]:
    """Insert a complete family submission and return (family_id, reference_code)."""
    now = datetime.now(timezone.utc).isoformat(timespec="seconds")
    photo_list = list(photos or [])
    first_photo = photo_list[0] if photo_list else {}

    with get_connection(db_path) as conn:
        phone_norm = normalize_phone(data["whatsapp_phone"])

        ref_code = _generate_reference_code(conn)
        cur = conn.execute(
            """
            INSERT INTO families (
                reference_code, ward_unit, house_name, head_of_family, address,
                whatsapp_phone, alt_phone, email, photo_filename, photo_thumb_filename,
                photo_original_name, photo_width, photo_height, photo_via_whatsapp,
                in_memoriam_page, family_greeting_page, business_ad_page,
                in_memoriam_names, declaration_accepted, submission_date,
                ward_animator_name, ward_animator_signature,
                head_signature_name, head_signature_data,
                committee_notes, verification_status, created_at, updated_at
            ) VALUES (
                ?, ?, ?, ?, ?,
                ?, ?, ?, ?, ?,
                ?, ?, ?, ?,
                ?, ?, ?,
                ?, ?, ?,
                ?, ?,
                ?, ?,
                ?, ?, ?, ?
            )
            """,
            (
                ref_code,
                data["ward_unit"].strip(),
                data["house_name"].strip(),
                data["head_of_family"].strip(),
                data["address"].strip(),
                phone_norm,
                data.get("alt_phone", "").strip(),
                data.get("email", "").strip(),
                first_photo.get("photo_filename", ""),
                first_photo.get("photo_thumb_filename", ""),
                first_photo.get("photo_original_name", ""),
                int(first_photo.get("photo_width", 0) or 0),
                int(first_photo.get("photo_height", 0) or 0),
                1 if data.get("photo_via_whatsapp") else 0,
                1 if data.get("in_memoriam_page") else 0,
                1 if data.get("family_greeting_page") else 0,
                1 if data.get("business_ad_page") else 0,
                data.get("in_memoriam_names", "").strip(),
                1 if data.get("declaration_accepted", True) else 0,
                data.get("submission_date", "").strip() or now[:10],
                data.get("ward_animator_name", "").strip(),
                data.get("ward_animator_signature", ""),
                data.get("head_signature_name", "").strip(),
                data.get("head_signature_data", ""),
                data.get("committee_notes", "").strip(),
                data.get("verification_status", "Pending"),
                now,
                now,
            ),
        )
        family_id = int(cur.lastrowid)
        for idx, ph in enumerate(photo_list, start=1):
            conn.execute(
                """
                INSERT INTO family_photos (
                    family_id, photo_order, photo_filename, photo_thumb_filename,
                    photo_original_name, photo_width, photo_height
                ) VALUES (?, ?, ?, ?, ?, ?, ?)
                """,
                (
                    family_id,
                    idx,
                    ph["photo_filename"],
                    ph.get("photo_thumb_filename", ""),
                    ph.get("photo_original_name", ""),
                    int(ph.get("photo_width", 0) or 0),
                    int(ph.get("photo_height", 0) or 0),
                ),
            )
        _replace_children(conn, family_id, members, priests)
        return family_id, ref_code


def _replace_children(
    conn: sqlite3.Connection,
    family_id: int,
    members: list[dict[str, Any]],
    priests: list[dict[str, Any]],
) -> None:
    conn.execute("DELETE FROM family_members WHERE family_id = ?", (family_id,))
    for idx, member in enumerate(members, start=1):
        full_name = (member.get("full_name") or "").strip()
        if not full_name:
            continue
        qualification = (member.get("qualification") or "").strip()
        profession = (member.get("profession") or "").strip()
        edu_job = (member.get("education_job") or "").strip()
        if not edu_job and (qualification or profession):
            edu_job = " / ".join(x for x in (qualification, profession) if x)
        conn.execute(
            """
            INSERT INTO family_members (
                family_id, member_order, full_name, relationship,
                date_of_birth, age, qualification, profession,
                education_job, contact_no, resident_status,
                resident_location, resident_state, resident_country
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (
                family_id,
                idx,
                full_name,
                (member.get("relationship") or "").strip(),
                (member.get("date_of_birth") or "").strip(),
                (member.get("age") or "").strip(),
                qualification,
                profession,
                edu_job,
                (member.get("contact_no") or "").strip(),
                (member.get("resident_status") or "").strip(),
                (member.get("resident_location") or "").strip(),
                (member.get("resident_state") or "").strip(),
                (member.get("resident_country") or "").strip(),
            ),
        )

    conn.execute("DELETE FROM priests_religious WHERE family_id = ?", (family_id,))
    for idx, priest in enumerate(priests, start=1):
        name = (priest.get("name") or "").strip()
        cong = (priest.get("congregation_diocese") or "").strip()
        posting = (priest.get("current_posting") or "").strip()
        if not (name or cong or posting):
            continue
        conn.execute(
            """
            INSERT INTO priests_religious (
                family_id, entry_order, name, congregation_diocese, current_posting
            ) VALUES (?, ?, ?, ?, ?)
            """,
            (family_id, idx, name, cong, posting),
        )


def update_family(
    family_id: int,
    data: dict[str, Any],
    members: list[dict[str, Any]],
    priests: list[dict[str, Any]],
    new_photos: list[dict[str, Any]] | None = None,
    delete_photo_ids: list[int] | None = None,
    db_path: str | None = None,
) -> list[dict[str, Any]]:
    """Update an existing family submission and return removed photo records for disk cleanup."""
    now = datetime.now(timezone.utc).isoformat(timespec="seconds")
    removed_photos: list[dict[str, Any]] = []

    with get_connection(db_path) as conn:
        existing = conn.execute("SELECT id FROM families WHERE id = ?", (family_id,)).fetchone()
        if not existing:
            raise ValueError("Family record not found.")

        phone_norm = normalize_phone(data["whatsapp_phone"])

        if delete_photo_ids:
            placeholders = ",".join("?" for _ in delete_photo_ids)
            rows = conn.execute(
                f"SELECT * FROM family_photos WHERE family_id = ? AND id IN ({placeholders})",
                [family_id, *delete_photo_ids],
            ).fetchall()
            removed_photos = [dict(r) for r in rows]
            conn.execute(
                f"DELETE FROM family_photos WHERE family_id = ? AND id IN ({placeholders})",
                [family_id, *delete_photo_ids],
            )

        current_rows = conn.execute(
            "SELECT * FROM family_photos WHERE family_id = ? ORDER BY photo_order ASC, id ASC",
            (family_id,),
        ).fetchall()
        for idx, r in enumerate(current_rows, start=1):
            conn.execute("UPDATE family_photos SET photo_order = ? WHERE id = ?", (idx, r["id"]))

        next_order = len(current_rows) + 1
        for ph in new_photos or []:
            if next_order > 1:
                break
            conn.execute(
                """
                INSERT INTO family_photos (
                    family_id, photo_order, photo_filename, photo_thumb_filename,
                    photo_original_name, photo_width, photo_height
                ) VALUES (?, ?, ?, ?, ?, ?, ?)
                """,
                (
                    family_id,
                    next_order,
                    ph["photo_filename"],
                    ph.get("photo_thumb_filename", ""),
                    ph.get("photo_original_name", ""),
                    int(ph.get("photo_width", 0) or 0),
                    int(ph.get("photo_height", 0) or 0),
                ),
            )
            next_order += 1

        conn.execute(
            """
            UPDATE families SET
                ward_unit = ?,
                house_name = ?,
                head_of_family = ?,
                address = ?,
                whatsapp_phone = ?,
                alt_phone = ?,
                email = ?,
                photo_via_whatsapp = ?,
                in_memoriam_page = ?,
                family_greeting_page = ?,
                business_ad_page = ?,
                in_memoriam_names = ?,
                submission_date = ?,
                committee_notes = ?,
                verification_status = ?,
                updated_at = ?
            WHERE id = ?
            """,
            (
                data["ward_unit"].strip(),
                data["house_name"].strip(),
                data["head_of_family"].strip(),
                data["address"].strip(),
                phone_norm,
                data.get("alt_phone", "").strip(),
                data.get("email", "").strip(),
                1 if data.get("photo_via_whatsapp") else 0,
                1 if data.get("in_memoriam_page") else 0,
                1 if data.get("family_greeting_page") else 0,
                1 if data.get("business_ad_page") else 0,
                data.get("in_memoriam_names", "").strip(),
                data.get("submission_date", "").strip() or now[:10],
                data.get("committee_notes", "").strip(),
                data.get("verification_status", "Pending"),
                now,
                family_id,
            ),
        )
        _sync_primary_photo_columns(conn, family_id)
        _replace_children(conn, family_id, members, priests)
        return removed_photos


def get_family(
    *,
    family_id: int | None = None,
    reference_code: str | None = None,
    whatsapp_phone: str | None = None,
    db_path: str | None = None,
) -> dict[str, Any] | None:
    """Fetch a single family with its photos, members, and priests/religious."""
    with get_connection(db_path) as conn:
        if family_id is not None:
            row = conn.execute("SELECT * FROM families WHERE id = ?", (family_id,)).fetchone()
        elif reference_code is not None:
            row = conn.execute(
                "SELECT * FROM families WHERE reference_code = ?", (reference_code,)
            ).fetchone()
        elif whatsapp_phone is not None:
            phone_norm = normalize_phone(whatsapp_phone)
            variants = phone_lookup_variants(phone_norm)
            placeholders = ",".join("?" for _ in variants)
            row = conn.execute(
                f"SELECT * FROM families WHERE whatsapp_phone IN ({placeholders}) ORDER BY id ASC LIMIT 1",
                variants,
            ).fetchone()
        else:
            return None

        if not row:
            return None

        family = dict(row)
        family["photos"] = [
            dict(r)
            for r in conn.execute(
                "SELECT * FROM family_photos WHERE family_id = ? ORDER BY photo_order ASC, id ASC",
                (family["id"],),
            ).fetchall()
        ]
        family["members"] = [
            dict(r)
            for r in conn.execute(
                "SELECT * FROM family_members WHERE family_id = ? ORDER BY member_order ASC",
                (family["id"],),
            ).fetchall()
        ]
        family["priests"] = [
            dict(r)
            for r in conn.execute(
                "SELECT * FROM priests_religious WHERE family_id = ? ORDER BY entry_order ASC",
                (family["id"],),
            ).fetchall()
        ]
        return family


def list_families(
    *,
    search: str = "",
    ward: str = "",
    souvenir_filter: str = "",
    photo_filter: str = "",
    status_filter: str = "",
    db_path: str | None = None,
) -> list[dict[str, Any]]:
    """List families with optional search and filters, including counts."""
    clauses = ["1=1"]
    params: list[Any] = []

    if search:
        like = f"%{search.strip()}%"
        clauses.append(
            "(f.reference_code LIKE ? OR f.house_name LIKE ? OR f.head_of_family LIKE ? "
            "OR f.ward_unit LIKE ? OR f.whatsapp_phone LIKE ? OR f.email LIKE ? OR f.address LIKE ?)"
        )
        params.extend([like, like, like, like, like, like, like])

    if ward:
        clauses.append("f.ward_unit = ?")
        params.append(ward)

    if souvenir_filter == "in_memoriam":
        clauses.append("f.in_memoriam_page = 1")
    elif souvenir_filter == "greeting":
        clauses.append("f.family_greeting_page = 1")
    elif souvenir_filter == "business_ad":
        clauses.append("f.business_ad_page = 1")

    if photo_filter == "uploaded":
        clauses.append("EXISTS (SELECT 1 FROM family_photos fp WHERE fp.family_id = f.id)")
    elif photo_filter == "whatsapp":
        clauses.append(
            "f.photo_via_whatsapp = 1 AND NOT EXISTS (SELECT 1 FROM family_photos fp WHERE fp.family_id = f.id)"
        )
    elif photo_filter == "missing":
        clauses.append(
            "f.photo_via_whatsapp = 0 AND NOT EXISTS (SELECT 1 FROM family_photos fp WHERE fp.family_id = f.id)"
        )

    if status_filter:
        clauses.append("f.verification_status = ?")
        params.append(status_filter)

    where_sql = " AND ".join(clauses)
    query = f"""
        SELECT
            f.*,
            (SELECT COUNT(*) FROM family_photos fp WHERE fp.family_id = f.id) AS photo_count,
            (SELECT COUNT(*) FROM family_members m WHERE m.family_id = f.id) AS member_count,
            (SELECT COUNT(*) FROM priests_religious p WHERE p.family_id = f.id) AS priest_count
        FROM families f
        WHERE {where_sql}
        ORDER BY f.id DESC
    """
    with get_connection(db_path) as conn:
        rows = conn.execute(query, params).fetchall()
        return [dict(r) for r in rows]


def get_all_full_families(db_path: str | None = None) -> list[dict[str, Any]]:
    """Return every family along with all nested photos, members, and priests for export."""
    with get_connection(db_path) as conn:
        families = [
            dict(r)
            for r in conn.execute("SELECT * FROM families ORDER BY ward_unit ASC, id ASC").fetchall()
        ]
        photos_by_fam: dict[int, list[dict[str, Any]]] = {}
        for r in conn.execute(
            "SELECT * FROM family_photos ORDER BY family_id ASC, photo_order ASC, id ASC"
        ).fetchall():
            d = dict(r)
            photos_by_fam.setdefault(d["family_id"], []).append(d)

        members_by_fam: dict[int, list[dict[str, Any]]] = {}
        for r in conn.execute(
            "SELECT * FROM family_members ORDER BY family_id ASC, member_order ASC"
        ).fetchall():
            d = dict(r)
            members_by_fam.setdefault(d["family_id"], []).append(d)

        priests_by_fam: dict[int, list[dict[str, Any]]] = {}
        for r in conn.execute(
            "SELECT * FROM priests_religious ORDER BY family_id ASC, entry_order ASC"
        ).fetchall():
            d = dict(r)
            priests_by_fam.setdefault(d["family_id"], []).append(d)

        for fam in families:
            fam["photos"] = photos_by_fam.get(fam["id"], [])
            fam["members"] = members_by_fam.get(fam["id"], [])
            fam["priests"] = priests_by_fam.get(fam["id"], [])
        return families


def get_dashboard_stats(db_path: str | None = None) -> dict[str, Any]:
    """Compute summary statistics for the committee dashboard."""
    with get_connection(db_path) as conn:
        fam_row = conn.execute(
            """
            SELECT
                COUNT(*) AS total_families,
                SUM(CASE WHEN EXISTS (SELECT 1 FROM family_photos fp WHERE fp.family_id = families.id) THEN 1 ELSE 0 END) AS families_with_photos,
                SUM(CASE WHEN in_memoriam_page = 1 THEN 1 ELSE 0 END) AS in_memoriam_count,
                SUM(CASE WHEN family_greeting_page = 1 THEN 1 ELSE 0 END) AS greeting_count,
                SUM(CASE WHEN business_ad_page = 1 THEN 1 ELSE 0 END) AS business_ad_count,
                SUM(CASE WHEN verification_status = 'Verified' THEN 1 ELSE 0 END) AS verified_count
            FROM families
            """
        ).fetchone()
        photo_row = conn.execute("SELECT COUNT(*) AS total_photos FROM family_photos").fetchone()
        mem_row = conn.execute(
            """
            SELECT
                COUNT(*) AS total_members,
                SUM(CASE WHEN LOWER(resident_status) LIKE '%nri%' OR resident_status LIKE '%വിദേശ%' THEN 1 ELSE 0 END) AS nri_count
            FROM family_members
            """
        ).fetchone()
        priest_row = conn.execute("SELECT COUNT(*) AS total_priests FROM priests_religious").fetchone()
        wards = [
            dict(r)
            for r in conn.execute(
                "SELECT ward_unit, COUNT(*) AS count FROM families GROUP BY ward_unit ORDER BY ward_unit ASC"
            ).fetchall()
        ]
        return {
            "total_families": int(fam_row["total_families"] or 0),
            "photos_uploaded": int(photo_row["total_photos"] or 0),
            "families_with_photos": int(fam_row["families_with_photos"] or 0),
            "in_memoriam_count": int(fam_row["in_memoriam_count"] or 0),
            "greeting_count": int(fam_row["greeting_count"] or 0),
            "business_ad_count": int(fam_row["business_ad_count"] or 0),
            "verified_count": int(fam_row["verified_count"] or 0),
            "total_members": int(mem_row["total_members"] or 0),
            "nri_count": int(mem_row["nri_count"] or 0),
            "total_priests": int(priest_row["total_priests"] or 0),
            "wards": wards,
        }


def delete_family(family_id: int, db_path: str | None = None) -> dict[str, Any] | None:
    """Delete a family record and return it along with its photo records for file cleanup."""
    with get_connection(db_path) as conn:
        row = conn.execute("SELECT * FROM families WHERE id = ?", (family_id,)).fetchone()
        if not row:
            return None
        photos = [
            dict(r)
            for r in conn.execute(
                "SELECT * FROM family_photos WHERE family_id = ?", (family_id,)
            ).fetchall()
        ]
        conn.execute("DELETE FROM families WHERE id = ?", (family_id,))
        res = dict(row)
        res["photos"] = photos
        return res


def phone_owns_photo(
    whatsapp_phone: str, filename: str, db_path: str | None = None
) -> bool:
    """Check whether a photo or thumbnail filename belongs to the given phone's family."""
    clean_name = os.path.basename(filename or "")
    if not clean_name:
        return False
    family = get_family(whatsapp_phone=whatsapp_phone, db_path=db_path)
    if not family:
        return False
    for ph in family.get("photos", []):
        if clean_name in (ph.get("photo_filename"), ph.get("photo_thumb_filename")):
            return True
    return clean_name in (
        family.get("photo_filename"),
        family.get("photo_thumb_filename"),
    )


def refs_own_photo(
    reference_codes: list[str], filename: str, db_path: str | None = None
) -> bool:
    """Check whether a photo or thumbnail filename belongs to any of the given reference codes."""
    clean_name = os.path.basename(filename or "")
    refs = [r.strip() for r in (reference_codes or []) if r and r.strip()]
    if not clean_name or not refs:
        return False
    for ref in refs:
        family = get_family(reference_code=ref, db_path=db_path)
        if not family:
            continue
        for ph in family.get("photos", []):
            if clean_name in (ph.get("photo_filename"), ph.get("photo_thumb_filename")):
                return True
        if clean_name in (
            family.get("photo_filename"),
            family.get("photo_thumb_filename"),
        ):
            return True
    return False


# ------------------------------------------------------------------
# Reverse OTP Challenges
# ------------------------------------------------------------------


def _utc_now() -> datetime:
    return datetime.now(timezone.utc)


def create_otp_challenge(
    phone_number: str,
    otp_code: str,
    *,
    ttl_seconds: int = 600,
    ip_address: str = "",
    user_agent: str = "",
    db_path: str | None = None,
) -> dict[str, Any]:
    """Create a pending Reverse OTP challenge, superseding older pending challenges."""
    phone_norm = normalize_phone(phone_number)
    now_dt = _utc_now()
    now_iso = now_dt.isoformat(timespec="seconds")
    expires_iso = (now_dt + timedelta(seconds=ttl_seconds)).isoformat(timespec="seconds")
    challenge_id = uuid.uuid4().hex

    with get_connection(db_path) as conn:
        conn.execute(
            "UPDATE otp_challenges SET status = 'superseded' WHERE phone_number = ? AND status = 'pending'",
            (phone_norm,),
        )
        conn.execute(
            """
            INSERT INTO otp_challenges (
                challenge_id, phone_number, otp_code, status, expires_at,
                ip_address, user_agent, created_at
            ) VALUES (?, ?, ?, 'pending', ?, ?, ?, ?)
            """,
            (
                challenge_id,
                phone_norm,
                otp_code,
                expires_iso,
                ip_address,
                user_agent,
                now_iso,
            ),
        )
        row = conn.execute(
            "SELECT * FROM otp_challenges WHERE challenge_id = ?", (challenge_id,)
        ).fetchone()
        return dict(row)


def get_otp_challenge(
    challenge_id: str, db_path: str | None = None
) -> dict[str, Any] | None:
    """Fetch an OTP challenge, transitioning pending challenges past expiry to expired."""
    now_iso = _utc_now().isoformat(timespec="seconds")
    with get_connection(db_path) as conn:
        row = conn.execute(
            "SELECT * FROM otp_challenges WHERE challenge_id = ?", (challenge_id,)
        ).fetchone()
        if not row:
            return None
        challenge = dict(row)
        if challenge["status"] == "pending" and challenge["expires_at"] <= now_iso:
            conn.execute(
                "UPDATE otp_challenges SET status = 'expired' WHERE id = ?",
                (challenge["id"],),
            )
            challenge["status"] = "expired"
        return challenge


def _message_contains_otp(message_body: str, otp_code: str) -> bool:
    """Check whether an incoming WhatsApp message contains the expected Reverse OTP code."""
    body = (message_body or "").upper()
    code_upper = (otp_code or "").upper()
    if not body or not code_upper:
        return False
    compact_body = re.sub(r"[\s\-]+", "", body)
    compact_code = re.sub(r"[\s\-]+", "", code_upper)
    if compact_code in compact_body:
        return True
    digits = re.sub(r"\D", "", code_upper)
    if digits and re.search(rf"(?<!\d){re.escape(digits)}(?!\d)", body):
        return True
    return False


def verify_otp_challenge_from_whatsapp(
    sender_phone: str,
    message_body: str,
    *,
    db_path: str | None = None,
) -> dict[str, Any] | None:
    """Verify the latest matching pending OTP challenge when a WhatsApp message arrives."""
    phone_norm = normalize_webhook_sender(sender_phone)
    now_iso = _utc_now().isoformat(timespec="seconds")
    with get_connection(db_path) as conn:
        rows = conn.execute(
            """
            SELECT * FROM otp_challenges
            WHERE phone_number = ? AND status = 'pending' AND expires_at > ?
            ORDER BY id DESC
            """,
            (phone_norm, now_iso),
        ).fetchall()
        for row in rows:
            if _message_contains_otp(message_body, row["otp_code"]):
                conn.execute(
                    """
                    UPDATE otp_challenges
                    SET status = 'verified', verified_at = ?, sender_reported = ?
                    WHERE id = ?
                    """,
                    (now_iso, sender_phone, row["id"]),
                )
                updated = conn.execute(
                    "SELECT * FROM otp_challenges WHERE id = ?", (row["id"],)
                ).fetchone()
                return dict(updated)
    return None


def consume_otp_challenge(
    challenge_id: str, db_path: str | None = None
) -> dict[str, Any] | None:
    """Mark a verified, unexpired OTP challenge as consumed and return it."""
    now_iso = _utc_now().isoformat(timespec="seconds")
    with get_connection(db_path) as conn:
        row = conn.execute(
            "SELECT * FROM otp_challenges WHERE challenge_id = ?", (challenge_id,)
        ).fetchone()
        if not row or row["status"] != "verified" or row["expires_at"] <= now_iso:
            return None
        conn.execute(
            "UPDATE otp_challenges SET status = 'consumed', consumed_at = ? WHERE id = ?",
            (now_iso, row["id"]),
        )
        updated = conn.execute(
            "SELECT * FROM otp_challenges WHERE id = ?", (row["id"],)
        ).fetchone()
        return dict(updated)


# ------------------------------------------------------------------
# Activity Logs (Phone Users & Admin)
# ------------------------------------------------------------------


def log_phone_activity(
    phone_number: str,
    event_type: str,
    *,
    reference_code: str = "",
    details: str = "",
    ip_address: str = "",
    user_agent: str = "",
    db_path: str | None = None,
) -> None:
    """Record a phone user's login, logout, OTP, view, or submission event."""
    now_iso = _utc_now().isoformat(timespec="seconds")
    with get_connection(db_path) as conn:
        conn.execute(
            """
            INSERT INTO phone_activity_logs (
                phone_number, event_type, reference_code, details,
                ip_address, user_agent, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?)
            """,
            (
                phone_number,
                event_type,
                reference_code,
                details,
                ip_address,
                user_agent,
                now_iso,
            ),
        )


def log_admin_activity(
    action: str,
    *,
    target_type: str = "",
    target_id: str = "",
    details: str = "",
    ip_address: str = "",
    user_agent: str = "",
    db_path: str | None = None,
) -> None:
    """Record an administrative action in admin_activity_logs."""
    now_iso = _utc_now().isoformat(timespec="seconds")
    with get_connection(db_path) as conn:
        conn.execute(
            """
            INSERT INTO admin_activity_logs (
                action, target_type, target_id, details,
                ip_address, user_agent, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?)
            """,
            (
                action,
                target_type,
                str(target_id),
                details,
                ip_address,
                user_agent,
                now_iso,
            ),
        )


def list_phone_activity_logs(
    *,
    search: str = "",
    event_type: str = "",
    limit: int = 300,
    db_path: str | None = None,
) -> list[dict[str, Any]]:
    """Query phone activity logs ordered newest-first."""
    clauses = ["1=1"]
    params: list[Any] = []
    if search:
        like = f"%{search.strip()}%"
        clauses.append(
            "(phone_number LIKE ? OR reference_code LIKE ? OR details LIKE ? OR ip_address LIKE ?)"
        )
        params.extend([like, like, like, like])
    if event_type:
        clauses.append("event_type = ?")
        params.append(event_type)
    where_sql = " AND ".join(clauses)
    params.append(limit)
    with get_connection(db_path) as conn:
        rows = conn.execute(
            f"SELECT * FROM phone_activity_logs WHERE {where_sql} ORDER BY id DESC LIMIT ?",
            params,
        ).fetchall()
        return [dict(r) for r in rows]


def list_admin_activity_logs(
    *,
    search: str = "",
    action: str = "",
    limit: int = 300,
    db_path: str | None = None,
) -> list[dict[str, Any]]:
    """Query admin activity logs ordered newest-first."""
    clauses = ["1=1"]
    params: list[Any] = []
    if search:
        like = f"%{search.strip()}%"
        clauses.append(
            "(action LIKE ? OR target_type LIKE ? OR target_id LIKE ? OR details LIKE ? OR ip_address LIKE ?)"
        )
        params.extend([like, like, like, like, like])
    if action:
        clauses.append("action = ?")
        params.append(action)
    where_sql = " AND ".join(clauses)
    params.append(limit)
    with get_connection(db_path) as conn:
        rows = conn.execute(
            f"SELECT * FROM admin_activity_logs WHERE {where_sql} ORDER BY id DESC LIMIT ?",
            params,
        ).fetchall()
        return [dict(r) for r in rows]
