#!/usr/bin/env python3
"""Pre-flight gate for the pusher / watcher (A5 incident 2026-11-07, host 62614 item 2).

A5 failed every cycle with `login_failed` because `workshop/profiles/.google-pw` was
missing entirely (restored 14:47 from a package copy). The rule now is:

    BEFORE the watcher does anything, verify the password file that the program itself
    will read: it must EXIST, be a regular file, be readable, and have size > 0.
    If not -> report loudly (one line + pointer), DO NOT run, DO NOT silently fail-closed
    every cycle.

Drop-in usage (watcher r13 and the copy inside 新手包 must both call this):

    from preflight_google_pw import require_password_file
    PW = require_password_file()          # raises SystemExit(2) with a loud message

    # or, when you want to keep running other checks first:
    require_password_file(PW_PATH, fatal=False)   # returns (ok, message)

The function never prints the file's contents, only its path and size (S0 hard safety).
"""
from __future__ import annotations

import os
import stat
import sys

# Absolute-first, in the same order the watcher's own _locate_pw_file() probes.
# Never rely on cwd: a relative default silently checks the wrong file.
CANDIDATES = [
    os.environ.get("WATCHER_GOOGLE_PW_FILE") or os.environ.get("GOOGLE_PW_PATH") or "",
    (os.path.join(os.environ["WATCHER_SEED_PROFILES_DIR"], ".google-pw")
     if os.environ.get("WATCHER_SEED_PROFILES_DIR") else ""),
    os.path.expanduser("~/workspace/workshop/profiles/.google-pw"),
    os.path.expanduser("~/workspace/workshop/.google-pw"),
    "/root/profiles/.google-pw",
    "workshop/profiles/.google-pw",   # last resort only
]
CANDIDATES = [c for c in CANDIDATES if c]
DEFAULT_PATH = os.environ.get("GOOGLE_PW_PATH") or CANDIDATES[0]


def resolve_password_path(candidates=None):
    """First EXISTING candidate, else the primary one.

    Probes defensively: an unreadable directory (e.g. /root as a normal user)
    must be treated as "not there", never allowed to raise and turn a loud
    fail-closed gate into a bare traceback.
    """
    cands = list(candidates or CANDIDATES)
    for c in cands:
        try:
            if os.path.exists(os.path.expanduser(c)):
                return os.path.expanduser(c)
        except OSError:
            continue
    return cands[0]


def require_password_file(path: str = DEFAULT_PATH, fatal: bool = True):
    """Verify the credential file the watcher will actually read.

    Returns (ok: bool, message: str). On failure with fatal=True the process exits
    with status 2 BEFORE any network/browser work, after emitting ONE loud line.
    """
    p = os.path.abspath(os.path.expanduser(path))
    problems = []

    if not os.path.exists(p):
        problems.append("MISSING")
    elif os.path.islink(p):
        problems.append("IS_SYMLINK")
    else:
        try:
            st = os.stat(p)
        except OSError as e:
            problems.append("STAT_ERROR:%s" % e.__class__.__name__)
            st = None
        if st is not None:
            if not stat.S_ISREG(st.st_mode):
                problems.append("NOT_REGULAR")
            if st.st_size <= 0:
                problems.append("EMPTY(size=0)")
            if not os.access(p, os.R_OK):
                problems.append("NOT_READABLE")
            if st.st_uid != os.getuid():
                problems.append("OWNER_MISMATCH(uid=%d)" % st.st_uid)
            # the watcher's own reader demands EXACTLY 0600; anything else is a
            # silent fail-closed loop later, so block here instead
            mode = stat.S_IMODE(st.st_mode)
            if mode != 0o600:
                problems.append("MODE_NOT_600(mode=%s)" % oct(mode))

    if problems:
        msg = ("PREFLIGHT_FAIL: password file unusable [%s] path=%s "
               "-> watcher must NOT start; ask the owner for the file (host 62614 item 2)"
               % (",".join(problems), p))
        # ONE line, no content, no secret material
        print(msg, file=sys.stderr, flush=True)
        if fatal:
            raise SystemExit(2)
        return False, msg

    size = os.stat(p).st_size
    msg = "PREFLIGHT_OK: password file present path=%s size=%dB" % (p, size)
    print(msg, flush=True)
    return True, msg


def selftest() -> int:
    """Self-check with a temp dir: missing / empty / symlink / good / mode0644 / resolver."""
    import tempfile

    failures = []
    with tempfile.TemporaryDirectory() as d:
        missing = os.path.join(d, "nope")
        ok, m = require_password_file(missing, fatal=False)
        if ok or "MISSING" not in m:
            failures.append("missing not detected")

        empty = os.path.join(d, "empty")
        open(empty, "w").close()
        ok, m = require_password_file(empty, fatal=False)
        if ok or "EMPTY" not in m:
            failures.append("empty not detected")

        good = os.path.join(d, "good")
        with open(good, "w") as f:
            f.write("placeholder-not-a-real-secret\n")
        os.chmod(good, 0o600)
        ok, m = require_password_file(good, fatal=False)
        if not ok:
            failures.append("good file rejected: " + m)

        loose = os.path.join(d, "loose")
        with open(loose, "w") as f:
            f.write("placeholder-not-a-real-secret\n")
        os.chmod(loose, 0o644)
        ok, m = require_password_file(loose, fatal=False)
        if ok or "MODE_NOT_600" not in m:
            failures.append("mode 0644 not detected")

        # probe must not raise on an unreadable/absent tree
        if resolve_password_path([os.path.join(d, "nope"), "/root/profiles/.google-pw"]) != os.path.join(d, "nope"):
            failures.append("resolve_password_path fallback wrong")

        link = os.path.join(d, "link")
        os.symlink(good, link)
        ok, m = require_password_file(link, fatal=False)
        if ok or "IS_SYMLINK" not in m:
            failures.append("symlink not detected")

    if failures:
        print("SELFTEST_FAIL: " + "; ".join(failures), file=sys.stderr)
        return 1
    print("SELFTEST_PASS 6/6 (missing, empty, symlink, good, mode0644, resolver)")
    return 0


if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "--selftest":
        raise SystemExit(selftest())
    require_password_file(sys.argv[1] if len(sys.argv) > 1 else DEFAULT_PATH)
