"""Tests for safe Telegram smart-research gate 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_smart_research_gates.py"


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


def test_installs_paid_gate_from_stdin_without_echoing_secret_or_chat_id(tmp_path):
    approval_ref = "approval_ref_livingip_x402_20260622"
    chat_id = "-1001234567890"
    proof_path = tmp_path / "proof.json"
    proc = run_installer(
        [
            "--agent",
            "leo-wallet-test",
            "--secrets-dir",
            str(tmp_path / "secrets"),
            "--allow-paid",
            "--allowed-chat-id",
            chat_id,
            "--max-usd",
            "0.06",
            "--approval-ref-from-stdin",
            "--no-chown",
            "--output",
            str(proof_path),
        ],
        approval_ref=approval_ref,
    )

    assert proc.returncode == 0, proc.stderr
    combined_output = proc.stdout + proc.stderr + proof_path.read_text()
    assert approval_ref not in combined_output
    assert chat_id not in combined_output

    proof = json.loads(proof_path.read_text())
    env_path = Path(proof["envPath"])
    approval_path = Path(proof["approvalRefPath"])
    assert proof["ok"] is True
    assert proof["agent"] == "leo-wallet-test"
    assert proof["paidEnabled"] is True
    assert proof["approvalRefPresent"] is True
    assert proof["allowedChatIdPresent"] is True
    assert proof["allowedChatTitlePresent"] is False
    assert proof["maxUsd"] == "0.06"
    assert proof["secretValuesIncluded"] is False

    env_content = env_path.read_text()
    assert "LIVINGIP_LEO_TELEGRAM_SMART_RESEARCH_ALLOW_PAID=1" in env_content
    assert "LIVINGIP_LEO_TELEGRAM_SMART_RESEARCH_MAX_USD=0.06" in env_content
    assert f"LIVINGIP_LEO_TELEGRAM_SMART_RESEARCH_ALLOWED_CHAT_ID={chat_id}" in env_content
    assert f"LIVINGIP_LEO_TELEGRAM_SMART_RESEARCH_APPROVAL_REF_FILE={approval_path}" in env_content
    assert approval_path.read_text().strip() == approval_ref

    assert stat.S_IMODE(os.stat(env_path).st_mode) == 0o600
    assert stat.S_IMODE(os.stat(approval_path).st_mode) == 0o600


def test_installs_paid_gate_with_title_fallback_without_echoing_secret(tmp_path):
    approval_ref = "approval_ref_livingip_x402_20260622"
    chat_title = "Leo"
    proof_path = tmp_path / "proof.json"
    proc = run_installer(
        [
            "--agent",
            "leo",
            "--secrets-dir",
            str(tmp_path / "secrets"),
            "--allow-paid",
            "--allowed-chat-title",
            chat_title,
            "--max-usd",
            "0.01",
            "--approval-ref-from-stdin",
            "--no-chown",
            "--output",
            str(proof_path),
        ],
        approval_ref=approval_ref,
    )

    assert proc.returncode == 0, proc.stderr
    combined_output = proc.stdout + proc.stderr + proof_path.read_text()
    assert approval_ref not in combined_output

    proof = json.loads(proof_path.read_text())
    env_path = Path(proof["envPath"])
    approval_path = Path(proof["approvalRefPath"])
    assert proof["ok"] is True
    assert proof["agent"] == "leo"
    assert proof["paidEnabled"] is True
    assert proof["approvalRefPresent"] is True
    assert proof["allowedChatIdPresent"] is False
    assert proof["allowedChatTitlePresent"] is True
    assert proof["maxUsd"] == "0.01"
    assert proof["secretValuesIncluded"] is False

    env_content = env_path.read_text()
    assert "LIVINGIP_LEO_TELEGRAM_SMART_RESEARCH_ALLOW_PAID=1" in env_content
    assert "LIVINGIP_LEO_TELEGRAM_SMART_RESEARCH_ALLOWED_CHAT_TITLE=Leo" in env_content
    assert "LIVINGIP_LEO_TELEGRAM_SMART_RESEARCH_ALLOWED_CHAT_ID=" not in env_content
    assert f"LIVINGIP_LEO_TELEGRAM_SMART_RESEARCH_APPROVAL_REF_FILE={approval_path}" in env_content
    assert approval_path.read_text().strip() == approval_ref


def test_installs_disabled_gate_without_approval_ref(tmp_path):
    proof_path = tmp_path / "proof.json"
    proc = run_installer(
        [
            "--agent",
            "leo-wallet-test",
            "--secrets-dir",
            str(tmp_path / "secrets"),
            "--no-chown",
            "--output",
            str(proof_path),
        ],
        approval_ref="",
    )

    assert proc.returncode == 0, proc.stderr
    proof = json.loads(proof_path.read_text())
    env_path = Path(proof["envPath"])
    approval_path = Path(proof["approvalRefPath"])
    assert proof["paidEnabled"] is False
    assert proof["approvalRefWritten"] is False
    assert "LIVINGIP_LEO_TELEGRAM_SMART_RESEARCH_ALLOW_PAID=0" in env_path.read_text()
    assert not approval_path.exists()


def test_refuses_cli_approval_ref_argument_without_echoing_secret():
    approval_ref = "approval_ref_livingip_x402_20260622"
    proc = run_installer(["--approval-ref", approval_ref], approval_ref="")

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