"""Harness entrypoint for web-act user scripts (invoked only by run_web_script)."""
from __future__ import annotations

import os
import runpy
import sys
import tempfile
import traceback


def _real(path: str) -> str:
    return os.path.realpath(os.path.abspath(os.path.expanduser(path)))


def _system_read_prefixes() -> tuple[str, ...]:
    """OS catalog dirs Playwright / mimetypes read (read-only, no writes)."""
    candidates = (
        "/etc",
        "/private/etc",
        "/usr/share/mime",
        "/usr/share/misc",
    )
    out: list[str] = []
    seen: set[str] = set()
    for raw in candidates:
        if not os.path.exists(raw):
            continue
        try:
            p = _real(raw)
        except OSError:
            continue
        if p in seen:
            continue
        seen.add(p)
        out.append(p)
    return tuple(out)


def _sandbox_bootstrap(run_cwd: str, workspace_root: str) -> str:
    run_repr = repr(_real(run_cwd))
    ws_repr = repr(_real(workspace_root) if workspace_root else run_cwd)
    tmp_repr = repr(_real(tempfile.gettempdir()))
    sys_read = _system_read_prefixes()
    sys_read_repr = "(" + ", ".join(repr(p) for p in sys_read) + ")" if sys_read else "()"
    return f"""import os as _os
import sys as _sys
import builtins as _builtins
import shutil as _sh
_RUN_CWD = {run_repr}
_WS_ROOT = {ws_repr}
_TMP = {tmp_repr}
_SYS_READ = {sys_read_repr}
_WRITE_PREFIXES = (_RUN_CWD, _TMP)
_READ_PREFIXES = (_RUN_CWD, _WS_ROOT, _TMP, _sys.prefix) + _SYS_READ
_real_open = open
def _sandbox_open(path, mode="r", *a, **k):
    if isinstance(path, int):
        return _real_open(path, mode, *a, **k)
    path_str = _os.fspath(path) if not isinstance(path, str) else path
    path_abs = _os.path.realpath(_os.path.normpath(_os.path.abspath(_os.path.expanduser(path_str))))
    if any(m in mode for m in ("w", "a", "x")):
        if not any(path_abs == p or path_abs.startswith(p + _os.sep) for p in _WRITE_PREFIXES):
            raise OSError("Write blocked outside run cwd and temp: " + path_abs)
    elif not any(path_abs == p or path_abs.startswith(p + _os.sep) for p in _READ_PREFIXES):
        raise OSError("Read blocked outside workspace/run cwd/temp: " + path_abs)
    return _real_open(path, mode, *a, **k)
open = _sandbox_open
_builtins.open = _sandbox_open
def _guard_path(path):
    p = _os.path.realpath(_os.path.abspath(_os.path.expanduser(_os.fspath(path))))
    if not any(p == root or p.startswith(root + _os.sep) for root in _WRITE_PREFIXES):
        raise OSError("Path mutation blocked outside run cwd: " + p)
    return p
def _blocked_rmtree(*a, **k):
    if a:
        _guard_path(a[0])
    return _sh._orig_rmtree(*a, **k)
def _blocked_remove(*a, **k):
    if a:
        _guard_path(a[0])
    return _os._orig_remove(*a, **k)
_sh._orig_rmtree = _sh.rmtree
_os._orig_remove = _os.remove
_sh.rmtree = _blocked_rmtree
_os.remove = _blocked_remove
"""


def _run_with_bootstrap(script_abs: str, run_cwd: str, allowed_root: str) -> int:
    ws_root = allowed_root or os.path.dirname(run_cwd)
    bootstrap = _sandbox_bootstrap(run_cwd, ws_root)
    with open(script_abs, "r", encoding="utf-8") as f:
        user_code = f.read()
    namespace: dict = {"__name__": "__main__", "__file__": script_abs}
    try:
        exec(compile(bootstrap + user_code, script_abs, "exec"), namespace)
        return 0
    except SystemExit as exc:
        code = exc.code
        if code is None:
            return 0
        if isinstance(code, int):
            return code
        return 1


def main(argv: list[str] | None = None) -> int:
    args = list(argv or sys.argv[1:])
    if len(args) < 1:
        print("usage: web_act_entry <script_abs> [run_cwd]", file=sys.stderr)
        return 2
    script_abs = _real(args[0])
    run_cwd = _real(args[1]) if len(args) > 1 else os.path.dirname(script_abs)
    allowed_root = os.environ.get("MUGI_WEB_ACT_ROOT", "").strip()
    if allowed_root:
        root = _real(allowed_root)
        if not script_abs.startswith(root + os.sep) and script_abs != root:
            print(f"Refused: script outside web-act root ({root})", file=sys.stderr)
            return 2
        if not run_cwd.startswith(root + os.sep) and run_cwd != root:
            print(f"Refused: cwd outside web-act root ({root})", file=sys.stderr)
            return 2
    if not os.path.isfile(script_abs):
        print(f"Script not found: {script_abs}", file=sys.stderr)
        return 2
    try:
        os.chdir(run_cwd)
    except OSError as exc:
        print(f"Cannot chdir to {run_cwd}: {exc}", file=sys.stderr)
        return 2
    try:
        return _run_with_bootstrap(script_abs, run_cwd, allowed_root)
    except Exception:
        traceback.print_exc()
        return 1


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