"""Network-isolated executable for the sealed NutriCoach v1.5 transaction."""

from __future__ import annotations

import argparse
import os
import subprocess
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))


def sandbox_command(approval: str) -> tuple[str, ...]:
    """Return the unconditional narrow Bubblewrap command."""
    profile = "/home/cube/.hermes/profiles/dualcoachtest"
    systemd = "/home/cube/.config/systemd/user"
    migration = "/home/cube/.hermes/migrations/nutricoach-v1.5.0-combined"
    authority = (
        "/home/cube/.hermes/runtime-authority/"
        + "dualcoach-v1.3.0-owner-risk-first-customer"
    )
    credentials = (
        "/home/cube/.hermes/runtime-authority/"
        + "dualcoach-v1.3.2-daily-checkin-rebound-first-customer-credentials"
    )
    bootstrap = (
        migration
        + "/live-transaction-preseal-v15-runtime-authority-r71b-maintenance/"
        + "controller-source/scripts/nutricoach_v150_detached_bootstrap.py"
    )
    return (
        "/usr/bin/bwrap",
        "--unshare-net",
        "--die-with-parent",
        "--clearenv",
        "--ro-bind",
        "/",
        "/",
        "--tmpfs",
        "/tmp",
        "--dev",
        "/dev",
        "--bind",
        profile,
        profile,
        "--bind",
        systemd,
        systemd,
        "--bind",
        migration,
        migration,
        "--bind",
        authority,
        authority,
        "--bind",
        credentials,
        credentials,
        "--setenv",
        "PATH",
        "/usr/bin:/bin",
        "--setenv",
        "XDG_RUNTIME_DIR",
        f"/run/user/{os.getuid()}",
        sys.executable,
        bootstrap,
        "--approval",
        approval,
    )


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    _ = parser.add_argument("--approval", required=True)
    _ = parser.parse_args()
    approval = sys.argv[sys.argv.index("--approval") + 1]
    result = subprocess.run(sandbox_command(approval), check=False)
    return result.returncode


if __name__ == "__main__":
    raise SystemExit(main())
