import json
import os
import subprocess
from pathlib import Path


REPO_ROOT = Path(__file__).resolve().parents[1]
SCRIPT = REPO_ROOT / "scripts/openbao-apply-operator-loopback-callback.sh"
CALLBACK = "http://127.0.0.1:18200/ui/vault/auth/netkingdom/oidc/callback"


def _fake_bao(tmp_path: Path) -> tuple[Path, Path]:
    capture = tmp_path / "written-role.json"
    executable = tmp_path / "bao"
    executable.write_text(
        """#!/bin/sh
set -eu
if [ "$1" = "write" ]; then
  cp "${3#@}" "$BAO_CAPTURE"
  exit 0
fi
if [ "$1" = "read" ]; then
  if [ "${BAO_FAKE_MISSING_CALLBACK:-false}" = "true" ]; then
    printf '%s\\n' '{"data":{"role_type":"oidc","token_policies":["platform-admin"],"allowed_redirect_uris":[]}}'
  else
    printf '%s\\n' '{"data":{"role_type":"oidc","token_policies":["platform-admin"],"allowed_redirect_uris":["http://127.0.0.1:18200/ui/vault/auth/netkingdom/oidc/callback"]}}'
  fi
  exit 0
fi
exit 2
""",
        encoding="utf-8",
    )
    executable.chmod(0o755)
    return executable, capture


def _run(tmp_path: Path, *, missing_callback: bool = False) -> tuple[subprocess.CompletedProcess[str], Path]:
    _, capture = _fake_bao(tmp_path)
    env = dict(os.environ)
    env.update(
        {
            "PATH": f"{tmp_path}:{env['PATH']}",
            "TMPDIR": str(tmp_path),
            "BAO_CAPTURE": str(capture),
            "BAO_FAKE_MISSING_CALLBACK": str(missing_callback).lower(),
        }
    )
    result = subprocess.run(
        [str(SCRIPT)],
        cwd=REPO_ROOT,
        env=env,
        text=True,
        capture_output=True,
        check=False,
    )
    return result, capture


def test_contained_command_is_silent_and_writes_exact_role(tmp_path: Path) -> None:
    result, capture = _run(tmp_path)
    assert result.returncode == 0
    assert result.stdout == ""
    assert result.stderr == ""

    role = json.loads(capture.read_text(encoding="utf-8"))
    assert CALLBACK in role["allowed_redirect_uris"]
    assert role["policies"] == ["platform-admin"]
    assert role["bound_claims"] == {"groups": ["net-kingdom-admins"]}
    assert not list(tmp_path.glob("openbao-platform-admin-*.json"))


def test_verification_failure_remains_silent_and_nonzero(tmp_path: Path) -> None:
    result, _ = _run(tmp_path, missing_callback=True)
    assert result.returncode != 0
    assert result.stdout == ""
    assert result.stderr == ""
    assert not list(tmp_path.glob("openbao-platform-admin-*.json"))
