"""Synthetic logs and mocked ADB only; no phone or vendor connection."""

import importlib.util
import json
import os
from pathlib import Path
import stat
import subprocess
import tempfile
import unittest
from unittest.mock import patch

spec = importlib.util.spec_from_file_location("pair_phone", Path(__file__).parents[1] / "yunke-pair-phone.py")
helper = importlib.util.module_from_spec(spec)
spec.loader.exec_module(helper)
ACCOUNT = {"company": "synthetic-company", "userId": "synthetic-user", "token": "private-token"}
LOG = "11-05 10:00:00 AccountManage mAccountBean=" + json.dumps(ACCOUNT)
TODAY, YESTERDAY = "2026-11-05", "2026-11-04"
READ_ONLY = {("devices",), ("shell", "date"), ("shell", "stat"), ("exec-out", "tail"), ("shell", "dumpsys"),
             ("shell", "ls"), ("shell", "pm"), ("pull",)}


class FakePhone:
    """Answers only read commands. A log value of DENIED simulates an ordinary permission failure."""
    DENIED = object()

    def __init__(self, logs, devices="phone\tdevice"):
        self.logs, self.devices, self.calls = logs, devices, []

    def __call__(self, command, **kwargs):
        args = command[3:] if command[1] == "-s" else command[1:]
        self.calls.append(args)
        if not (tuple(args[:1]) in READ_ONLY or tuple(args[:2]) in READ_ONLY):
            raise AssertionError(f"Unexpected ADB command: {args}")
        return subprocess.CompletedProcess(command, *self.answer(args), "")

    def answer(self, args):
        if args[0] == "devices":
            return 0, f"List of devices attached\n{self.devices}\n"
        if args[:2] == ["shell", "date"]:
            return 0, TODAY + "\n"
        if args[:2] == ["shell", "dumpsys"]:
            return 0, "    versionCode=20033 minSdk=26\n    versionName=2.0.33\n"
        if args[:2] == ["shell", "ls"]:
            return 0, "aioutbound\nlog_2026-11-04\n"
        log = self.logs.get(args[-1].rsplit("log_", 1)[-1])
        if args[:2] == ["shell", "stat"]:
            if log is self.DENIED:
                return 1, "stat: Permission denied"
            return (1, "stat: No such file or directory") if log is None else (0, f"{len(log)}\n")
        return 0, log[-int(args[3]):]


def run_with(phone):
    return patch.object(helper.subprocess, "run", side_effect=phone)


class PhonePairingTest(unittest.TestCase):
    def export(self, phone, **options):
        with tempfile.TemporaryDirectory() as folder, run_with(phone):
            output = Path(folder) / "pairing.json"
            try:
                helper.export_session("adb", None, output, **options)
            except helper.PairingError:
                self.assertFalse(output.exists(), "a refused export must leave no file")
                raise
            if os.name == "posix":
                self.assertEqual(stat.S_IMODE(output.stat().st_mode), 0o600)
            return json.loads(output.read_text())

    def test_export_writes_a_minimal_file_with_its_source_and_never_the_full_record(self):
        record = dict(ACCOUNT, extra="not-exported")
        data = self.export(FakePhone({TODAY: "11-05 10:00:00 AccountManage mAccountBean=" + json.dumps(record)}))
        self.assertEqual(data["app_token"], ACCOUNT["token"])
        self.assertEqual((data["source_log_date"], data["source_record_time"], data["app_version"], data["validity"]),
                         (TODAY, "11-05 10:00:00", "2.0.33", "unverified"))
        self.assertNotIn("not-exported", json.dumps(data))

    def test_the_app_2_0_33_record_format_exports_only_the_session(self):
        record = dict(ACCOUNT, companyName="", headUrl="", name="x", phone="00000000000")
        log = "11-05 10:00:00.123 【AccountManage】: init   json=" + json.dumps(record, separators=(",", ":")) + " "
        data = self.export(FakePhone({TODAY: log}))
        self.assertEqual((data["app_token"], data["source_record_time"]), (ACCOUNT["token"], "11-05 10:00:00"))
        self.assertNotIn("00000000000", json.dumps(data))

    def test_todays_missing_log_never_falls_back_but_an_explicit_recent_date_can_be_chosen(self):
        phone = FakePhone({YESTERDAY: LOG})
        with self.assertRaises(helper.PairingError) as error:
            self.export(phone)
        self.assertEqual(error.exception.kind, "missing")
        self.assertEqual(self.export(FakePhone({YESTERDAY: LOG}), day=YESTERDAY)["source_log_date"], YESTERDAY)

    def test_an_older_date_is_refused_when_a_newer_record_or_failure_exists(self):
        for today_log, kind in [(LOG, "newer"), ("11-05 09:00:00 reply code=-10000 token incorrect", "invalidated")]:
            with self.subTest(kind=kind), self.assertRaises(helper.PairingError) as error:
                self.export(FakePhone({YESTERDAY: LOG, TODAY: today_log}), day=YESTERDAY)
            self.assertEqual(error.exception.kind, kind)

    def test_a_date_can_only_be_a_recent_past_date_and_never_a_path(self):
        for bad in ["../../secrets", "2026-11-06", "2026-10-01", "2026-13-40", "2026-11-05; ls"]:
            phone = FakePhone({TODAY: LOG})
            with self.subTest(date=bad), self.assertRaises(helper.PairingError):
                self.export(phone, day=bad)
            self.assertFalse([call for call in phone.calls if call[:2] == ["exec-out", "tail"]])

    def test_a_permission_failure_is_named_as_such(self):
        with self.assertRaises(helper.PairingError) as error:
            self.export(FakePhone({TODAY: FakePhone.DENIED}))
        self.assertEqual(error.exception.kind, "denied")

    def test_a_record_before_the_read_window_asks_for_a_wider_window(self):
        log = LOG + "\n" + "x" * 3000
        with self.assertRaises(helper.PairingError) as error:
            self.export(FakePhone({TODAY: log}), window=2000)
        self.assertEqual(error.exception.kind, "window")
        self.assertEqual(self.export(FakePhone({TODAY: log}), window=8000)["app_token"], ACCOUNT["token"])

    def test_a_record_cut_by_the_read_window_is_not_mistaken_for_a_broken_one(self):
        log = LOG + "\n" + "x" * 500
        with self.assertRaises(helper.PairingError) as error:
            self.export(FakePhone({TODAY: log}), window=len(log) - 5)
        self.assertEqual(error.exception.kind, "window")

    def test_a_bad_latest_record_never_exports_an_older_token(self):
        cases = {"no_record": "unrelated log", "incomplete": LOG + "\nAccountManage mAccountBean=null",
                 "unreadable": LOG + "\nAccountManage mAccountBean={broken",
                 "identity": LOG + "\nAccountManage mAccountBean=" + json.dumps({**ACCOUNT, "company": "personal"}),
                 "invalidated": LOG + "\nreply token incorrect"}
        for token in ["bad\nheader", "abc***xyz"]:
            cases[f"incomplete:{token}"] = LOG + "\nAccountManage mAccountBean=" + json.dumps({**ACCOUNT, "token": token})
        for expected, log in cases.items():
            with self.subTest(log=log), self.assertRaises(helper.PairingError) as error:
                helper.read_account(log)
            self.assertEqual(error.exception.kind, expected.split(":")[0])
            self.assertNotIn(ACCOUNT["token"], str(error.exception))

    def test_a_bracket_before_the_marker_cannot_redirect_the_parser(self):
        line = '{"noise":1} AccountManage mAccountBean=' + json.dumps(ACCOUNT)
        self.assertEqual(helper.read_account(line)["company_code"], ACCOUNT["company"])

    def test_inspect_shows_no_secret_stops_at_the_newest_record_and_names_the_next_command(self):
        older = "2026-11-03"
        phone = FakePhone({YESTERDAY: LOG, older: LOG})
        with run_with(phone):
            report = "\n".join(helper.inspect_phone("adb", None))
        for secret in ACCOUNT.values():
            self.assertNotIn(secret, report)
        self.assertIn("2.0.33 (code 20033)", report)
        self.assertIn(f"--date {YESTERDAY} --output", report)
        self.assertFalse([call for call in phone.calls if call[-1].endswith(older)])

    def test_inspect_does_not_recommend_export_when_the_newest_record_is_unusable(self):
        with run_with(FakePhone({TODAY: "AccountManage mAccountBean={broken", YESTERDAY: LOG})):
            report = "\n".join(helper.inspect_phone("adb", None))
        self.assertIn("not exportable (unreadable)", report)
        self.assertNotIn("--output", report)

    def test_each_device_state_is_named_and_phones_are_never_guessed(self):
        for devices, phrase in [("a\tdevice\nb\tdevice", "--serial"), ("a\tunauthorized", "USB debugging"),
                                ("a\toffline", "offline"), ("", "authorize exactly one")]:
            with self.subTest(devices=devices), run_with(FakePhone({}, devices)), self.assertRaises(helper.PairingError) as error:
                helper.select_serial("adb", None)
            self.assertIn(phrase, str(error.exception))

    def test_an_adb_failure_exposes_no_diagnostics(self):
        with patch.object(helper.subprocess, "run", side_effect=subprocess.CalledProcessError(
                1, ["adb"], output=LOG, stderr=ACCOUNT["token"])):
            with self.assertRaises(helper.PairingError) as error:
                helper.adb_read("adb", ["devices"])
            self.assertNotIn(ACCOUNT["token"], str(error.exception))

    def test_existing_output_is_not_overwritten(self):
        with tempfile.TemporaryDirectory() as folder, run_with(FakePhone({TODAY: LOG})):
            output = Path(folder) / "pairing.json"
            output.write_text("existing")
            with self.assertRaises(helper.PairingError):
                helper.export_session("adb", None, output)
            self.assertEqual(output.read_text(), "existing")


if __name__ == "__main__":
    unittest.main()
