#!/usr/bin/env python3
"""
PL SMS Sync — capture iMessage/SMS from local Messages DB and upsert SMS_Message__c in Salesforce.
macOS menu bar app (rumps) with optional CLI for --test / --login.
"""

from __future__ import annotations

# ---------------------------------------------------------------------------
# SSL certificate fix for PyInstaller bundles.
# Bundled Python cannot find the system CA store.  We locate the certifi
# CA bundle and (a) set env vars for OpenSSL, (b) expose a helper that
# builds an explicit ssl.SSLContext for every urlopen() call.
# ---------------------------------------------------------------------------
import os as _os, sys as _sys, ssl as _ssl

_CACERT_PATH: str = ""  # resolved once at import time

def _resolve_cacert() -> str:
    """Find cacert.pem — try certifi module first, then bundle paths."""
    # 1. certifi package (most reliable, works inside PyInstaller PYZ)
    try:
        import certifi
        p = certifi.where()
        if _os.path.isfile(p):
            return p
    except Exception:
        pass
    # 2. PyInstaller _MEIPASS paths (Frameworks and Resources)
    if getattr(_sys, "frozen", False):
        meipass = getattr(_sys, "_MEIPASS", "")
        for candidate in [
            _os.path.join(meipass, "certifi", "cacert.pem"),
            _os.path.join(_os.path.dirname(_sys.executable), "..", "Resources", "certifi", "cacert.pem"),
            _os.path.join(_os.path.dirname(_sys.executable), "..", "Frameworks", "certifi", "cacert.pem"),
        ]:
            if _os.path.isfile(candidate):
                return _os.path.abspath(candidate)
    return ""

_CACERT_PATH = _resolve_cacert()
if _CACERT_PATH:
    _os.environ.setdefault("SSL_CERT_FILE", _CACERT_PATH)
    _os.environ.setdefault("REQUESTS_CA_BUNDLE", _CACERT_PATH)


def _ssl_ctx() -> _ssl.SSLContext:
    """Return an SSLContext that works on staff Macs (no system CA store)."""
    if _CACERT_PATH:
        return _ssl.create_default_context(cafile=_CACERT_PATH)
    return _ssl.create_default_context()

import argparse
import base64
import datetime as dt
import fcntl
import hashlib
import json
import logging
import os
import plistlib
import re
import secrets
import shutil
import sqlite3
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
import threading
import webbrowser
import socket
from http.server import BaseHTTPRequestHandler, HTTPServer
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union


# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------

APP_NAME = "PL SMS Sync"
APP_VERSION = "1.2.0"
UPDATE_BASE_URL = "https://pure.purelocations.com.au/pl-sms-sync"
KEYCHAIN_SERVICE = "au.com.purelocations.smssync"
KEYCHAIN_ACCOUNT = "PLSmsSync"
DEFAULT_SUPPORT_DIR = os.path.expanduser("~/Library/Application Support/PLSmsSync")
DEFAULT_CONFIG_PATH = os.path.join(DEFAULT_SUPPORT_DIR, "config.json")
DEFAULT_STATE_PATH = os.path.join(DEFAULT_SUPPORT_DIR, "state.json")
DEFAULT_LOCK_PATH = os.path.join(DEFAULT_SUPPORT_DIR, ".lock")
DEFAULT_INSTANCE_LOCK_PATH = os.path.join(DEFAULT_SUPPORT_DIR, ".instance.lock")
DEFAULT_LOG_PATH = os.path.expanduser("~/Library/Logs/pl-sms-sync.log")
MESSAGES_DB = os.path.expanduser("~/Library/Messages/chat.db")
APPLE_EPOCH = dt.datetime(2001, 1, 1, 0, 0, 0, tzinfo=dt.timezone.utc)
BRISBANE = dt.timezone(dt.timedelta(hours=10))  # Australia/Brisbane (no DST)
DESCRIPTION_MAX = 32000
PREVIEW_LEN = 40
COMPOSITE_BATCH = 200
NANO_THRESHOLD = 10**12

MESSAGE_C_MAX = 32768

# Only sync messages from the last N months on first sync / reset.
SYNC_WINDOW_MONTHS = 12

REQUIRED_SMS_MESSAGE_FIELDS = (
    "SMS_GUID__c",
    "Contact__c",
    "Direction__c",
    "Service__c",
    "Sent_At__c",
    "Message_Body__c",
    "Message__c",
    "Staff_Number__c",
    "Synced_By__c",
    "Phone_Number__c",
    "Destination__c",
)

SMS_OBJECT = "SMS_Message__c"

FDA_RETRY_INTERVAL = 30
FDA_SETUP_RETRY_INTERVAL = 15
FDA_SETTINGS_URLS = (
    "x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?Privacy_AllFiles",
    "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles",
)
FDA_ALERT_TITLE = "Messages Access Required"
FDA_ALERT_MESSAGE = (
    "PL SMS Sync needs access to your Messages to work.\n\n"
    "Click OK to open System Settings, then toggle PL SMS Sync ON in the Full Disk Access list."
)
WELCOME_ALERT_TITLE = "Welcome to PL SMS Sync"
WELCOME_ALERT_MESSAGE = (
    "This app syncs your iMessage and SMS conversations to Salesforce.\n\n"
    "You'll need to:\n"
    "1. Allow access to Messages\n"
    "2. Sign into Salesforce\n\n"
    "Let's get started!"
)

logger = logging.getLogger("pl_sms_sync")


class _DualStackHTTPServer(HTTPServer):
    """HTTPServer that listens on both IPv4 and IPv6 (dual-stack).

    macOS browsers may resolve ``localhost`` to either ``127.0.0.1`` (IPv4) or
    ``::1`` (IPv6).  The default HTTPServer only binds IPv4, so a callback from
    an IPv6 browser will silently fail.  This class binds an IPv6 socket with
    ``IPV6_V6ONLY=0`` so it accepts both address families.
    """

    address_family = socket.AF_INET6

    def server_bind(self) -> None:
        try:
            self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
        except (AttributeError, OSError) as exc:
            logger.debug("Dual-stack setsockopt failed (%s), falling back", exc)
        super().server_bind()


def is_frozen() -> bool:
    """True when running as a PyInstaller bundle (.app)."""
    return bool(getattr(sys, "frozen", False))


def application_executable() -> str:
    """Path to this program (.app bundle, binary, or script) for Full Disk Access."""
    if is_frozen():
        exe = os.path.abspath(sys.executable)
        # PyInstaller .app: .../PL SMS Sync.app/Contents/MacOS/PL SMS Sync
        parts = exe.split(os.sep)
        if "Contents" in parts:
            idx = parts.index("Contents")
            if idx > 0:
                return os.sep.join(parts[:idx])
        return exe
    return os.path.abspath(sys.argv[0] if sys.argv else __file__)


def full_disk_access_hint() -> str:
    """User-facing hint for macOS Full Disk Access settings."""
    if is_frozen():
        return f"Grant Full Disk Access to: {application_executable()}"
    exe = application_executable()
    if exe.endswith(".py"):
        return (
            "Grant Full Disk Access to the python3 binary used to run this tool "
            f"(or the installed pl-sms-sync binary). Script: {exe}"
        )
    return f"Grant Full Disk Access to: {exe}"


# ---------------------------------------------------------------------------
# Auto-update
# ---------------------------------------------------------------------------

def _current_arch() -> str:
    """Return 'arm64' or 'intel' matching the running binary."""
    import platform
    return "intel" if platform.machine() == "x86_64" else "arm64"


def check_for_update() -> Optional[Dict[str, Any]]:
    """Check UPDATE_BASE_URL/version.json for a newer version.

    Returns the parsed JSON dict if an update is available, None otherwise.
    """
    url = f"{UPDATE_BASE_URL}/version.json"
    try:
        ctx = _ssl_context()
        req = urllib.request.Request(url, method="GET")
        req.add_header("User-Agent", f"{APP_NAME}/{APP_VERSION}")
        with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
            info = json.loads(resp.read().decode("utf-8"))
        remote_version = info.get("version", "0.0.0")
        if _version_tuple(remote_version) > _version_tuple(APP_VERSION):
            return info
    except Exception as exc:
        logger.debug("Update check failed: %s", exc)
    return None


def _version_tuple(v: str) -> Tuple[int, ...]:
    """Parse '1.2.3' into (1, 2, 3) for comparison."""
    parts: List[int] = []
    for seg in v.split("."):
        try:
            parts.append(int(seg))
        except ValueError:
            parts.append(0)
    return tuple(parts)


def apply_update(info: Dict[str, Any]) -> bool:
    """Download the update zip, extract, and replace the running .app bundle.

    Returns True if the update was applied and a relaunch script was started.
    The caller should exit promptly.
    """
    if not is_frozen():
        logger.info("Auto-update skipped — not running as .app bundle")
        return False

    arch = _current_arch()
    zip_url = info.get(f"url_{arch}")
    if not zip_url:
        zip_url = f"{UPDATE_BASE_URL}/PL-SMS-Sync-{arch}.zip"
    version = info.get("version", "unknown")
    logger.info("Downloading update v%s from %s", version, zip_url)

    try:
        # Locate current .app bundle
        app_path = application_executable()  # e.g. /Applications/PL SMS Sync.app
        if not app_path.endswith(".app") or not os.path.isdir(app_path):
            logger.error("Cannot determine .app bundle path: %s", app_path)
            return False

        parent_dir = os.path.dirname(app_path)
        app_name = os.path.basename(app_path)

        # Download to temp file
        tmp_zip = os.path.join(tempfile.gettempdir(), "pl-sms-sync-update.zip")
        ctx = _ssl_context()
        req = urllib.request.Request(zip_url, method="GET")
        req.add_header("User-Agent", f"{APP_NAME}/{APP_VERSION}")
        with urllib.request.urlopen(req, timeout=120, context=ctx) as resp:
            with open(tmp_zip, "wb") as f:
                shutil.copyfileobj(resp, f)

        # Write a relaunch helper script
        # It waits for this process to exit, replaces the .app, and reopens it.
        relaunch_script = os.path.join(tempfile.gettempdir(), "pl-sms-sync-relaunch.sh")
        with open(relaunch_script, "w") as f:
            f.write(f"""#!/bin/bash
# PL SMS Sync auto-update relaunch script
sleep 2
# Remove old app
rm -rf {shutil.quote(app_path)}
# Extract using ditto (preserves code signing and macOS resource forks)
ditto -xk {shutil.quote(tmp_zip)} {shutil.quote(parent_dir)}
# Remove quarantine attribute (prevents Gatekeeper dialog on downloaded apps)
xattr -cr {shutil.quote(app_path)} 2>/dev/null
# Clean up
rm -f {shutil.quote(tmp_zip)}
# Relaunch
sleep 1
open {shutil.quote(app_path)}
rm -f {shutil.quote(relaunch_script)}
""")
        os.chmod(relaunch_script, 0o755)
        subprocess.Popen(["/bin/bash", relaunch_script])
        logger.info("Update v%s staged — relaunch script started", version)
        return True

    except Exception as exc:
        logger.error("Auto-update failed: %s", exc)
        return False


def login_item_app_path() -> str:
    """POSIX path to the .app bundle for Login Items."""
    if is_frozen():
        return application_executable()
    default = os.path.expanduser(f"~/Applications/{APP_NAME}.app")
    if os.path.isdir(default):
        return default
    return application_executable()


def login_item_enabled(app_path: Optional[str] = None) -> bool:
    """Return True if app_path is registered in macOS Login Items."""
    path = os.path.abspath(app_path or login_item_app_path())
    path_js = json.dumps(path)
    script = f"""
    tell application "System Events"
        repeat with L in login items
            try
                if (POSIX path of (path of L)) is equal to {path_js} then return "yes"
            end try
        end repeat
    end tell
    return "no"
    """
    try:
        r = subprocess.run(
            ["osascript", "-e", script],
            capture_output=True,
            text=True,
            timeout=30,
        )
        return r.returncode == 0 and r.stdout.strip() == "yes"
    except (OSError, subprocess.SubprocessError):
        return False


def set_login_item_enabled(
    enabled: bool,
    app_path: Optional[str] = None,
    *,
    hidden: bool = True,
) -> bool:
    """Add or remove this app from Login Items."""
    path = os.path.abspath(app_path or login_item_app_path())
    if enabled:
        if login_item_enabled(path):
            return True
        path_js = json.dumps(path)
        hidden_lit = "true" if hidden else "false"
        script = (
            f"tell application \"System Events\" to make login item at end "
            f"with properties {{path:POSIX file {path_js}, hidden:{hidden_lit}}}"
        )
    else:
        path_js = json.dumps(path)
        script = f"""
        tell application "System Events"
            repeat with L in login items
                try
                    if (POSIX path of (path of L)) is equal to {path_js} then delete L
                end try
            end repeat
        end tell
        """
    try:
        r = subprocess.run(
            ["osascript", "-e", script],
            capture_output=True,
            text=True,
            timeout=30,
        )
        if r.returncode != 0:
            logger.warning("Login item osascript failed: %s", (r.stderr or r.stdout).strip())
            return False
        return login_item_enabled(path) if enabled else not login_item_enabled(path)
    except (OSError, subprocess.SubprocessError) as e:
        logger.warning("Login item change failed: %s", e)
        return False


def open_full_disk_access_settings() -> None:
    """Open macOS System Settings to the Full Disk Access privacy pane."""
    for url in FDA_SETTINGS_URLS:
        try:
            r = subprocess.run(["open", url], capture_output=True, timeout=10)
            if r.returncode == 0:
                return
        except (OSError, subprocess.SubprocessError):
            continue
    subprocess.Popen(["open", FDA_SETTINGS_URLS[-1]])


# ---------------------------------------------------------------------------
# Logging (secure — no bodies, masked phones)
# ---------------------------------------------------------------------------


def mask_phone(e164: Optional[str]) -> str:
    """Mask E.164 for logs/reports: +61 4** *** 123."""
    if not e164:
        return "(unknown)"
    digits = re.sub(r"\D", "", e164)
    if len(digits) < 4:
        return "+** ***"
    last3 = digits[-3:]
    if digits.startswith("61") and len(digits) >= 11:
        # AU mobile roughly +61 4xx xxx xxx
        return f"+61 4** *** {last3}"
    cc = digits[: min(3, len(digits) - 3)]
    return f"+{cc[:2]}** *** {last3}"


def preview_text(text: str, n: int = PREVIEW_LEN) -> str:
    t = (text or "").replace("\n", " ").strip()
    if len(t) <= n:
        return t
    return t[: n - 1] + "…"


class SecureLogFilter(logging.Filter):
    def filter(self, record: logging.LogRecord) -> bool:
        msg = record.getMessage()
        # Redact likely E.164 in logs
        record.msg = re.sub(r"\+\d{8,15}", lambda m: mask_phone(m.group(0)), msg)
        record.args = ()
        return True


def setup_logging(log_path: Optional[str] = None, verbose: bool = False) -> None:
    from logging.handlers import RotatingFileHandler

    level = logging.DEBUG if verbose else logging.INFO
    handlers: List[logging.Handler] = [logging.StreamHandler(sys.stderr)]
    if log_path:
        os.makedirs(os.path.dirname(log_path), exist_ok=True)
        handlers.append(RotatingFileHandler(
            log_path, maxBytes=5 * 1024 * 1024, backupCount=3, encoding="utf-8",
        ))
    logging.basicConfig(
        level=level,
        format="%(asctime)s %(levelname)s %(message)s",
        handlers=handlers,
        force=True,
    )
    for h in handlers:
        h.addFilter(SecureLogFilter())


def notify_macos(title: str, message: str) -> None:
    try:
        script = f'display notification {json.dumps(message)} with title {json.dumps(title)}'
        subprocess.run(
            ["osascript", "-e", script],
            check=False,
            capture_output=True,
            timeout=10,
        )
    except (OSError, subprocess.SubprocessError):
        pass


# ---------------------------------------------------------------------------
# Phone normalisation (E.164, AU focus)
# ---------------------------------------------------------------------------


def normalize_phone_e164(raw: Optional[str], default_region: str = "AU") -> Optional[str]:
    """
    Normalise a phone handle to E.164. Australian numbers are mapped to +61...
    Returns None if not a plausible phone number.
    """
    if raw is None:
        return None
    s = str(raw).strip()
    if not s or "@" in s:
        return None
    # Strip common formatting
    s = re.sub(r"^tel:", "", s, flags=re.I)
    s = re.sub(r"[\s\-\(\)\.]", "", s)
    if s.startswith("00"):
        s = "+" + s[2:]
    if not s.startswith("+"):
        digits = re.sub(r"\D", "", s)
        if not digits:
            return None
        if default_region == "AU":
            if digits.startswith("61"):
                s = "+" + digits
            elif digits.startswith("0"):
                s = "+61" + digits[1:]
            elif len(digits) == 9 and digits[0] in "2345678":
                s = "+61" + digits
            elif len(digits) >= 10:
                s = "+" + digits
            else:
                s = "+61" + digits
        else:
            s = "+" + digits
    else:
        s = "+" + re.sub(r"\D", "", s[1:])

    digits = s[1:]

    # Fix common AU data-entry mistake: +610412... → +61412...
    # A leading 0 after country code 61 is redundant.
    if default_region == "AU" and digits.startswith("610") and len(digits) == 12:
        digits = "61" + digits[3:]

    if len(digits) < 8 or len(digits) > 15:
        return None
    if default_region == "AU" and digits.startswith("61"):
        if len(digits) not in (11, 12):  # +61 9-10 digits after country code
            if len(digits) == 10 and digits.startswith("61"):
                pass
            elif not (11 <= len(digits) <= 12):
                return None
    return "+" + digits


def is_email_handle(handle: str) -> bool:
    return "@" in handle and "." in handle.split("@")[-1]


# ---------------------------------------------------------------------------
# Apple timestamps
# ---------------------------------------------------------------------------


def apple_timestamp_to_utc(value: Union[int, float, None]) -> Optional[dt.datetime]:
    """Convert Messages date column (seconds or nanoseconds since 2001-01-01 UTC)."""
    if value is None:
        return None
    try:
        v = int(value)
    except (TypeError, ValueError):
        return None
    if v == 0:
        return None
    if abs(v) > NANO_THRESHOLD:
        seconds = v / 1_000_000_000.0
    else:
        seconds = float(v)
    return APPLE_EPOCH + dt.timedelta(seconds=seconds)


def utc_to_brisbane(when: dt.datetime) -> dt.datetime:
    if when.tzinfo is None:
        when = when.replace(tzinfo=dt.timezone.utc)
    return when.astimezone(BRISBANE)


def format_sf_datetime(when: dt.datetime) -> str:
    if when.tzinfo is None:
        when = when.replace(tzinfo=dt.timezone.utc)
    return when.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000+0000")


# ---------------------------------------------------------------------------
# attributedBody extraction
# ---------------------------------------------------------------------------


_OBJC_METADATA = frozenset({
    "NSString", "NSMutableString", "NSAttributedString",
    "NSMutableAttributedString", "NSDictionary", "NSMutableDictionary",
    "NSArray", "NSMutableArray", "NSNumber", "NSValue", "NSData",
    "NSMutableData", "NSDate", "NSObject", "NSParagraphStyle",
    "NSMutableParagraphStyle", "NSFont", "NSColor", "NSKeyedArchiver",
    "streamtyped", "typedstream",
})


def _is_objc_metadata(s: str) -> bool:
    """True when *s* is an Obj-C class name or NSKeyedArchiver key, not message text."""
    if not s:
        return True
    if s in _OBJC_METADATA:
        return True
    # NSKeyedArchiver keys: $archiver, $objects, $class, $top, etc.
    if s.startswith("$"):
        return True
    return False


def _extract_via_nsunarchiver(blob: bytes) -> Optional[str]:
    """Use Apple's NSUnarchiver to decode typedstream attributedBody blobs.

    This is the same decoder macOS Messages uses internally — it handles
    all encoding formats, emoji, attributed text, and edge cases perfectly.
    """
    try:
        from Foundation import NSUnarchiver, NSData
        data = NSData.dataWithBytes_length_(blob, len(blob))
        obj = NSUnarchiver.unarchiveObjectWithData_(data)
        if obj is not None and hasattr(obj, "string"):
            text = str(obj.string())
            if text:
                return text
    except Exception:
        pass
    return None


def extract_attributed_body(blob: Optional[bytes]) -> Optional[str]:
    """Extract plain text from Messages attributedBody blob.

    Primary path: Apple's own NSUnarchiver (perfect for typedstream format).
    Fallback: manual binary parsing for edge cases or non-macOS environments.
    """
    if blob is None:
        return None
    if isinstance(blob, str):
        return blob or None
    if not blob:
        return None

    # Already UTF-8 text in some rows (not binary archives)
    try:
        text = blob.decode("utf-8")
        if text and not text.startswith("\x04") and not text.lstrip().startswith("<?xml"):
            if "NSString" not in text[:80]:
                stripped = text.strip()
                if stripped and sum(c.isprintable() or c in "\n\r\t" for c in stripped) > len(stripped) * 0.9:
                    return stripped
    except UnicodeDecodeError:
        pass

    # ── Primary: Apple's NSUnarchiver (handles typedstream perfectly) ──
    result = _extract_via_nsunarchiver(blob)
    if result:
        return result

    # ── Fallback: manual binary parsing ──
    # Binary plist fragments
    for match in re.finditer(rb"bplist0[0-9]", blob):
        start = match.start()
        candidates = [len(blob)]
        for next_match in re.finditer(rb"bplist0[0-9]", blob[start + 8:]):
            candidates.append(start + 8 + next_match.start())
        for end in candidates:
            if end <= start + 8:
                continue
            try:
                pl = plistlib.loads(blob[start:end])
                found = _plist_find_string(pl)
                if found:
                    return found
            except (plistlib.InvalidFileException, ValueError, OSError):
                continue

    # NSString marker + length-prefixed string
    for marker in (b"NSMutableString", b"NSString"):
        idx = blob.find(marker)
        if idx >= 0:
            pos = idx + len(marker)
            extracted = _read_length_prefixed_string(blob, pos)
            tail = blob[idx + len(marker) :]
            runs = _extract_text_runs(tail)
            runs = [r for r in runs if not _is_objc_metadata(r)]
            best_run = max(runs, key=len) if runs else None

            if extracted and not _is_objc_metadata(extracted):
                if best_run and len(best_run) > len(extracted) * 1.5 + 5:
                    return best_run
                return extracted
            if best_run:
                return best_run

    # Raw UTF-8 run scan (last resort)
    strings = _extract_text_runs(blob)
    if strings:
        candidates = [s for s in strings if not _is_objc_metadata(s) and len(s) >= 1]
        if candidates:
            return max(candidates, key=len)

    return None


def _decode_ber_length(data: bytes, pos: int) -> Tuple[int, int]:
    """Decode a BER-style length at *pos*.

    Apple's typedstream / NSKeyedArchiver uses:
      0x00–0x7E  → length is the byte itself; data starts at pos + 1
      0x81       → length is the next 1 byte;  data starts at pos + 2
      0x82       → length is the next 2 bytes (big-endian); data starts at pos + 3
      0x83       → length is the next 3 bytes; data starts at pos + 4
      0x84       → length is the next 4 bytes; data starts at pos + 5

    Returns (string_length, data_start_offset).
    Returns (-1, pos) on failure.
    """
    if pos >= len(data):
        return (-1, pos)
    first = data[pos]
    if first <= 0x7E:
        return (first, pos + 1)
    if first == 0x81 and pos + 2 <= len(data):
        return (data[pos + 1], pos + 2)
    if first == 0x82 and pos + 3 <= len(data):
        return (int.from_bytes(data[pos + 1 : pos + 3], "big"), pos + 3)
    if first == 0x83 and pos + 4 <= len(data):
        return (int.from_bytes(data[pos + 1 : pos + 4], "big"), pos + 4)
    if first == 0x84 and pos + 5 <= len(data):
        return (int.from_bytes(data[pos + 1 : pos + 5], "big"), pos + 5)
    return (-1, pos)


def _looks_like_utf16(chunk: bytes) -> bool:
    """Heuristic: True if chunk looks like UTF-16 encoded Latin/emoji text.

    Checks for null-byte patterns typical of ASCII-range characters in UTF-16
    (every other byte is 0x00).  Rejects data that decodes to mostly CJK or
    other non-Latin scripts — PL conversations are English-only.
    """
    if len(chunk) < 4 or len(chunk) % 2 != 0:
        return False
    # Count null bytes in even/odd positions — UTF-16 Latin text has
    # nulls in either the high byte (BE) or low byte (LE) positions
    nulls_even = sum(1 for i in range(0, len(chunk), 2) if chunk[i] == 0)
    nulls_odd = sum(1 for i in range(1, len(chunk), 2) if chunk[i] == 0)
    pairs = len(chunk) // 2
    # At least 30% of bytes in one position should be null (Latin text)
    return nulls_even > pairs * 0.3 or nulls_odd > pairs * 0.3


def _is_latin_text(text: str) -> bool:
    """True if text is predominantly Latin-script / ASCII (not CJK noise)."""
    if not text:
        return False
    latin = sum(1 for c in text if c.isascii() or c in "😀🙂👍❤️🎉✅")
    return latin >= len(text) * 0.4


def _try_decode_text(chunk: bytes) -> str:
    """Try decoding a byte chunk as UTF-8, then UTF-16 (with and without BOM).

    Apple's typedstream / NSKeyedArchiver uses UTF-8 for ASCII-only strings
    and UTF-16 for strings containing emoji or non-Latin text.
    UTF-16 is only attempted when the byte pattern looks plausible (null-byte
    interleaving), to avoid decoding random binary data as CJK characters.
    """
    # UTF-8 first (most common)
    try:
        return chunk.decode("utf-8")
    except UnicodeDecodeError:
        pass
    # UTF-16 with BOM (explicit encoding marker)
    if len(chunk) >= 2 and chunk[:2] in (b"\xff\xfe", b"\xfe\xff"):
        try:
            text = chunk.decode("utf-16")
            if _is_latin_text(text):
                return text
        except (UnicodeDecodeError, ValueError):
            pass
    # Only try UTF-16BE/LE if the byte pattern looks like encoded Latin text
    if _looks_like_utf16(chunk):
        for encoding in ("utf-16-be", "utf-16-le"):
            try:
                text = chunk.decode(encoding)
                if text and _is_latin_text(text):
                    return text
            except (UnicodeDecodeError, ValueError):
                continue
    return ""


def _read_length_prefixed_string(data: bytes, start: int) -> Optional[str]:
    """Read length-prefixed strings (UTF-8 or UTF-16) from typedstream data."""
    pos = start
    best: Optional[str] = None
    for _ in range(24):
        if pos >= len(data):
            break
        ln, data_start = _decode_ber_length(data, pos)
        if 1 <= ln <= 64_000 and data_start + ln <= len(data):
            chunk = data[data_start : data_start + ln]
            text = _try_decode_text(chunk)
            if text and not _is_objc_metadata(text):
                if sum(c.isprintable() or c in "\n\r\t" for c in text) >= max(1, len(text) // 2):
                    if best is None or len(text) > len(best):
                        best = text
            if ln > 0 and data_start + ln > pos:
                pos = data_start + ln
                continue
        if data[pos] in (0xFF, 0xFE, 0x07) or data[pos] < 0x09:
            pos += 1
            continue
        pos += 1
    return best


def _plist_find_string(obj: Any) -> Optional[str]:
    """Walk a plist object tree to find the first real message string.

    Skips Objective-C class names and NSKeyedArchiver metadata keys that
    appear as string values in the ``$objects`` array.
    """
    stack = [obj]
    while stack:
        item = stack.pop()
        if isinstance(item, str):
            if not _is_objc_metadata(item):
                return item
        if isinstance(item, dict):
            stack.extend(item.values())
        elif isinstance(item, (list, tuple)):
            stack.extend(item)
    return None


def _extract_text_runs(data: bytes, min_len: int = 1, max_scan: int = 64_000) -> List[str]:
    """Extract printable UTF-8 text runs from binary data.

    Scans at most *max_scan* bytes.  Only extracts UTF-8 runs — UTF-16
    decoding is handled by ``_try_decode_text`` in the length-prefixed
    reader where exact byte boundaries are known.  Raw UTF-16 scanning
    over binary data produces false positives (random bytes decode as
    CJK characters).
    """
    scan = data[:max_scan] if len(data) > max_scan else data
    results: List[str] = []
    i = 0
    while i < len(scan):
        if scan[i] < 0x20 and scan[i] not in (0x09, 0x0A, 0x0D):
            i += 1
            continue
        start = i
        while i < len(scan) and (scan[i] >= 0x20 or scan[i] in (0x09, 0x0A, 0x0D)):
            i += 1
        chunk = scan[start:i]
        try:
            s = chunk.decode("utf-8")
        except UnicodeDecodeError:
            try:
                s = chunk.decode("utf-8", errors="ignore")
            except Exception:
                continue
        s = s.strip()
        if len(s) >= min_len:
            results.append(s)
    return results


# ---------------------------------------------------------------------------
# Strict contact matching
# ---------------------------------------------------------------------------


MatchResult = Tuple[str, List[str]]  # status: none|one|ambiguous, contact ids


class ContactIndex:
    """Pre-built lookup indexes for O(1) contact matching.

    Built once per sync from the contacts list.  Avoids calling
    normalize_phone_e164 on every contact for every message.
    """

    __slots__ = ("_phone_index", "_email_index", "_by_id")

    def __init__(self, contacts: Sequence[Dict[str, Any]]) -> None:
        self._by_id: Dict[str, Dict[str, Any]] = {}
        self._phone_index: Dict[str, List[str]] = {}
        self._email_index: Dict[str, List[str]] = {}
        for c in contacts:
            cid = c["Id"]
            self._by_id[cid] = c
            # Phone keys
            pk = c.get("SMS_Phone_Key__c")
            if pk:
                self._phone_index.setdefault(str(pk).strip(), []).append(cid)
            for field in ("MobilePhone", "Phone"):
                ph = normalize_phone_e164(c.get(field))
                if ph:
                    self._phone_index.setdefault(ph, []).append(cid)
            # Email key
            email = (c.get("Email") or "").strip().lower()
            if email:
                self._email_index.setdefault(email, []).append(cid)
        # Dedupe
        for idx in (self._phone_index, self._email_index):
            for k in idx:
                idx[k] = list(dict.fromkeys(idx[k]))

    def match(self, handle: str) -> MatchResult:
        """Match a message handle to contacts. O(1) lookup."""
        if is_email_handle(handle):
            ids = self._email_index.get(handle.strip().lower(), [])
        else:
            key = normalize_phone_e164(handle)
            if not key:
                return "none", []
            ids = self._phone_index.get(key, [])
        if len(ids) == 0:
            return "none", []
        if len(ids) == 1:
            return "one", ids
        return "ambiguous", ids

    def get(self, contact_id: str) -> Dict[str, Any]:
        return self._by_id.get(contact_id, {"Id": contact_id})


class StaffExclusionIndex:
    """Pre-built set of normalised phone numbers and emails for internal PL
    staff, used to skip internal comms during sync."""

    __slots__ = ("_phones", "_emails", "_count")

    def __init__(self, users: Sequence[Dict[str, Any]]) -> None:
        self._phones: set = set()
        self._emails: set = set()
        self._count = 0
        for u in users:
            self._count += 1
            for field in ("MobilePhone", "Phone"):
                raw = (u.get(field) or "").strip()
                if raw:
                    normed = normalize_phone_e164(raw)
                    if normed:
                        self._phones.add(normed)
            email = (u.get("Email") or "").strip().lower()
            if email:
                self._emails.add(email)

    def is_internal(self, handle: str) -> bool:
        """Return True if the handle belongs to a PL staff member."""
        if not handle:
            return False
        if is_email_handle(handle):
            return handle.strip().lower() in self._emails
        normed = normalize_phone_e164(handle)
        return normed in self._phones if normed else False

    def __len__(self) -> int:
        return self._count


# ---------------------------------------------------------------------------
# Keychain
# ---------------------------------------------------------------------------


def keychain_store(token_json: str) -> None:
    subprocess.run(
        [
            "security",
            "add-generic-password",
            "-a",
            KEYCHAIN_ACCOUNT,
            "-s",
            KEYCHAIN_SERVICE,
            "-w",
            token_json,
            "-U",
        ],
        check=True,
        capture_output=True,
    )


def keychain_load() -> Optional[str]:
    try:
        r = subprocess.run(
            [
                "security",
                "find-generic-password",
                "-a",
                KEYCHAIN_ACCOUNT,
                "-s",
                KEYCHAIN_SERVICE,
                "-w",
            ],
            check=True,
            capture_output=True,
            text=True,
        )
        return r.stdout.strip()
    except subprocess.CalledProcessError:
        return None


def keychain_delete() -> None:
    subprocess.run(
        ["security", "delete-generic-password", "-a", KEYCHAIN_ACCOUNT, "-s", KEYCHAIN_SERVICE],
        capture_output=True,
    )


# ---------------------------------------------------------------------------
# OAuth PKCE
# ---------------------------------------------------------------------------


def pkce_pair() -> Tuple[str, str]:
    verifier = base64.urlsafe_b64encode(secrets.token_bytes(32)).decode("ascii").rstrip("=")
    challenge = (
        base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest())
        .decode("ascii")
        .rstrip("=")
    )
    return verifier, challenge


class _OAuthCallbackHandler(BaseHTTPRequestHandler):
    auth_code: Optional[str] = None
    error: Optional[str] = None

    def log_message(self, fmt: str, *args: Any) -> None:
        pass

    def do_GET(self) -> None:
        parsed = urllib.parse.urlparse(self.path)
        if parsed.path != "/callback":
            logger.debug("OAuth server: ignoring request to %s", parsed.path)
            self.send_response(404)
            self.end_headers()
            return
        qs = urllib.parse.parse_qs(parsed.query)
        logger.info("OAuth callback received: path=%s code=%s error=%s",
                     parsed.path, "yes" if qs.get("code") else "no",
                     qs.get("error", ["none"])[0])
        if "error" in qs:
            error_desc = qs.get("error_description", [qs["error"][0]])[0]
            _OAuthCallbackHandler.error = error_desc
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.end_headers()
            self.wfile.write(f"<html><body><h1>Sign-in failed</h1><p>{error_desc}</p></body></html>".encode())
        elif "code" in qs:
            _OAuthCallbackHandler.auth_code = qs["code"][0]
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.end_headers()
            self.wfile.write(b"<html><body><h1>Salesforce sign-in complete.</h1>You can close this window.</body></html>")
        else:
            logger.warning("OAuth callback with no code and no error: qs=%s", qs)
            self.send_response(400)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.end_headers()
            self.wfile.write(b"<html><body><h1>Unexpected callback</h1><p>No authorization code received.</p></body></html>")


def _ask_for_url_via_osascript() -> Optional[str]:
    """Show a macOS dialog asking the user to paste a URL. Safe to call from any thread."""
    try:
        r = subprocess.run(
            ["osascript", "-e",
             'display dialog "The browser callback didn\'t reach the app.\\n\\n'
             'Please copy the FULL URL from your browser\'s address bar '
             '(it starts with http://localhost...) and paste it below:" '
             'default answer "" with title "PL SMS Sync — Paste Browser URL" '
             'buttons {"Cancel", "OK"} default button "OK"'],
            capture_output=True, text=True, timeout=300
        )
        if r.returncode != 0:
            return None
        output = r.stdout.strip()
        # osascript output: "button returned:OK, text returned:<url>"
        for part in output.split(", "):
            if part.startswith("text returned:"):
                return part[len("text returned:"):].strip()
        return None
    except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
        logger.error("osascript dialog failed: %s", e)
        return None


def _parse_auth_code_from_url(url: str) -> Tuple[Optional[str], Optional[str]]:
    """Extract auth code or error from a callback URL. Returns (code, error)."""
    parsed = urllib.parse.urlparse(url)
    qs = urllib.parse.parse_qs(parsed.query)
    if "code" in qs:
        return (qs["code"][0], None)
    if "error" in qs:
        desc = qs.get("error_description", qs["error"])[0]
        return (None, desc)
    # Check URL fragment too
    fqs = urllib.parse.parse_qs(parsed.fragment)
    if "code" in fqs:
        return (fqs["code"][0], None)
    return (None, None)


def oauth_login(config: Dict[str, Any]) -> Dict[str, Any]:
    login_domain = config["login_domain"].rstrip("/")
    client_id = config["consumer_key"]
    port = int(config.get("redirect_port", 8476))
    redirect_uri = f"http://localhost:{port}/callback"
    verifier, challenge = pkce_pair()

    params = {
        "response_type": "code",
        "client_id": client_id,
        "redirect_uri": redirect_uri,
        "scope": "api refresh_token",
        "code_challenge": challenge,
        "code_challenge_method": "S256",
    }
    auth_url = f"{login_domain}/services/oauth2/authorize?" + urllib.parse.urlencode(params)

    # ---- Step 1: Start callback server and open browser ----
    _OAuthCallbackHandler.auth_code = None
    _OAuthCallbackHandler.error = None
    server: Optional[HTTPServer] = None
    try:
        server = _DualStackHTTPServer(("::", port), _OAuthCallbackHandler)
        server.timeout = 1
        logger.info("OAuth: dual-stack callback server listening on port %d (IPv4+IPv6)", port)
    except OSError:
        try:
            server = HTTPServer(("", port), _OAuthCallbackHandler)
            server.timeout = 1
            logger.info("OAuth: IPv4-only callback server listening on port %d", port)
        except OSError as e:
            logger.warning("OAuth: cannot bind port %d: %s", port, e)

    webbrowser.open(auth_url)
    logger.info("OAuth: browser opened, waiting for callback (30s)...")

    # ---- Step 2: Wait up to 30 seconds for automatic callback ----
    auth_code: Optional[str] = None
    error: Optional[str] = None

    if server is not None:
        deadline = time.time() + 30
        while time.time() < deadline and _OAuthCallbackHandler.auth_code is None and _OAuthCallbackHandler.error is None:
            server.handle_request()
        server.server_close()
        auth_code = _OAuthCallbackHandler.auth_code
        error = _OAuthCallbackHandler.error
        if auth_code:
            logger.info("OAuth: auto callback received auth code")
        elif error:
            logger.info("OAuth: auto callback received error: %s", error)
        else:
            logger.warning("OAuth: no callback received after 30s")

    # ---- Step 3: If no callback, ask user to paste the URL ----
    if not auth_code and not error:
        logger.info("OAuth: showing manual URL paste dialog")
        pasted = _ask_for_url_via_osascript()
        if pasted:
            logger.info("OAuth: user pasted URL: %s", pasted[:100])
            auth_code, error = _parse_auth_code_from_url(pasted)
            if not auth_code and not error:
                raise RuntimeError(
                    f"No authorization code found in the URL you pasted.\n"
                    f"URL: {pasted[:200]}\n\n"
                    f"Expected a URL like: http://localhost:{port}/callback?code=..."
                )
        else:
            raise RuntimeError(
                "Sign-in cancelled. If the browser showed an error page, "
                "try closing all browser tabs and signing in again."
            )

    if error:
        raise RuntimeError(f"Salesforce denied access: {error}")
    if not auth_code:
        raise RuntimeError("No authorization code received.")

    # ---- Step 4: Exchange code for tokens ----
    logger.info("OAuth: exchanging auth code for tokens at %s", login_domain)
    token_url = f"{login_domain}/services/oauth2/token"
    body = urllib.parse.urlencode(
        {
            "grant_type": "authorization_code",
            "code": auth_code,
            "client_id": client_id,
            "redirect_uri": redirect_uri,
            "code_verifier": verifier,
        }
    ).encode("utf-8")
    req = urllib.request.Request(token_url, data=body, method="POST")
    req.add_header("Content-Type", "application/x-www-form-urlencoded")
    try:
        with urllib.request.urlopen(req, timeout=60, context=_ssl_ctx()) as resp:
            tokens = json.loads(resp.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        error_body = e.read().decode("utf-8", errors="replace")
        logger.error("OAuth token exchange failed: HTTP %d: %s", e.code, error_body)
        raise RuntimeError(f"Salesforce token exchange failed (HTTP {e.code}): {error_body}") from e
    except urllib.error.URLError as e:
        logger.error("OAuth token exchange network error: %s", e.reason)
        raise RuntimeError(f"Cannot reach Salesforce for token exchange: {e.reason}") from e

    logger.info("OAuth: token exchange successful, instance=%s", tokens.get("instance_url", "?"))
    tokens["login_domain"] = login_domain
    tokens["issued_at"] = time.time()
    return tokens


class TokenRefreshFailed(Exception):
    """Raised when the refresh token is invalid/expired and re-login is needed."""
    pass


def token_refresh(config: Dict[str, Any], stored: Dict[str, Any]) -> Dict[str, Any]:
    login_domain = stored.get("login_domain") or config["login_domain"].rstrip("/")
    token_url = f"{login_domain}/services/oauth2/token"
    body = urllib.parse.urlencode(
        {
            "grant_type": "refresh_token",
            "refresh_token": stored["refresh_token"],
            "client_id": config["consumer_key"],
        }
    ).encode("utf-8")
    req = urllib.request.Request(token_url, data=body, method="POST")
    req.add_header("Content-Type", "application/x-www-form-urlencoded")
    try:
        with urllib.request.urlopen(req, timeout=60, context=_ssl_ctx()) as resp:
            fresh = json.loads(resp.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        error_body = e.read().decode("utf-8", errors="replace")
        logger.error("Token refresh failed: HTTP %d: %s", e.code, error_body)
        keychain_delete()
        raise TokenRefreshFailed(
            f"Salesforce session expired (HTTP {e.code}). Please sign in again."
        ) from e
    except urllib.error.URLError as e:
        logger.error("Token refresh network error: %s", e.reason)
        raise TokenRefreshFailed(
            f"Cannot reach Salesforce to refresh session: {e.reason}"
        ) from e
    stored["access_token"] = fresh["access_token"]
    stored["instance_url"] = fresh.get("instance_url", stored.get("instance_url"))
    stored["issued_at"] = time.time()
    if fresh.get("refresh_token"):
        stored["refresh_token"] = fresh["refresh_token"]
    return stored


# ---------------------------------------------------------------------------
# Salesforce REST
# ---------------------------------------------------------------------------


class SalesforceClient:
    def __init__(self, config: Dict[str, Any], tokens: Dict[str, Any]):
        self.config = config
        self.tokens = tokens
        self.api_version = config.get("api_version", "v59.0")
        self.instance_url = tokens["instance_url"].rstrip("/")

    def _headers(self) -> Dict[str, str]:
        return {
            "Authorization": f"Bearer {self.tokens['access_token']}",
            "Content-Type": "application/json",
        }

    def request(
        self,
        method: str,
        path: str,
        body: Optional[Union[dict, list]] = None,
        retry_auth: bool = True,
    ) -> Tuple[int, Any]:
        url = f"{self.instance_url}{path}"
        data = None if body is None else json.dumps(body).encode("utf-8")
        req = urllib.request.Request(url, data=data, method=method, headers=self._headers())
        try:
            with urllib.request.urlopen(req, timeout=120, context=_ssl_ctx()) as resp:
                raw = resp.read().decode("utf-8")
                return resp.status, json.loads(raw) if raw else {}
        except urllib.error.HTTPError as e:
            status = e.code
            raw = e.read().decode("utf-8", errors="replace")
            try:
                payload = json.loads(raw) if raw else []
            except json.JSONDecodeError:
                payload = {"message": raw}
            if status == 401 and retry_auth:
                try:
                    self.tokens = token_refresh(self.config, self.tokens)
                    keychain_store(json.dumps(self.tokens))
                    return self.request(method, path, body, retry_auth=False)
                except TokenRefreshFailed:
                    raise
            if status in (403, 429):
                codes = []
                if isinstance(payload, list):
                    codes = [p.get("errorCode") for p in payload if isinstance(p, dict)]
                elif isinstance(payload, dict):
                    codes = [payload.get("errorCode")]
                if "REQUEST_LIMIT_EXCEEDED" in codes or status == 429:
                    raise ApiLimitExceeded(status, payload)
            return status, payload

    def describe_sms_message(self) -> Dict[str, Any]:
        _, data = self.request(
            "GET",
            f"/services/data/{self.api_version}/sobjects/{SMS_OBJECT}/describe/",
        )
        return data

    def query_contacts(self, e164_keys: Sequence[str]) -> List[Dict[str, Any]]:
        if not e164_keys:
            return []
        # Chunk IN clauses
        all_rows: List[Dict[str, Any]] = []
        keys = list(dict.fromkeys(e164_keys))
        for i in range(0, len(keys), 100):
            chunk = keys[i : i + 100]
            in_list = ",".join("'" + k.replace("'", "\\'") + "'" for k in chunk)
            soql = (
                "SELECT Id, AccountId, Phone, MobilePhone, Email, SMS_Phone_Key__c "
                f"FROM Contact WHERE SMS_Phone_Key__c IN ({in_list})"
            )
            path = "/services/data/" + self.api_version + "/query?q=" + urllib.parse.quote(soql)
            status, data = self.request("GET", path)
            if status != 200 or not isinstance(data, dict):
                return []
            all_rows.extend(data.get("records", []))
        return all_rows

    def query_contacts_fallback(self) -> List[Dict[str, Any]]:
        soql = "SELECT Id, AccountId, Phone, MobilePhone, Email, SMS_Phone_Key__c FROM Contact WHERE Phone != NULL OR MobilePhone != NULL OR Email != NULL"
        path = "/services/data/" + self.api_version + "/query?q=" + urllib.parse.quote(soql)
        records: List[Dict[str, Any]] = []
        while path:
            status, data = self.request("GET", path)
            if status != 200 or not isinstance(data, dict):
                break
            records.extend(data.get("records", []))
            next_url = data.get("nextRecordsUrl")
            path = next_url if next_url else None
        return records

    def query_user_id(self) -> str:
        _, data = self.request("GET", f"/services/data/{self.api_version}/chatter/users/me")
        return data.get("id") or data.get("Id") or ""

    def query_internal_staff(self) -> List[Dict[str, Any]]:
        """Fetch phone numbers and emails for internal PL staff.

        Sources from Contacts under the 'Pure Locations Pty Ltd' Account,
        which is the most complete list of staff with correct phone numbers.
        """
        soql = (
            "SELECT Id, MobilePhone, Phone, Email "
            "FROM Contact "
            "WHERE Account.Name = 'Pure Locations Pty Ltd'"
        )
        path = "/services/data/" + self.api_version + "/query?q=" + urllib.parse.quote(soql)
        records: List[Dict[str, Any]] = []
        while path:
            status, data = self.request("GET", path)
            if status != 200 or not isinstance(data, dict):
                break
            records.extend(data.get("records", []))
            next_url = data.get("nextRecordsUrl")
            path = next_url if next_url else None
        return records

    def composite_upsert_sms_messages(self, records: List[Dict[str, Any]]) -> Dict[str, Any]:
        path = (
            f"/services/data/{self.api_version}/composite/sobjects/"
            f"{SMS_OBJECT}/SMS_GUID__c"
        )
        body = {"allOrNone": False, "records": records}
        status, data = self.request("PATCH", path, body)
        return {"httpStatus": status, "body": data}


class ApiLimitExceeded(Exception):
    def __init__(self, status: int, payload: Any):
        super().__init__(f"API limit ({status})")
        self.status = status
        self.payload = payload


def validate_sf_sms_setup(client: SalesforceClient) -> Tuple[bool, List[str]]:
    errors: List[str] = []
    desc = client.describe_sms_message()
    if not desc.get("createable"):
        errors.append(f"User cannot create {SMS_OBJECT} records")
    field_map = {f["name"]: f for f in desc.get("fields", [])}
    for name in REQUIRED_SMS_MESSAGE_FIELDS:
        if name not in field_map:
            errors.append(f"Missing {SMS_OBJECT} field: {name}")
            continue
        if not field_map[name].get("createable") and not field_map[name].get("updateable"):
            errors.append(f"{SMS_OBJECT} field not writable: {name}")
    guid_f = field_map.get("SMS_GUID__c")
    if guid_f and not guid_f.get("externalId"):
        errors.append("SMS_GUID__c must be marked as External ID")
    dir_f = field_map.get("Direction__c")
    if dir_f and dir_f.get("type") == "picklist":
        vals = {p["value"] for p in dir_f.get("picklistValues", []) if p.get("active")}
        for needed in ("Inbound", "Outbound"):
            if needed not in vals:
                errors.append(f'Direction__c picklist missing value "{needed}"')
    svc_f = field_map.get("Service__c")
    if svc_f and svc_f.get("type") == "picklist":
        vals = {p["value"] for p in svc_f.get("picklistValues", []) if p.get("active")}
        for needed in ("iMessage", "SMS"):
            if needed not in vals:
                errors.append(f'Service__c picklist missing value "{needed}"')
    return len(errors) == 0, errors


# ---------------------------------------------------------------------------
# Messages database
# ---------------------------------------------------------------------------


class MessagesAccessError(Exception):
    pass


MAX_DB_COPY_BYTES = 500 * 1024 * 1024  # 500 MB — refuse to temp-copy above this


def _configure_conn(conn: sqlite3.Connection) -> sqlite3.Connection:
    """Apply safe PRAGMAs for large read-only databases."""
    conn.row_factory = sqlite3.Row
    try:
        conn.execute("PRAGMA cache_size = -8000")   # 8 MB page cache (neg = KB)
        conn.execute("PRAGMA mmap_size = 67108864")  # 64 MB mmap window
        conn.execute("PRAGMA query_only = ON")
    except sqlite3.OperationalError:
        pass
    return conn


def open_messages_db() -> Tuple[sqlite3.Connection, Optional[str]]:
    """
    Open chat.db read-only. Returns (connection, temp_path_to_delete_or_None).

    For multi-GB databases the primary read-only URI is critical — the temp-file
    fallback is size-capped to avoid copying gigabytes into /tmp.
    """
    if not os.path.exists(MESSAGES_DB):
        raise MessagesAccessError(f"Messages database not found at {MESSAGES_DB}")

    db_size = os.path.getsize(MESSAGES_DB)
    logger.info("chat.db size: %.1f MB", db_size / (1024 * 1024))

    # --- Attempt 1: direct read-only (zero copy, works with WAL) ---
    try:
        uri = f"file:{MESSAGES_DB}?mode=ro"
        conn = sqlite3.connect(uri, uri=True)
        return _configure_conn(conn), None
    except (sqlite3.OperationalError, sqlite3.DatabaseError) as e:
        logger.debug("Read-only open failed: %s", e)

    # --- Attempt 2: immutable flag (skips WAL/journal entirely) ---
    try:
        uri = f"file:{MESSAGES_DB}?immutable=1"
        conn = sqlite3.connect(uri, uri=True)
        logger.info("Opened chat.db in immutable mode (WAL changes may lag)")
        return _configure_conn(conn), None
    except (sqlite3.OperationalError, sqlite3.DatabaseError) as e:
        logger.debug("Immutable open failed: %s", e)

    # --- Attempt 3: temp copy (only for smaller databases) ---
    if db_size > MAX_DB_COPY_BYTES:
        raise MessagesAccessError(
            f"Cannot open Messages database directly and it is too large to copy "
            f"({db_size / (1024*1024):.0f} MB). " + full_disk_access_hint()
        )

    temp_path: Optional[str] = None
    try:
        logger.warning("Falling back to temp copy of chat.db (%.1f MB)", db_size / (1024 * 1024))
        fd, temp_path = tempfile.mkstemp(prefix="chat_", suffix=".db")
        os.close(fd)
        shutil.copy2(MESSAGES_DB, temp_path)
        conn = sqlite3.connect(f"file:{temp_path}?mode=ro", uri=True)
        return _configure_conn(conn), temp_path
    except (OSError, sqlite3.OperationalError, sqlite3.DatabaseError) as e:
        if temp_path and os.path.exists(temp_path):
            os.unlink(temp_path)
        raise MessagesAccessError(
            "Cannot read Messages database. " + full_disk_access_hint()
        ) from e


def probe_messages_db_access() -> bool:
    """Return True if chat.db can be opened read-only (Full Disk Access OK)."""
    try:
        conn, temp_path = open_messages_db()
        conn.close()
        if temp_path and os.path.exists(temp_path):
            os.unlink(temp_path)
        return True
    except MessagesAccessError:
        return False


def is_messages_access_error(error: Optional[str]) -> bool:
    if not error:
        return False
    return "Cannot read Messages database" in error or "Messages database not found" in error


MAX_ATTRIBUTED_BODY_BYTES = 256_000  # skip plist parsing for blobs over 256 KB


def _utc_to_apple_ns(when: dt.datetime) -> int:
    """Convert a UTC datetime to Apple's nanosecond timestamp for SQL filtering."""
    return int((when - APPLE_EPOCH).total_seconds() * 1_000_000_000)


def sync_date_floor() -> dt.datetime:
    """Return the earliest message date we care about (SYNC_WINDOW_MONTHS ago)."""
    now = dt.datetime.now(tz=dt.timezone.utc)
    return now - dt.timedelta(days=SYNC_WINDOW_MONTHS * 30)


def fetch_messages_batch(
    conn: sqlite3.Connection,
    *,
    since_rowid: int = 0,
    limit: int = 50,
    date_floor_ns: Optional[int] = None,
) -> List[Dict[str, Any]]:
    """Fetch up to *limit* messages after *since_rowid*, ordered by ROWID.

    Oversized attributedBody blobs are excluded at the SQL level to avoid
    loading megabytes of binary data into Python.  Each row is parsed
    individually so a single corrupt message cannot crash the batch.

    When *date_floor_ns* is provided, messages older than that Apple-epoch
    nanosecond timestamp are skipped at the SQL level (used to enforce the
    12-month sync window on first sync / reset).
    """
    date_clause = ""
    params: list = [MAX_ATTRIBUTED_BODY_BYTES, since_rowid]
    if date_floor_ns is not None:
        date_clause = "AND m.date > ? "
        params.append(date_floor_ns)
    params.append(limit)

    sql = f"""
        SELECT
            m.ROWID AS rowid,
            m.guid,
            m.text,
            CASE WHEN LENGTH(m.attributedBody) <= ? THEN m.attributedBody ELSE NULL END
                AS attributedBody,
            m.handle_id,
            m.is_from_me,
            m.date,
            m.service,
            m.cache_has_attachments,
            h.id AS handle_identifier
        FROM message m
        LEFT JOIN handle h ON h.ROWID = m.handle_id
        WHERE m.ROWID > ?
        {date_clause}ORDER BY m.ROWID ASC
        LIMIT ?
    """
    cur = conn.execute(sql, params)
    rows: List[Dict[str, Any]] = []
    for r in cur:
        try:
            when = apple_timestamp_to_utc(r["date"])
            text = r["text"]
            if not text and r["attributedBody"]:
                try:
                    text = extract_attributed_body(r["attributedBody"])
                except Exception as exc:
                    logger.debug("attributedBody parse failed rowid %s: %s", r["rowid"], exc)
                    text = ""
            if r["cache_has_attachments"] and not (text and text.strip()):
                text = "[media attachment — not saved to Salesforce, please check the phone's SMS thread]"
            rows.append(
                {
                    "rowid": r["rowid"],
                    "guid": r["guid"],
                    "text": text or "",
                    "handle": r["handle_identifier"] or "",
                    "is_from_me": bool(r["is_from_me"]),
                    "date": when,
                    "service": r["service"] or "SMS",
                    "has_attachments": bool(r["cache_has_attachments"]),
                }
            )
        except Exception as exc:
            logger.debug("Skipping message rowid %s: %s", r["rowid"], exc)
            rows.append(
                {
                    "rowid": r["rowid"],
                    "guid": r.get("guid") or f"unknown-{r['rowid']}",
                    "text": "",
                    "handle": r.get("handle_identifier") or "",
                    "is_from_me": bool(r.get("is_from_me")),
                    "date": None,
                    "service": r.get("service") or "SMS",
                    "has_attachments": False,
                }
            )
    return rows


def chat_participant_counts(
    conn: sqlite3.Connection, message_rowids: Sequence[int]
) -> Dict[int, int]:
    """Return {message_rowid: participant_count} for a batch of messages.

    Uses a single query instead of N per-row queries — important when
    chat.db is multi-GB and each round-trip touches the B-tree.
    """
    if not message_rowids:
        return {}
    placeholders = ",".join("?" for _ in message_rowids)
    sql = f"""
        SELECT cmj.message_id, COUNT(DISTINCT chj.handle_id) AS cnt
        FROM chat_message_join cmj
        JOIN chat_handle_join chj ON chj.chat_id = cmj.chat_id
        WHERE cmj.message_id IN ({placeholders})
        GROUP BY cmj.message_id
    """
    result: Dict[int, int] = {}
    for row in conn.execute(sql, list(message_rowids)):
        result[int(row["message_id"])] = int(row["cnt"])
    return result


def detect_staff_number(conn: sqlite3.Connection, config: Dict[str, Any]) -> Optional[str]:
    if config.get("staff_number"):
        return normalize_phone_e164(config["staff_number"])
    sql = """
        SELECT DISTINCT h.id
        FROM message m
        JOIN handle h ON h.ROWID = m.handle_id
        WHERE m.is_from_me = 1 AND h.id IS NOT NULL
        ORDER BY m.ROWID DESC
        LIMIT 50
    """
    counts: Dict[str, int] = {}
    for row in conn.execute(sql):
        ph = normalize_phone_e164(row["id"])
        if ph:
            counts[ph] = counts.get(ph, 0) + 1
    if not counts:
        return None
    return max(counts, key=counts.get)


# ---------------------------------------------------------------------------
# State & lock
# ---------------------------------------------------------------------------


def load_state(path: str) -> Dict[str, Any]:
    if not os.path.exists(path):
        return {
            "last_rowid": 0,
            "total_synced": 0,
            "last_sync_at": None,
            "login_item_offered": False,
            "setup_complete": False,
        }
    with open(path, encoding="utf-8") as f:
        state = json.load(f)
    state.setdefault("last_rowid", 0)
    state.setdefault("total_synced", 0)
    state.setdefault("last_sync_at", None)
    state.setdefault("login_item_offered", False)
    state.setdefault("setup_complete", False)
    return state


def save_state(path: str, state: Dict[str, Any]) -> None:
    os.makedirs(os.path.dirname(path), exist_ok=True)
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(state, f, indent=2)
    os.replace(tmp, path)


class RunLock:
    def __init__(self, path: str):
        self.path = path
        self._fd: Optional[int] = None

    def __enter__(self) -> "RunLock":
        os.makedirs(os.path.dirname(self.path), exist_ok=True)
        self._fd = os.open(self.path, os.O_CREAT | os.O_RDWR)
        try:
            fcntl.flock(self._fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            os.close(self._fd)
            self._fd = None
            raise RuntimeError("Another PL SMS Sync instance is already running")
        return self

    def __exit__(self, *args: Any) -> None:
        if self._fd is not None:
            fcntl.flock(self._fd, fcntl.LOCK_UN)
            os.close(self._fd)
            self._fd = None


class InstanceLock:
    """Held for the lifetime of the menu bar app (single instance)."""

    def __init__(self, path: str = DEFAULT_INSTANCE_LOCK_PATH):
        self.path = path
        self._fd: Optional[int] = None

    def acquire(self) -> bool:
        os.makedirs(os.path.dirname(self.path), exist_ok=True)
        self._fd = os.open(self.path, os.O_CREAT | os.O_RDWR)
        try:
            fcntl.flock(self._fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
            return True
        except BlockingIOError:
            os.close(self._fd)
            self._fd = None
            return False

    def release(self) -> None:
        if self._fd is not None:
            fcntl.flock(self._fd, fcntl.LOCK_UN)
            os.close(self._fd)
            self._fd = None


# ---------------------------------------------------------------------------
# SMS_Message__c building & sync
# ---------------------------------------------------------------------------


def external_party_phone(handle: str) -> Optional[str]:
    """E.164 for Phone_Number__c, or None for non-phone handles."""
    if is_email_handle(handle):
        return None
    return normalize_phone_e164(handle)


def build_sms_message_record(
    msg: Dict[str, Any],
    contact: Dict[str, Any],
    synced_by_id: str,
    staff_number: Optional[str],
) -> Dict[str, Any]:
    direction = "Outbound" if msg["is_from_me"] else "Inbound"
    svc = msg.get("service") or "SMS"
    svc_label = "iMessage" if svc.lower() == "imessage" else "SMS"
    when = msg["date"] or dt.datetime.now(tz=dt.timezone.utc)
    raw_text = msg.get("text") or ""
    body = raw_text[:DESCRIPTION_MAX]
    message_c = raw_text[:MESSAGE_C_MAX]
    party_phone = external_party_phone(msg.get("handle") or "")

    rec: Dict[str, Any] = {
        "attributes": {"type": SMS_OBJECT},
        "SMS_GUID__c": msg["guid"],
        "Contact__c": contact["Id"],
        "Message_Body__c": body,
        "Message__c": message_c,
        "Synced_By__c": synced_by_id,
        "Sent_At__c": format_sf_datetime(when),
        "Direction__c": direction,
        "Service__c": svc_label,
    }
    if contact.get("AccountId"):
        rec["Account__c"] = contact["AccountId"]
    if staff_number:
        rec["Staff_Number__c"] = staff_number
    if party_phone:
        rec["Phone_Number__c"] = party_phone
        digits = party_phone.lstrip("+")
        if digits.isdigit():
            rec["Destination__c"] = digits[:15]
    return rec


# Old Wordpress Sync key that existing installs may still have.
_OLD_WP_SYNC_KEY = "3MVG9fe4g9fhX0E4LfomBbdF3rm.17iPtZHBuSYqzt4yloK_h96rqNG6e8W8YW8vSlYg7Bu8MRuc3gV780cJU"
_NEW_PL_SMS_KEY = "3MVG9fe4g9fhX0E4LfomBbdF3rmGX8Xs4vo8ZBDFiW7Ourswz2ehCmVOqkctir3S4rapH8uAz0jx5LvDofVRj"


def load_config(path: str) -> Dict[str, Any]:
    with open(path, encoding="utf-8") as f:
        cfg = json.load(f)
    if cfg.get("consumer_key") == _OLD_WP_SYNC_KEY:
        logger.info("Migrating consumer_key from Wordpress Sync → PL SMS Sync Connected App")
        cfg["consumer_key"] = _NEW_PL_SMS_KEY
        try:
            with open(path, "w", encoding="utf-8") as f:
                json.dump(cfg, f, indent=2)
                f.write("\n")
        except OSError as e:
            logger.warning("Could not persist consumer_key migration: %s", e)
        keychain_delete()
    return cfg


def resolve_tokens(config: Dict[str, Any], login: bool) -> Optional[Dict[str, Any]]:
    raw = keychain_load()
    if raw:
        try:
            return json.loads(raw)
        except json.JSONDecodeError:
            pass
    if login:
        tokens = oauth_login(config)
        keychain_store(json.dumps(tokens))
        return tokens
    return None


def process_messages(
    conn: sqlite3.Connection,
    messages: List[Dict[str, Any]],
    contact_index: ContactIndex,
    *,
    skip_groups: bool = True,
    staff_exclusion: Optional[StaffExclusionIndex] = None,
) -> Dict[str, Any]:
    stats = {
        "total": len(messages),
        "sent": 0,
        "received": 0,
        "imessage": 0,
        "sms": 0,
        "upload": 0,
        "no_match": 0,
        "ambiguous": 0,
        "skipped_group": 0,
        "skipped_internal": 0,
        "no_match_handles": [],
        "ambiguous_details": [],
        "to_upload": [],
    }

    # One batched query for all participant counts instead of N per-row queries
    group_counts: Dict[int, int] = {}
    if skip_groups:
        group_counts = chat_participant_counts(conn, [m["rowid"] for m in messages])

    for msg in messages:
        if msg["is_from_me"]:
            stats["sent"] += 1
        else:
            stats["received"] += 1
        svc = (msg.get("service") or "").lower()
        if "imessage" in svc:
            stats["imessage"] += 1
        else:
            stats["sms"] += 1

        if skip_groups and group_counts.get(msg["rowid"], 0) > 2:
            stats["skipped_group"] += 1
            continue

        # Skip internal staff-to-staff communications
        if staff_exclusion and staff_exclusion.is_internal(msg["handle"]):
            stats["skipped_internal"] += 1
            continue

        status, ids = contact_index.match(msg["handle"])
        if status == "one":
            stats["upload"] += 1
            stats["to_upload"].append((msg, contact_index.get(ids[0])))
        elif status == "ambiguous":
            stats["ambiguous"] += 1
            stats["ambiguous_details"].append({"handle_masked": mask_phone(normalize_phone_e164(msg["handle"])), "contact_ids": ids})
        else:
            stats["no_match"] += 1
            if not is_email_handle(msg["handle"]):
                stats["no_match_handles"].append(mask_phone(normalize_phone_e164(msg["handle"])))
            else:
                stats["no_match_handles"].append("(email hidden)")

    return stats


def print_test_report(
    messages: List[Dict[str, Any]],
    stats: Dict[str, Any],
    sf_ok: bool,
    sf_errors: List[str],
) -> bool:
    dates = [m["date"] for m in messages if m.get("date")]
    if dates:
        dr = f"{min(dates).astimezone(BRISBANE).isoformat()} .. {max(dates).astimezone(BRISBANE).isoformat()} (Brisbane)"
    else:
        dr = "n/a"

    print("\n=== PL SMS Sync — test report ===")
    print(f"Messages scanned: {stats['total']}")
    print(f"Sent: {stats['sent']}  Received: {stats['received']}")
    print(f"Service — iMessage: {stats['imessage']}  SMS: {stats['sms']}")
    print(f"Date range (Brisbane): {dr}")
    print(f"Skipped group chats (>2 participants): {stats['skipped_group']}")
    print(f"Would upload: {stats['upload']}")
    print(f"No Contact match: {stats['no_match']}")
    print(f"Ambiguous match: {stats['ambiguous']}")
    if sf_errors:
        print("Salesforce validation:")
        for e in sf_errors:
            print(f"  - {e}")
    else:
        print(f"Salesforce validation: all required {SMS_OBJECT} fields present")

    print("\nLast 5 messages (masked numbers, preview only):")
    for msg in messages[-5:]:
        h = mask_phone(normalize_phone_e164(msg["handle"])) if not is_email_handle(msg["handle"]) else "(email)"
        prev = preview_text(msg.get("text") or "")
        when = msg.get("date")
        ts = utc_to_brisbane(when).strftime("%Y-%m-%d %H:%M") if when else "?"
        direction = "out" if msg["is_from_me"] else "in"
        print(f"  [{ts}] {direction} {h}: {prev}")

    passed = sf_ok and stats["total"] >= 0
    print("\n" + ("PASS" if passed else "FAIL"))
    return passed


def run_sync_batch(
    client: SalesforceClient,
    records: List[Dict[str, Any]],
) -> Tuple[int, int]:
    ok = 0
    fail = 0
    for i in range(0, len(records), COMPOSITE_BATCH):
        chunk = records[i : i + COMPOSITE_BATCH]
        try:
            result = client.composite_upsert_sms_messages(chunk)
        except ApiLimitExceeded:
            logger.warning("Salesforce API limit hit; will retry on next run")
            raise
        status = result.get("httpStatus")
        body = result.get("body")
        logger.debug("Composite response status=%s body_type=%s", status, type(body).__name__)
        if isinstance(body, list):
            for idx, item in enumerate(body):
                if item.get("success"):
                    ok += 1
                else:
                    fail += 1
                    errors = item.get("errors") or []
                    logger.warning(
                        "Upsert failure [%d]: success=%s errors=%s full_item=%s",
                        idx, item.get("success"), errors, item,
                    )
        elif isinstance(body, dict):
            if body.get("success"):
                ok += len(chunk)
            else:
                fail += len(chunk)
                logger.warning("Composite error response: %s", body)
        else:
            logger.warning("Unexpected composite response: httpStatus=%s body=%s", status, body)
            fail += len(chunk)
    return ok, fail


def format_relative_sync(when_iso: Optional[str]) -> str:
    if not when_iso:
        return "Never"
    try:
        when = dt.datetime.fromisoformat(when_iso.replace("Z", "+00:00"))
    except ValueError:
        return "Unknown"
    if when.tzinfo is None:
        when = when.replace(tzinfo=dt.timezone.utc)
    delta = dt.datetime.now(tz=dt.timezone.utc) - when.astimezone(dt.timezone.utc)
    secs = int(delta.total_seconds())
    if secs < 0:
        return "Just now"
    if secs < 60:
        return "Just now"
    if secs < 3600:
        m = secs // 60
        return f"{m} minute{'s' if m != 1 else ''} ago"
    if secs < 86400:
        h = secs // 3600
        return f"{h} hour{'s' if h != 1 else ''} ago"
    d = secs // 86400
    return f"{d} day{'s' if d != 1 else ''} ago"


def format_sync_count(n: int) -> str:
    return f"{n:,} messages synced"


def perform_sync(
    config: Dict[str, Any],
    *,
    state_path: str = DEFAULT_STATE_PATH,
    log_path: Optional[str] = DEFAULT_LOG_PATH,
    notify: bool = True,
) -> Dict[str, Any]:
    """Run one sync cycle (upsert). Returns summary with ok, fail, error, signed_in."""
    result: Dict[str, Any] = {"ok": 0, "fail": 0, "error": None, "signed_in": bool(keychain_load())}
    setup_logging(log_path, verbose=False)
    logger.info("Sync: starting")

    tokens = resolve_tokens(config, login=False)
    if not tokens:
        result["error"] = "not_signed_in"
        if notify:
            notify_macos(APP_NAME, "PL SMS Sync needs you to sign in to Salesforce")
        return result

    temp_db: Optional[str] = None
    try:
        conn, temp_db = open_messages_db()
    except MessagesAccessError as e:
        result["error"] = str(e)
        logger.error("%s", e)
        return result

    BATCH_SIZE = 50
    state = load_state(state_path)
    since_rowid = int(state.get("last_rowid", 0))

    try:
        sf_client = SalesforceClient(config, tokens)
        contacts: List[Dict[str, Any]] = []
        try:
            contacts = sf_client.query_contacts_fallback()
        except Exception:
            contacts = []
        if not contacts:
            logger.info("Sync: no contacts from fallback query, will try per-batch")
        else:
            logger.info("Sync: loaded %d Salesforce contacts for matching", len(contacts))
        ci = ContactIndex(contacts)

        # Build staff exclusion index to skip internal comms
        # Sourced from Contacts under the Pure Locations Pty Ltd Account
        staff_excl: Optional[StaffExclusionIndex] = None
        try:
            internal_contacts = sf_client.query_internal_staff()
            staff_excl = StaffExclusionIndex(internal_contacts)
            logger.info("Sync: loaded %d internal staff contacts for exclusion (%d phones, %d emails)",
                        len(staff_excl), len(staff_excl._phones), len(staff_excl._emails))
        except Exception as exc:
            logger.warning("Could not load internal staff for exclusion: %s", exc)

        synced_by = sf_client.query_user_id() or tokens.get("id", "")
        staff = detect_staff_number(conn, config)
        batches_processed = 0

        # Apply 12-month date floor so we don't sync ancient messages
        floor = sync_date_floor()
        date_floor_ns = _utc_to_apple_ns(floor)
        logger.info("Sync: date floor = %s (%d months window)", floor.strftime("%Y-%m-%d"), SYNC_WINDOW_MONTHS)

        with RunLock(DEFAULT_LOCK_PATH):
            while True:
                messages = fetch_messages_batch(
                    conn, since_rowid=since_rowid, limit=BATCH_SIZE,
                    date_floor_ns=date_floor_ns,
                )
                logger.info(
                    "Sync batch %d: fetched %d messages (after rowid %d)",
                    batches_processed + 1, len(messages), since_rowid,
                )
                if not messages:
                    # Re-read state from disk so we don't overwrite a user reset
                    state = load_state(state_path)
                    state["last_sync_at"] = dt.datetime.now(tz=dt.timezone.utc).isoformat()
                    save_state(state_path, state)
                    break

                # If fallback returned nothing, try targeted query with this batch's numbers
                if not contacts:
                    phone_keys = list({
                        normalize_phone_e164(m["handle"])
                        for m in messages
                        if not is_email_handle(m["handle"]) and normalize_phone_e164(m["handle"])
                    })
                    if phone_keys:
                        try:
                            contacts = sf_client.query_contacts(phone_keys)
                            ci = ContactIndex(contacts)
                        except urllib.error.HTTPError:
                            pass

                stats = process_messages(conn, messages, ci, staff_exclusion=staff_excl)
                if stats["skipped_internal"] > 0:
                    logger.debug("Batch %d: skipped %d internal messages",
                                 batches_processed + 1, stats["skipped_internal"])
                max_rowid = max(m["rowid"] for m in messages)
                batch_ok = 0

                if stats["to_upload"]:
                    records = [
                        build_sms_message_record(m, c, synced_by, staff)
                        for m, c in stats["to_upload"]
                    ]
                    try:
                        ok, fail = run_sync_batch(sf_client, records)
                    except ApiLimitExceeded:
                        logger.warning("API limit reached after %d batches, saving progress", batches_processed)
                        state = load_state(state_path)
                        state["last_rowid"] = max(state.get("last_rowid", 0), max_rowid)
                        state["last_sync_at"] = dt.datetime.now(tz=dt.timezone.utc).isoformat()
                        save_state(state_path, state)
                        result["error"] = "api_limit"
                        return result
                    batch_ok = ok
                    result["ok"] += ok
                    result["fail"] += fail
                    logger.info("Batch %d: upserted %d, failed %d", batches_processed + 1, ok, fail)

                # Re-read state from disk before merging — prevents overwriting a user reset
                state = load_state(state_path)
                state["last_rowid"] = max(state.get("last_rowid", 0), max_rowid)
                state["total_synced"] = int(state.get("total_synced", 0)) + batch_ok
                state["last_sync_at"] = dt.datetime.now(tz=dt.timezone.utc).isoformat()
                save_state(state_path, state)

                since_rowid = max_rowid
                batches_processed += 1
                del messages, stats  # free memory before next batch

        logger.info("Sync complete: %d upserted, %d failures across %d batches",
                     result["ok"], result["fail"], batches_processed)
    except TokenRefreshFailed as e:
        result["error"] = "session_expired"
        result["signed_in"] = False
        logger.warning("Session expired, re-login needed: %s", e)
    except Exception as e:
        result["error"] = str(e)
        logger.exception("Sync failed: %s", e)
    finally:
        conn.close()
        if temp_db and os.path.exists(temp_db):
            os.unlink(temp_db)
    return result


def cli_mode_requested(argv: Optional[Sequence[str]] = None) -> bool:
    args = argv if argv is not None else sys.argv[1:]
    if not args:
        return False
    flags = {"--test", "--sync", "--login", "--logout", "-h", "--help", "-v", "--verbose"}
    return any(a in flags or a.startswith("-") for a in args)


# ---------------------------------------------------------------------------
# Menu bar app (rumps)
# ---------------------------------------------------------------------------


def run_menu_bar_app() -> None:
    import rumps

    class PLSmsSyncApp(rumps.App):
        def __init__(self) -> None:
            super().__init__("PL SMS Sync", title="💬", quit_button="Quit")
            self.config_path = DEFAULT_CONFIG_PATH
            self.state_path = DEFAULT_STATE_PATH
            self._sync_lock = threading.Lock()
            self._syncing = False
            self._menu_dirty = False
            self._waiting_for_fda = False
            self._fda_dialog_shown = False
            self._sf_login_dialog_shown = False
            self._welcome_shown = False
            self._pending_login_item_offer = False
            self._pending_setup_finish = False
            self._normal_sync_interval = 900
            # Cached values for hot-path menu refresh (avoid subprocess + disk I/O every 5s)
            self._cached_signed_in: bool = False
            self._cached_state: Dict[str, Any] = {}
            self._cache_ts: float = 0.0
            self._cache_ttl: float = 10.0  # seconds

            if not os.path.exists(self.config_path):
                os.makedirs(os.path.dirname(self.config_path), exist_ok=True)
                example = ""
                if is_frozen() and hasattr(sys, "_MEIPASS"):
                    for candidate in [
                        os.path.join(sys._MEIPASS, "config.example.json"),
                        os.path.join(os.path.dirname(sys.executable), "..", "Resources", "config.example.json"),
                    ]:
                        if os.path.isfile(candidate):
                            example = candidate
                            break
                if not example:
                    fallback = os.path.join(
                        os.path.dirname(os.path.abspath(__file__)), "config.example.json"
                    )
                    if os.path.isfile(fallback):
                        example = fallback
                if example:
                    shutil.copy2(example, self.config_path)

            self.header_item = rumps.MenuItem("💬 PL SMS Sync", callback=None)
            self.status_item = rumps.MenuItem("⚠️ Not signed in", callback=None)
            self.help_item = rumps.MenuItem(
                "   Click here for help...",
                callback=self._fda_help_action,
            )
            self.last_sync_item = rumps.MenuItem("   Last sync: Never", callback=None)
            self.count_item = rumps.MenuItem("   0 messages synced", callback=None)
            self.sign_in_item = rumps.MenuItem("Sign in to Salesforce...", callback=self.login_action)
            self.sync_now_item = rumps.MenuItem("↻ Sync Now", callback=self.sync_now)
            self.start_at_login_item = rumps.MenuItem(
                "Start at Login",
                callback=self.toggle_start_at_login,
            )
            self.view_log_item = rumps.MenuItem("View Log...", callback=self.view_log)
            self.reset_item = rumps.MenuItem("Reset Sync History...", callback=self.reset_sync)
            self.sign_out_item = rumps.MenuItem("Sign Out", callback=self.sign_out)
            self.about_item = rumps.MenuItem("About PL SMS Sync", callback=self.about)

            self.menu = [
                self.header_item,
                None,
                self.status_item,
                self.help_item,
                self.last_sync_item,
                self.count_item,
                None,
                self.sync_now_item,
                self.sign_in_item,
                None,
                self.start_at_login_item,
                None,
                self.view_log_item,
                self.reset_item,
                self.sign_out_item,
                None,
                self.about_item,
            ]

            setup_logging(DEFAULT_LOG_PATH, verbose=False)
            self._run_migrations()
            if os.path.exists(self.config_path):
                try:
                    self._normal_sync_interval = int(
                        load_config(self.config_path).get("sync_interval", 900)
                    )
                except (TypeError, ValueError, json.JSONDecodeError):
                    pass
            self._sync_timer = rumps.Timer(self.auto_sync, self._normal_sync_interval)
            self._sync_timer.start()
            self._fda_timer = rumps.Timer(self._fda_retry_tick, FDA_RETRY_INTERVAL)
            self._ui_timer = rumps.Timer(self.refresh_ui, 5)
            self._ui_timer.start()
            # Auto-update check on launch (background thread)
            self._update_timer = rumps.Timer(self._check_update_tick, 14400)  # 4 hours
            threading.Thread(target=self._check_update_background, daemon=True).start()
            self.refresh_menu(None)

            self._bootstrap_timer = rumps.Timer(self._bootstrap_on_main_thread, 1)
            self._bootstrap_timer.start()

        def _load_config(self) -> Dict[str, Any]:
            return load_config(self.config_path)

        def _refresh_cache(self, force: bool = False) -> None:
            """Refresh cached signed-in flag and state from disk/keychain.

            Called from refresh_menu (every 5s).  Avoids spawning a subprocess
            and reading state.json on every tick.
            """
            now = time.time()
            if not force and (now - self._cache_ts) < self._cache_ttl:
                return
            self._cached_signed_in = bool(keychain_load())
            self._cached_state = load_state(self.state_path)
            self._cache_ts = now

        def _invalidate_cache(self) -> None:
            """Force next refresh_menu to re-read keychain and state."""
            self._cache_ts = 0.0

        def _in_setup_mode(self) -> bool:
            return not load_state(self.state_path).get("setup_complete", False)

        def _finish_setup(self) -> None:
            state = load_state(self.state_path)
            if state.get("setup_complete"):
                return
            state["setup_complete"] = True
            save_state(self.state_path, state)
            self._menu_dirty = True; self._invalidate_cache()

        def _show_welcome_once(self) -> None:
            if self._welcome_shown or not self._in_setup_mode():
                return
            self._welcome_shown = True
            rumps.alert(WELCOME_ALERT_TITLE, WELCOME_ALERT_MESSAGE, "OK")

        def _fda_help_action(self, _: Any) -> None:
            open_full_disk_access_settings()

        def _begin_fda_wait(self) -> None:
            self._waiting_for_fda = True
            self._menu_dirty = True; self._invalidate_cache()
            self._fda_timer.interval = (
                FDA_SETUP_RETRY_INTERVAL if self._in_setup_mode() else FDA_RETRY_INTERVAL
            )
            if not self._fda_timer.is_alive():
                self._fda_timer.start()

        def _show_fda_dialog_once(self) -> None:
            if self._fda_dialog_shown:
                return
            self._fda_dialog_shown = True
            rumps.alert(FDA_ALERT_TITLE, FDA_ALERT_MESSAGE, "OK")
            open_full_disk_access_settings()

        def _prompt_sf_login_if_needed(self) -> None:
            if self._sf_login_dialog_shown or keychain_load():
                return
            self._sf_login_dialog_shown = True
            if self._in_setup_mode():
                message = (
                    "Now let's connect to Salesforce.\n\n"
                    "Click Sign In and log in with your Salesforce credentials."
                )
            else:
                message = "Sign in to Salesforce to start syncing your messages."
            response = rumps.alert(APP_NAME, message, ok="Sign In", cancel="Later")
            if response == 1:
                self.login_action(None)

        def _on_fda_granted(self) -> None:
            if not self._waiting_for_fda:
                return
            self._waiting_for_fda = False
            if self._fda_timer.is_alive():
                self._fda_timer.stop()
            self._sync_timer.interval = self._normal_sync_interval
            if self._in_setup_mode():
                rumps.notification(APP_NAME, "✅ Messages access granted!", "")
            else:
                rumps.notification(APP_NAME, "PL SMS Sync is now reading your messages", "")
            self._menu_dirty = True; self._invalidate_cache()
            self._after_messages_access_ready()

        def _after_messages_access_ready(self) -> None:
            if keychain_load():
                self._run_sync_async(notify=False)
            else:
                self._prompt_sf_login_if_needed()

        def _bootstrap_on_main_thread(self, _: Any) -> None:
            self._bootstrap_timer.stop()
            self._show_welcome_once()
            if probe_messages_db_access():
                self._after_messages_access_ready()
                return
            self._begin_fda_wait()
            self._show_fda_dialog_once()

        def _fda_retry_tick(self, _: Any) -> None:
            if not self._waiting_for_fda:
                return
            if probe_messages_db_access():
                self._on_fda_granted()

        def refresh_ui(self, _: Any) -> None:
            if self._pending_login_item_offer:
                self._pending_login_item_offer = False
                self._offer_login_item_once()
            if self._pending_setup_finish:
                self._pending_setup_finish = False
                self._finish_setup()
            if self._menu_dirty:
                self._menu_dirty = False
            self.refresh_menu(None)

        def refresh_menu(self, _: Any) -> None:
            self._refresh_cache()
            signed_in = self._cached_signed_in
            state = self._cached_state
            in_setup = not state.get("setup_complete", False)

            self.last_sync_item.title = f"   Last sync: {format_relative_sync(state.get('last_sync_at'))}"
            total = int(state.get("total_synced", 0))
            self.count_item.title = f"   {format_sync_count(total)}"
            try:
                self.start_at_login_item.state = 1 if login_item_enabled() else 0
            except Exception:
                pass

            if in_setup and self._waiting_for_fda:
                self.status_item.title = "⚠️ Step 1 of 2: Grant Messages access"
                self.help_item.title = "   Click here for help..."
                self.help_item.set_callback(self._fda_help_action)
                self.sign_in_item.title = ""
                self.sign_in_item.set_callback(None)
                self.sync_now_item.set_callback(None)
            elif in_setup and not signed_in:
                self.status_item.title = "⚠️ Step 2 of 2: Sign into Salesforce"
                self.help_item.title = ""
                self.help_item.set_callback(None)
                self.sign_in_item.title = "Sign in to Salesforce..."
                self.sign_in_item.set_callback(self.login_action)
                self.sync_now_item.set_callback(None)
            elif signed_in:
                self.status_item.title = "✅ Connected to Salesforce"
                self.help_item.title = ""
                self.help_item.set_callback(None)
                self.sign_in_item.title = ""
                self.sign_in_item.set_callback(None)
                self.sync_now_item.set_callback(self.sync_now)
            else:
                if state.get("last_sync_at"):
                    self.status_item.title = "⚠️ Salesforce connection lost"
                else:
                    self.status_item.title = "⚠️ Not signed in"
                self.help_item.title = ""
                self.help_item.set_callback(None)
                self.sign_in_item.title = "Sign in to Salesforce..."
                self.sign_in_item.set_callback(self.login_action)
                self.sync_now_item.set_callback(self.sync_now)

        def _mark_login_item_offer_pending(self) -> None:
            state = load_state(self.state_path)
            if state.get("login_item_offered"):
                if self._in_setup_mode():
                    self._pending_setup_finish = True
                return
            if not keychain_load() or not probe_messages_db_access():
                return
            self._pending_login_item_offer = True

        def _offer_login_item_once(self) -> None:
            state = load_state(self.state_path)
            if state.get("login_item_offered"):
                return
            if not keychain_load() or not probe_messages_db_access():
                return
            state["login_item_offered"] = True
            save_state(self.state_path, state)
            if login_item_enabled():
                if self._in_setup_mode():
                    self._finish_setup()
                return
            response = rumps.alert(
                "Start automatically?",
                "Would you like PL SMS Sync to start automatically when you log in?",
                ok="Yes",
                cancel="No",
            )
            if response == 1:
                if set_login_item_enabled(True):
                    rumps.notification(APP_NAME, "PL SMS Sync will start at login", "")
                else:
                    rumps.notification(
                        APP_NAME,
                        "Could not add Login Item",
                        "Use the menu: Start at Login, or System Settings → Login Items.",
                    )
            if self._in_setup_mode():
                self._finish_setup()
            self._menu_dirty = True; self._invalidate_cache()

        def toggle_start_at_login(self, sender: Any) -> None:
            currently = login_item_enabled()
            want = not currently
            if set_login_item_enabled(want):
                try:
                    sender.state = 1 if want else 0
                except Exception:
                    pass
                if want:
                    rumps.notification(APP_NAME, "Enabled start at login", "")
                else:
                    rumps.notification(APP_NAME, "Disabled start at login", "")
            else:
                rumps.notification(
                    APP_NAME,
                    "Login Items change failed",
                    "Grant automation permission for System Events if prompted.",
                )
            self._menu_dirty = True; self._invalidate_cache()

        def _run_sync_async(self, *, notify: bool = True) -> None:
            if not self._sync_lock.acquire(blocking=False):
                rumps.notification(APP_NAME, "Sync already in progress", "")
                return
            self._syncing = True

            def work() -> None:
                try:
                    if not os.path.exists(self.config_path):
                        rumps.notification(APP_NAME, "Missing config.json", DEFAULT_CONFIG_PATH)
                        return
                    if self._waiting_for_fda:
                        return
                    result = perform_sync(
                        self._load_config(),
                        state_path=self.state_path,
                        log_path=DEFAULT_LOG_PATH,
                        notify=notify,
                    )
                    if result.get("error") == "session_expired":
                        rumps.notification(APP_NAME, "Salesforce session expired", "Please sign in again.")
                        self.status_item.title = "⚠️ Session expired — sign in again"
                    elif is_messages_access_error(result.get("error")):
                        self._begin_fda_wait()
                    elif result.get("error") is None and result.get("signed_in"):
                        self._mark_login_item_offer_pending()
                finally:
                    self._syncing = False
                    self._sync_lock.release()
                    self._menu_dirty = True; self._invalidate_cache()

            threading.Thread(target=work, daemon=True).start()

        def sync_now(self, _: Any) -> None:
            if self._waiting_for_fda and not probe_messages_db_access():
                rumps.notification(
                    APP_NAME,
                    "Waiting for Full Disk Access",
                    "Enable PL SMS Sync in System Settings → Privacy & Security → Full Disk Access.",
                )
                return
            self._run_sync_async(notify=True)

        def auto_sync(self, _: Any) -> None:
            if self._waiting_for_fda:
                if probe_messages_db_access():
                    self._on_fda_granted()
                return
            if not self._syncing:
                self._run_sync_async(notify=True)

        def login_action(self, _: Any) -> None:
            if not os.path.exists(self.config_path):
                rumps.notification(APP_NAME, "Create config first", self.config_path)
                return

            self.status_item.title = "⏳ Signing in to Salesforce..."
            self._menu_dirty = True; self._invalidate_cache()

            def work() -> None:
                try:
                    logger.info("Login: starting OAuth flow")
                    tokens = oauth_login(self._load_config())
                    logger.info("Login: OAuth complete, storing tokens in Keychain")
                    keychain_store(json.dumps(tokens))
                    logger.info("Login: Salesforce sign-in saved to Keychain")
                    rumps.notification(APP_NAME, "✅ Connected to Salesforce!", "")
                    if probe_messages_db_access():
                        self._run_sync_async(notify=False)
                    elif self._in_setup_mode():
                        self._begin_fda_wait()
                        self._show_fda_dialog_once()
                except Exception as e:
                    logger.error("Sign-in failed: %s", e, exc_info=True)
                    error_msg = str(e)
                    if len(error_msg) > 200:
                        error_msg = error_msg[:200] + "..."
                    self.status_item.title = "❌ Sign-in failed"
                    # Use osascript for the alert — safe from any thread
                    escaped = error_msg.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")
                    subprocess.run(
                        ["osascript", "-e",
                         f'display dialog "Sign-in failed:\\n\\n{escaped}\\n\\n'
                         f'Check ~/Library/Logs/pl-sms-sync.log for details." '
                         f'with title "PL SMS Sync" buttons {{"OK"}} default button "OK" '
                         f'with icon stop'],
                        capture_output=True, timeout=60
                    )
                self._menu_dirty = True; self._invalidate_cache()

            threading.Thread(target=work, daemon=True).start()

        def view_log(self, _: Any) -> None:
            path = DEFAULT_LOG_PATH
            os.makedirs(os.path.dirname(path), exist_ok=True)
            if not os.path.exists(path):
                open(path, "a", encoding="utf-8").close()
            subprocess.run(["open", "-a", "Console", path], check=False)

        def reset_sync(self, _: Any) -> None:
            resp = rumps.alert(
                "Reset Sync History",
                "This will clear all sync progress and re-sync all messages from scratch.\n\n"
                "Your Salesforce connection will not be affected.",
                ok="Reset",
                cancel="Cancel",
            )
            if resp == 1:
                state_path = os.path.join(DEFAULT_SUPPORT_DIR, "state.json")
                try:
                    state = load_state(state_path)
                    fresh = {"setup_complete": state.get("setup_complete", True)}
                    save_state(state_path, fresh)
                    self.last_sync_item.title = "   Last sync: Never"
                    self.count_item.title = "   0 messages synced"
                    self._menu_dirty = True; self._invalidate_cache()
                    logger.info("Sync history reset by user")
                    rumps.notification(APP_NAME, "Sync history cleared", "Next sync will process all messages.")
                except OSError as e:
                    logger.error("Failed to reset sync state: %s", e)
                    rumps.notification(APP_NAME, "Reset failed", str(e))

        def sign_out(self, _: Any) -> None:
            resp = rumps.alert(
                "Sign Out",
                "This will remove your Salesforce connection.\n\n"
                "You'll need to sign in again to sync messages.",
                ok="Sign Out",
                cancel="Cancel",
            )
            if resp == 1:
                keychain_delete()
                self.status_item.title = "⚠️ Not signed in"
                self._menu_dirty = True; self._invalidate_cache()
                logger.info("User signed out of Salesforce")
                rumps.notification(APP_NAME, "Signed out", "Click 'Sign in to Salesforce' to reconnect.")

        # ── Migrations ──

        def _run_migrations(self) -> None:
            """One-time data migrations keyed by version."""
            state = load_state(self.state_path)
            applied = set(state.get("migrations_applied", []))

            if "v1.1.0_resync" not in applied and state.get("setup_complete"):
                # v1.1.0 fixed message truncation (126-byte limit), first/last
                # char loss, NSString leaking, and added emoji support.
                # Reset sync so every message is re-extracted with the new parser
                # and upserted over the broken Salesforce records.
                old_total = state.get("total_synced", 0)
                state["last_rowid"] = 0
                state["total_synced"] = 0
                state["last_sync_at"] = None
                applied.add("v1.1.0_resync")
                state["migrations_applied"] = sorted(applied)
                save_state(self.state_path, state)
                logger.info(
                    "Migration v1.1.0_resync: reset sync history "
                    "(was %d messages) — re-sync will fix truncated text",
                    old_total,
                )

            if "v1.2.0_resync" not in applied and state.get("setup_complete"):
                # v1.2.0 replaced manual binary parser with Apple's NSUnarchiver
                # and removed UTF-16BE raw scanner that produced CJK garbage.
                # Re-sync to fix garbled records in Salesforce.
                old_total = state.get("total_synced", 0)
                state["last_rowid"] = 0
                state["total_synced"] = 0
                state["last_sync_at"] = None
                applied.add("v1.2.0_resync")
                state["migrations_applied"] = sorted(applied)
                save_state(self.state_path, state)
                logger.info(
                    "Migration v1.2.0_resync: reset sync history "
                    "(was %d messages) — re-sync with NSUnarchiver parser",
                    old_total,
                )

        def about(self, _: Any) -> None:
            rumps.alert(
                APP_NAME,
                f"Version {APP_VERSION}\n\n"
                "Syncs iMessage/SMS from this Mac to Salesforce SMS_Message__c records.",
                "Pure Locations",
            )

        # ── Auto-update ──

        def _check_update_background(self) -> None:
            """Run update check in a background thread (called on launch)."""
            try:
                time.sleep(5)  # let the app finish launching
                info = check_for_update()
                if info:
                    version = info.get("version", "?")
                    logger.info("Update available: v%s (current: v%s)", version, APP_VERSION)
                    rumps.notification(
                        APP_NAME,
                        f"Updating to v{version}…",
                        "The app will restart automatically.",
                    )
                    time.sleep(2)
                    if apply_update(info):
                        rumps.quit_application()
                else:
                    logger.debug("No update available (current: v%s)", APP_VERSION)
                    # Start the periodic timer only after first check
                    self._update_timer.start()
            except Exception as exc:
                logger.debug("Update check error: %s", exc)

        def _check_update_tick(self, _: Any) -> None:
            """Periodic update check (every 4 hours)."""
            threading.Thread(target=self._check_update_background, daemon=True).start()

    instance = InstanceLock()
    if not instance.acquire():
        rumps.notification(APP_NAME, "Already running", "Quit the other PL SMS Sync first.")
        return

    app = PLSmsSyncApp()
    app._instance_lock = instance  # type: ignore[attr-defined]
    app.run()
    instance.release()


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------


def parse_args(argv: Optional[Sequence[str]] = None) -> argparse.Namespace:
    p = argparse.ArgumentParser(description=APP_NAME)
    p.add_argument("--config", default=DEFAULT_CONFIG_PATH, help="Path to config.json")
    p.add_argument("--state", default=DEFAULT_STATE_PATH, help="Path to state.json")
    p.add_argument("--log-file", default=None, help="Log file path")
    p.add_argument("-v", "--verbose", action="store_true")
    mode = p.add_mutually_exclusive_group()
    mode.add_argument("--test", action="store_true", help="Read-only validation (default)")
    mode.add_argument("--sync", action="store_true", help="Perform Salesforce upserts")
    p.add_argument("--confirm", action="store_true", help="Required with --sync to write")
    p.add_argument("--since", metavar="YYYY-MM-DD", help="Only messages on/after this date (UTC calendar day)")
    p.add_argument("--limit", type=int, help="Max messages to process")
    p.add_argument("--login", action="store_true", help="Run Salesforce OAuth sign-in")
    p.add_argument("--logout", action="store_true", help="Delete Keychain tokens")
    return p.parse_args(argv)


def main(argv: Optional[Sequence[str]] = None) -> int:
    args = parse_args(argv)
    log_path = args.log_file or (DEFAULT_LOG_PATH if args.sync else None)
    setup_logging(log_path, args.verbose)

    if args.logout:
        keychain_delete()
        print("Salesforce token removed from Keychain")
        return 0

    config_path = args.config
    if not os.path.exists(config_path):
        logger.error("Config not found: %s — copy config.example.json", config_path)
        return 1
    config = load_config(config_path)

    do_test = not args.sync
    if args.login or (not do_test and not keychain_load()):
        try:
            resolve_tokens(config, login=True)
            logger.info("Salesforce sign-in saved to Keychain")
        except Exception as e:
            logger.error("Sign-in failed: %s", e)
            return 1
        if args.login:
            return 0

    tokens = resolve_tokens(config, login=False)
    if not tokens and do_test:
        logger.warning("No Salesforce token; SF validation will be skipped")
    elif not tokens and args.sync:
        notify_macos(APP_NAME, "PL SMS Sync needs you to sign in to Salesforce")
        logger.error("No Salesforce token in Keychain")
        return 1

    since_date: Optional[dt.date] = None
    if args.since:
        since_date = dt.date.fromisoformat(args.since)

    temp_db: Optional[str] = None
    try:
        conn, temp_db = open_messages_db()
    except MessagesAccessError as e:
        logger.error("%s", e)
        return 1

    state = load_state(args.state)
    since_rowid = int(state.get("last_rowid", 0))
    if args.since or args.limit:
        # allow re-processing window regardless of rowid when filters set
        since_rowid = 0

    CLI_BATCH = args.limit or 50
    try:
        sf_client: Optional[SalesforceClient] = None
        sf_ok = True
        sf_errors: List[str] = []
        contacts: List[Dict[str, Any]] = []

        if tokens:
            try:
                sf_client = SalesforceClient(config, tokens)
                sf_ok, sf_errors = validate_sf_sms_setup(sf_client)
            except urllib.error.HTTPError as e:
                sf_ok = False
                sf_errors = [f"Salesforce HTTP {e.code}"]
            except Exception as e:
                sf_ok = False
                sf_errors = [str(e)]
        elif do_test:
            sf_ok = False
            sf_errors = ["No Salesforce token in Keychain; run --login"]

        # For --test mode, fetch one batch for the report
        if do_test:
            messages = fetch_messages_batch(conn, since_rowid=since_rowid, limit=CLI_BATCH)
            if sf_client:
                try:
                    contacts = sf_client.query_contacts_fallback()
                except Exception:
                    contacts = []
            ci = ContactIndex(contacts)
            stats = process_messages(conn, messages, ci)
            print_test_report(messages, stats, sf_ok, sf_errors)
            return 0 if sf_ok else 1

        if not args.confirm:
            logger.error("--sync requires --confirm")
            return 1
        if not sf_client or not tokens:
            notify_macos(APP_NAME, "PL SMS Sync needs you to sign in to Salesforce")
            return 1

        # Load contacts once, build index once
        try:
            contacts = sf_client.query_contacts_fallback()
        except Exception:
            contacts = []
        ci = ContactIndex(contacts)

        synced_by = sf_client.query_user_id() or tokens.get("id", "")
        staff = detect_staff_number(conn, config)
        total_ok = 0
        total_fail = 0
        batches = 0

        while True:
            messages = fetch_messages_batch(conn, since_rowid=since_rowid, limit=CLI_BATCH)
            if not messages:
                break
            batches += 1
            logger.info("CLI batch %d: %d messages (after rowid %d)", batches, len(messages), since_rowid)

            # max_rowid MUST come from the pre-filter list so we always advance
            max_rowid = max(m["rowid"] for m in messages)

            # Apply since_date filter for CLI
            if since_date:
                messages = [
                    m for m in messages
                    if m.get("date") and m["date"].astimezone(dt.timezone.utc).date() >= since_date
                ]

            stats = process_messages(conn, messages, ci)

            batch_ok = 0
            if stats["to_upload"]:
                with RunLock(DEFAULT_LOCK_PATH):
                    records = [
                        build_sms_message_record(m, c, synced_by, staff)
                        for m, c in stats["to_upload"]
                    ]
                    try:
                        ok, fail = run_sync_batch(sf_client, records)
                    except ApiLimitExceeded:
                        logger.warning("API limit reached, saving progress")
                        state = load_state(args.state)
                        state["last_rowid"] = max(state.get("last_rowid", 0), max_rowid)
                        state["last_sync_at"] = dt.datetime.now(tz=dt.timezone.utc).isoformat()
                        save_state(args.state, state)
                        return 0
                    batch_ok = ok
                    total_ok += ok
                    total_fail += fail
                    logger.info("Batch %d: upserted %d, failed %d", batches, ok, fail)

            state = load_state(args.state)
            state["last_rowid"] = max(state.get("last_rowid", 0), max_rowid)
            state["total_synced"] = int(state.get("total_synced", 0)) + batch_ok
            state["last_sync_at"] = dt.datetime.now(tz=dt.timezone.utc).isoformat()
            save_state(args.state, state)
            since_rowid = max_rowid

            if args.limit:
                break  # honour explicit --limit

        logger.info("Sync complete: %d upserted, %d failures across %d batches", total_ok, total_fail, batches)
        return 0 if total_fail == 0 else 2
    finally:
        conn.close()
        if temp_db and os.path.exists(temp_db):
            os.unlink(temp_db)


if __name__ == "__main__":
    if cli_mode_requested():
        sys.exit(main())
    run_menu_bar_app()
