#!/usr/bin/env python3
"""savi-claude <agent> [claude args...]

Start a Claude session in an agent's folder, from a terminal, as that agent:
its connector secrets are handed to the session from the installation's
encrypted store, so a workspace .mcp.json's ${VAR} references resolve.  The
session keeps its Claude sign-in in a folder of its own, so the installation's
own sign-in is never shared or changed (services/terminal_session.py).

    savi-claude <agent>             work as the agent
    savi-claude <agent> --continue  any claude option passes straight through

It runs only as the account this installation runs under, because only
that account can open the store.  Started as any other account, it says so,
names the account, and starts nothing.

This file uses the standard library alone and imports nothing from the
product, so it runs the same way on every build, the encrypted one included:
after its check it hands over to savi_claude.py in the product folder, under
the interpreter the installation itself runs on, and that entry point loads
the product the way the build needs.

Install:  the installation drops this at <store>/bin/savi-claude with its own
folders, interpreter and account written in (services/provisioning.py
install_launcher).  Put that folder on PATH, or call it by full path.
"""
from __future__ import annotations

import os
import sys

# Written in by install_launcher;  left as placeholders when this file is run
# straight from the product folder, and then found the way the product finds
# them.
_STAMPED_PRODUCT = "__SAVI_COMMS_PRODUCT_DIR__"
_STAMPED_STORE = "__SAVI_COMMS_STORE_DIR__"
_STAMPED_PYTHON = "__SAVI_COMMS_PYTHON__"
_STAMPED_ACCOUNT = "__SAVI_COMMS_ACCOUNT__"

ENTRY = "savi_claude.py"

WRONG_ACCOUNT = ("savi-claude runs only as {owner}, the account this installation runs "
                 "under, and this terminal is signed in as {me}.  Nothing was started.  "
                 "Sign in to this computer as {owner} and run it again.")
NO_REACH = ("savi-claude runs only as {owner}, the account this installation runs "
            "under, and this terminal's account, {me}, cannot open the installation's "
            "store at {store}.  Nothing was started.  Sign in to this computer as {owner} "
            "and run it again.")
NO_STORE = ("savi-claude runs only as {owner}, the account this installation runs under.  "
            "This terminal's account, {me}, has no installation:  there is no store at "
            "{store}.  Nothing was started.  Sign in to this computer as {owner} and run "
            "it again.")
UNKNOWN_OWNER = "the account the installation runs under"
NO_ENTRY = ("the product folder {product} has no {entry}, so the session cannot start.  "
            "Unpack the full release again.")


def _stamped(value: str) -> str:
    return "" if value.startswith("__") else value


def product_dir() -> str:
    return (os.environ.get("SAVI_COMMS_DAEMON_DIR") or _stamped(_STAMPED_PRODUCT)
            or os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


def store_dir() -> str:
    """The installation's store.  Unstamped, the same order the product and its
    gate shim use:  SAVI_COMMS_ROOT, then the per-account pointer file, then
    ~/.savi-comms (config.resolve_store_root is the product's own copy;  this
    one is kept to the standard library so it runs before the product loads)."""
    named = os.environ.get("SAVI_COMMS_ROOT") or _stamped(_STAMPED_STORE)
    if named:
        return os.path.abspath(os.path.expanduser(named))
    pointer = os.path.join(os.environ.get("XDG_CONFIG_HOME")
                           or os.path.expanduser("~/.config"), "savi-comms", "store")
    try:
        with open(pointer, encoding="utf-8") as f:
            line = f.readline().strip()
    except OSError:
        line = ""
    if line:
        return os.path.normpath(os.path.join(os.path.dirname(pointer),
                                             os.path.expanduser(line)))
    return os.path.expanduser("~/.savi-comms")


def _name_of(uid: int) -> str:
    try:
        import pwd
        return pwd.getpwuid(uid).pw_name
    except (ImportError, KeyError):
        return f"user id {uid}"


def refusal(store: str) -> str:
    """Why this account may not start a session, or "" when it may."""
    me = _name_of(os.geteuid())
    owner = _stamped(_STAMPED_ACCOUNT)
    try:
        st = os.stat(store)
    except FileNotFoundError:
        return NO_STORE.format(owner=owner or UNKNOWN_OWNER, me=me, store=store)
    except OSError:
        return NO_REACH.format(owner=owner or UNKNOWN_OWNER, me=me, store=store)
    if st.st_uid != os.geteuid():
        return WRONG_ACCOUNT.format(owner=_name_of(st.st_uid), me=me)
    if not os.access(store, os.R_OK | os.X_OK):
        return NO_REACH.format(owner=owner or _name_of(st.st_uid), me=me, store=store)
    return ""


def main(argv) -> int:
    if not argv or argv[0] in ("-h", "--help"):
        print(__doc__)
        return 2
    store = store_dir()
    why = refusal(store)
    if why:
        print(why, file=sys.stderr)
        return 2
    product = product_dir()
    entry = os.path.join(product, ENTRY)
    if not os.path.isfile(entry):
        print("savi-claude:  " + NO_ENTRY.format(product=product, entry=ENTRY), file=sys.stderr)
        return 2
    python = _stamped(_STAMPED_PYTHON) or sys.executable
    env = dict(os.environ)
    env["SAVI_COMMS_ROOT"] = store
    os.execve(python, [python, entry, *argv], env)
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
