#!/usr/bin/env python3
"""Export an existing Android App session using read-only ADB commands; never log in."""

import argparse
import datetime
import hashlib
import json
import os
import re
import shutil
import subprocess
from pathlib import Path

PACKAGE = "com.yunke.aioutbound"
LOG_ROOT = "/sdcard/.yunke_log"
LOG_DIR = LOG_ROOT + "/aioutbound"
DEFAULT_WINDOW = 2097152
MAX_WINDOW = 67108864
MAX_LOOKBACK_DAYS = 7
MARKERS = ("mAccountBean=", "json=")  # Phone-number login and App start, per the 2.0.33 APK
INVALIDATED = re.compile(r"token incorrect|[\"']?code[\"']?\s*[:=]\s*-10000\b", re.IGNORECASE)
STAMP = re.compile(r"(?:\d{4}-)?\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}")
UNVERIFIED = "Token validity and device online state are not verified."


class PairingError(Exception):
    """A fixed diagnostic safe to show without exposing phone logs or credentials."""

    def __init__(self, message, kind="error"):
        super().__init__(message)
        self.kind = kind


def record_marker(line):
    """The marker that makes this line an account record, or None. Only AccountManage writes them."""
    return next((marker for marker in MARKERS if marker in line), None) if "AccountManage" in line else None


def account_lines(log):
    """Every account record in the text that was actually read."""
    return [line for line in log.splitlines() if record_marker(line)]


def record_time(line):
    """When the record was logged, read only from the text before its marker."""
    stamp = STAMP.search(line.split(record_marker(line))[0])
    return stamp.group(0) if stamp else None


def decode_record(line):
    """Parse only what follows the marker, so a bracket earlier in the line cannot mislead it."""
    marker = record_marker(line)
    return json.JSONDecoder().raw_decode(line[line.index(marker) + len(marker):].lstrip())[0]


def read_account(log):
    """Use the last account record, never fall back to an older valid-looking token."""
    lines = log.splitlines()
    records = [index for index, line in enumerate(lines) if record_marker(line)]
    if not records:
        raise PairingError("No existing account record was found. Do not log in again to generate one.", "no_record")
    if any(INVALIDATED.search(line) for line in lines[records[-1] + 1:]):
        raise PairingError("The log shows a session failure after the latest account record; it was not exported.", "invalidated")
    try:
        account = decode_record(lines[records[-1]])
    except (ValueError, TypeError):
        raise PairingError("The latest account record is unreadable; no older session was exported. "
                           "This App version may log it differently.", "unreadable") from None
    credentials = {}
    for source, target, limit in [("company", "company_code", 100), ("userId", "user_id", 100), ("token", "app_token", 4000)]:
        value = account.get(source) if isinstance(account, dict) else None
        if not isinstance(value, str) or not value or len(value) > limit or re.search(r"[\x00-\x20\x7f]", value):
            raise PairingError("The latest account record has no complete session. No session was exported.", "incomplete")
        credentials[target] = value
    if re.search(r"\*|\.\.\.|…", credentials["app_token"]):
        raise PairingError("The latest account record has a masked token. No session was exported.", "incomplete")
    if credentials["company_code"] == "personal":
        raise PairingError("The latest account record is the personal identity, not the enterprise. No session was exported.", "identity")
    return credentials


def adb_try(adb, args, timeout=15):
    """Run one read command and return (exit code, raw text). The text is classified, never shown."""
    try:
        result = subprocess.run([adb, *args], capture_output=True, text=True, encoding="utf-8",
                                errors="replace", timeout=timeout)
    except (OSError, subprocess.SubprocessError):
        raise PairingError("ADB read failed. Check the existing connection and ordinary file permissions; do not elevate access.") from None
    return result.returncode, (result.stdout or "") + (result.stderr or "")


def adb_read(adb, args, timeout=15):
    """Never return subprocess diagnostics that might include the session payload."""
    try:
        return subprocess.run([adb, *args], capture_output=True, text=True, encoding="utf-8", errors="replace",
                              check=True, timeout=timeout).stdout
    except (OSError, subprocess.SubprocessError):
        raise PairingError("ADB read failed. Check the existing connection and ordinary file permissions; do not elevate access.") from None


def select_serial(adb, serial):
    """Name each device state separately and never guess between phones."""
    rows = [parts for line in adb_read(adb, ["devices"]).splitlines() if len(parts := line.split()) == 2]
    ready = [row[0] for row in rows if row[1] == "device"]
    if serial in ready or (serial is None and len(ready) == 1):
        return serial or ready[0]
    if serial is None and len(ready) > 1:
        raise PairingError("Several phones are connected. Choose one with --serial.")
    states = {row[1] for row in rows}
    if "unauthorized" in states:
        raise PairingError("The phone has not authorized this computer. Accept the USB debugging prompt on the phone.")
    if "offline" in states:
        raise PairingError("The phone is offline to ADB. Reconnect it; do not change wireless debugging settings.")
    raise PairingError("Select one already authorized phone with --serial, or connect and authorize exactly one phone.")


def phone_date(adb, prefix):
    """The phone's own date names its log files; the computer's date may differ."""
    day = adb_read(adb, [*prefix, "shell", "date", "+%Y-%m-%d"]).strip()
    if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", day):
        raise PairingError("The phone date could not be read; no session was exported.")
    return day


def selected_day(today, requested):
    """Only an explicit recent date reaches the fixed log path; it is never a path or a future day."""
    if requested is None:
        return today
    try:
        if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", requested):
            raise ValueError
        age = (datetime.date.fromisoformat(today) - datetime.date.fromisoformat(requested)).days
    except ValueError:
        raise PairingError("--date must be a real date written YYYY-MM-DD.") from None
    if age < 0 or age > MAX_LOOKBACK_DAYS:
        raise PairingError(f"--date must be between today and {MAX_LOOKBACK_DAYS} days ago on the phone's clock.")
    return requested


def days_between(oldest, newest):
    """Log dates after `oldest` up to `newest`, newest first."""
    first = datetime.date.fromisoformat(oldest)
    span = (datetime.date.fromisoformat(newest) - first).days
    return [(first + datetime.timedelta(days=offset)).isoformat() for offset in range(span, 0, -1)]


def log_path(day):
    """The only file this helper reads the contents of."""
    return f"{LOG_DIR}/log_{day}"


def log_size(adb, prefix, day):
    """Tell a missing file from a permission failure, so neither is reported as an invalid token."""
    code, text = adb_try(adb, [*prefix, "shell", "stat", "-c", "%s", log_path(day)])
    if code == 0 and text.strip().isdigit():
        return int(text.strip())
    lowered = text.lower()
    if "no such file" in lowered:
        raise PairingError(f"log_{day} does not exist on the phone.", "missing")
    if "permission denied" in lowered:
        raise PairingError(f"log_{day} exists but ordinary ADB access is denied. Do not root or elevate.", "denied")
    raise PairingError("ADB read failed. Check the existing connection and ordinary file permissions; do not elevate access.")


def read_window(adb, prefix, day, size, window):
    """Read a bounded tail. Beyond the window the first line may be partial, so it is dropped."""
    log = adb_read(adb, [*prefix, "exec-out", "tail", "-c", str(window), log_path(day)], timeout=15 + window // 1048576)
    truncated = size > window
    if truncated:
        log = log.split("\n", 1)[1] if "\n" in log else ""
    return log, truncated


def app_version(adb, prefix):
    """The installed version, read rather than assumed. Older evidence is for App 2.0.20 only."""
    text = adb_read(adb, [*prefix, "shell", "dumpsys", "package", PACKAGE], timeout=30)
    name = re.search(r"versionName=(\S+)", text)
    code = re.search(r"versionCode=(\d+)", text)
    return (name.group(1) if name else None), (code.group(1) if code else None)


def refuse_newer_evidence(adb, prefix, day, today, window):
    """An older date is usable only if nothing newer replaces or invalidates it."""
    for later in days_between(day, today):
        try:
            size = log_size(adb, prefix, later)
        except PairingError as error:
            if error.kind == "missing":
                continue
            raise
        log, truncated = read_window(adb, prefix, later, size, window)
        if account_lines(log):
            raise PairingError(f"A newer account record exists in log_{later}. Export that date; the older session was not exported.", "newer")
        if INVALIDATED.search(log):
            raise PairingError(f"log_{later} shows a later session failure. The older session was not exported.", "invalidated")
        if truncated:
            raise PairingError(f"log_{later} is larger than the read window, so a newer record cannot be ruled out. "
                               f"Use a larger --max-bytes (limit {MAX_WINDOW}).", "window")


def export_session(adb, serial, output, day=None, window=DEFAULT_WINDOW):
    """Read one authorized device and one bounded log tail into an exclusive private file."""
    prefix = ["-s", select_serial(adb, serial)]
    today = phone_date(adb, prefix)
    day = selected_day(today, day)
    size = log_size(adb, prefix, day)
    log, truncated = read_window(adb, prefix, day, size, window)
    if truncated and not account_lines(log):
        raise PairingError(f"No account record in the last {window} bytes of log_{day}, which is larger. "
                           f"Use a larger --max-bytes (limit {MAX_WINDOW}). Do not log in again.", "window")
    credentials = read_account(log)
    refuse_newer_evidence(adb, prefix, day, today, window)
    name, code = app_version(adb, prefix)
    if name is None:
        raise PairingError(f"{PACKAGE} is not installed on this phone; no session was exported.")
    credentials.update({
        "captured_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
        "source": "existing App log", "source_log_date": day, "source_record_time": record_time(account_lines(log)[-1]),
        "app_version": name, "app_version_code": code, "validity": "unverified",
    })
    try:
        fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    except FileExistsError:
        raise PairingError("The output already exists. Remove the old pairing file or choose a new path; it was not overwritten.") from None
    except OSError:
        raise PairingError("The output file could not be created in the selected folder.") from None
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as handle:
            json.dump(credentials, handle, ensure_ascii=True)
            handle.write("\n")
    except OSError:
        Path(output).unlink(missing_ok=True)
        raise PairingError("The pairing file could not be written; its incomplete copy was removed.") from None
    return credentials


def masked(value):
    """Enough to compare with the saved identity by eye, without printing the identifier."""
    return f"{value[:2]}...{value[-2:]}" if len(value) >= 8 else "*" * len(value)


def names_in(adb, prefix, path):
    """Up to 20 plain file names in one fixed folder; contents are not read."""
    code, text = adb_try(adb, [*prefix, "shell", "ls", "-1", path])
    names = sorted(name for name in text.split() if re.fullmatch(r"[\w.\-]{1,64}", name))
    if code != 0:
        return "not readable" if "permission denied" in text.lower() else "not present"
    return ", ".join(names[-20:]) or "empty"


def describe_records(log):
    """Counts and shapes of the account records; identifiers masked, the token never shown."""
    accounts = []
    for line in account_lines(log):
        try:
            account = decode_record(line)
        except (ValueError, TypeError):
            continue
        if isinstance(account, dict):
            accounts.append(account)
    identities = {(str(item.get("company")), str(item.get("userId"))) for item in accounts}
    tokens = {str(item.get("token")) for item in accounts}
    summary = (f"records={len(account_lines(log))}, identities={len(identities)}, tokens={len(tokens)}, "
               f"last record at {record_time(account_lines(log)[-1]) or 'unknown time'}")
    try:
        found = read_account(log)
    except PairingError as error:
        fields = sorted(accounts[-1]) if accounts else []
        return f"{summary}\n  not exportable ({error.kind}): {error}\n  last record fields: {', '.join(fields[:40]) or 'not JSON'}", False
    return (f"{summary}\n  exportable: company={masked(found['company_code'])}, user={masked(found['user_id'])}, "
            f"token length {len(found['app_token'])}"), True


def pull_apk(adb, prefix, folder):
    """Copy the installed APK for offline reading; never reinstall or change it."""
    remote = [line[len("package:"):].strip() for line in adb_read(adb, [*prefix, "shell", "pm", "path", PACKAGE]).splitlines()
              if line.startswith("package:")]
    if not remote or not all(re.fullmatch(r"/data/app/[\w~=.+\-/]+\.apk", path) for path in remote):
        raise PairingError("The installed APK path could not be read.")
    Path(folder).mkdir(parents=True, exist_ok=True)
    lines = []
    for path in remote:
        target = Path(folder) / Path(path).name
        if target.exists():
            raise PairingError(f"{target.name} already exists in that folder; it was not overwritten.")
        adb_read(adb, [*prefix, "pull", path, str(target)], timeout=600)
        digest = hashlib.sha256(target.read_bytes()).hexdigest()
        lines.append(f"apk: {target.name}, {target.stat().st_size} bytes, sha256 {digest}")
    return lines


def inspect_phone(adb, serial, window=DEFAULT_WINDOW, apk_folder=None):
    """Report what the phone holds without writing a session file. Stops at the newest record."""
    prefix = ["-s", select_serial(adb, serial)]
    today = phone_date(adb, prefix)
    name, code = app_version(adb, prefix)
    report = ["Yunke phone report (contains no token or Cookie)", f"package: {PACKAGE}",
              f"app version: {name or 'NOT INSTALLED'} (code {code or 'unknown'})", f"phone date: {today}",
              f"folders in {LOG_ROOT}: {names_in(adb, prefix, LOG_ROOT)}", f"files in {LOG_DIR}: {names_in(adb, prefix, LOG_DIR)}"]
    oldest = (datetime.date.fromisoformat(today) - datetime.timedelta(days=MAX_LOOKBACK_DAYS + 1)).isoformat()
    next_step = f"No account record in the last {MAX_LOOKBACK_DAYS} days. Do not log in again; send this report to the integrator."
    for day in days_between(oldest, today):
        try:
            size = log_size(adb, prefix, day)
        except PairingError as error:
            report.append(f"log_{day}: {error}")
            if error.kind == "missing":
                continue
            next_step = "Stop here. Do not root or elevate; send this report to the integrator."
            break
        log, truncated = read_window(adb, prefix, day, size, window)
        heading = f"log_{day}: {size} bytes, read window {window}, truncated={'yes' if truncated else 'no'}"
        if account_lines(log):
            detail, exportable = describe_records(log)
            report.append(f"{heading}, {detail}")
            date_option = "" if day == today else f"--date {day} "
            next_step = (f"Next: python3 yunke-pair-phone.py {date_option}--output yunke-phone-pairing.json" if exportable
                         else "Stop here. No older record is used; send this report to the integrator.")
            break
        report.append(f"{heading}, no account record in the read window")
        if truncated:
            next_step = f"Run again with a larger --max-bytes (limit {MAX_WINDOW}). Do not log in again."
            break
    if apk_folder:
        report.extend(pull_apk(adb, prefix, apk_folder))
    return report + [next_step, UNVERIFIED]


def main():
    """No vendor HTTP, App launch, retry, login, device setting or phone write exists here."""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--adb", default=shutil.which("adb"), help="Path to an existing adb executable")
    parser.add_argument("--serial", help="An already authorized device from adb devices")
    parser.add_argument("--output", help="New private JSON file; never overwrite an existing file")
    parser.add_argument("--date", help=f"Existing log date YYYY-MM-DD, up to {MAX_LOOKBACK_DAYS} days back; refused if a newer record exists")
    parser.add_argument("--max-bytes", type=int, default=DEFAULT_WINDOW, help=f"Bytes to read from the end of a log (limit {MAX_WINDOW})")
    parser.add_argument("--inspect", action="store_true", help="Print a report with no secrets and write no session file")
    parser.add_argument("--pull-apk", metavar="FOLDER", help="With --inspect: copy the installed APK to a private folder and print its hash")
    args = parser.parse_args()
    if not args.adb:
        parser.exit(1, "ADB was not found. Supply --adb with its existing path.\n")
    if not 1024 <= args.max_bytes <= MAX_WINDOW:
        parser.error(f"--max-bytes must be between 1024 and {MAX_WINDOW}")
    if args.inspect == bool(args.output) or (args.pull_apk and not args.inspect) or (args.date and args.inspect):
        parser.error("use either --inspect [--pull-apk FOLDER] or --output FILE [--date YYYY-MM-DD]")
    try:
        if args.inspect:
            print("\n".join(inspect_phone(args.adb, args.serial, args.max_bytes, args.pull_apk)))
            return
        saved = export_session(args.adb, args.serial, args.output, args.date, args.max_bytes)
    except PairingError as error:
        parser.exit(1, str(error) + "\n")
    print(f"Pairing file saved from log_{saved['source_log_date']} (record time {saved['source_record_time'] or 'unknown'}, "
          f"App {saved['app_version']}). Import it in Yunke management, then delete the local file. {UNVERIFIED}")


if __name__ == "__main__":
    main()
