"""Tests for safe Telegram agent token installation."""

import json
import os
import stat
import subprocess
import sys
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]
SCRIPT = REPO_ROOT / "scripts" / "install_telegram_agent_token.py"


def run_installer(args: list[str], *, token: str = "123456789:abcdefghijklmnopqrstuvwxyzABC") -> subprocess.CompletedProcess:
    return subprocess.run(
        [sys.executable, str(SCRIPT), *args],
        input=token,
        text=True,
        capture_output=True,
        check=False,
    )


def test_installs_leo_wallet_test_token_from_stdin_without_echoing_secret(tmp_path):
    token = "123456789:abcdefghijklmnopqrstuvwxyzABC"
    proof_path = tmp_path / "proof.json"
    proc = run_installer(
        [
            "--agent",
            "leo-wallet-test",
            "--repo-root",
            str(REPO_ROOT),
            "--secrets-dir",
            str(tmp_path / "secrets"),
            "--from-stdin",
            "--no-chown",
            "--skip-validate",
            "--output",
            str(proof_path),
        ],
        token=token,
    )

    assert proc.returncode == 0, proc.stderr
    assert token not in proc.stdout
    assert token not in proc.stderr

    proof = json.loads(proof_path.read_text())
    token_path = Path(proof["tokenPath"])
    assert proof["ok"] is True
    assert proof["agent"] == "leo-wallet-test"
    assert proof["secretValuesIncluded"] is False
    assert proof["tokenFileWritten"] is True
    assert token not in proof_path.read_text()

    assert token_path.read_text().strip() == token
    mode = stat.S_IMODE(os.stat(token_path).st_mode)
    assert mode == 0o600


def test_refuses_cli_token_argument_without_echoing_secret():
    token = "123456789:abcdefghijklmnopqrstuvwxyzABC"
    proc = run_installer(["--token", token], token="")

    combined_output = proc.stdout + proc.stderr
    assert proc.returncode == 2
    assert token not in combined_output
    assert "Secret-bearing CLI args are not accepted" in combined_output
