"""Tests for the Leo wallet-test Telegram runtime verifier."""

import json
import subprocess
import sys
from pathlib import Path
from unittest.mock import MagicMock, patch

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


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


def test_missing_token_writes_sanitized_blocker(tmp_path):
    proof_path = tmp_path / "proof.json"
    proc = run_checker(
        [
            "--agent",
            "leo-wallet-test",
            "--repo-root",
            str(REPO_ROOT),
            "--secrets-dir",
            str(tmp_path / "secrets"),
            "--skip-getme",
            "--output",
            str(proof_path),
        ]
    )

    assert proc.returncode == 0, proc.stderr
    proof = json.loads(proof_path.read_text())
    assert proof["ok"] is False
    assert proof["exactBlocker"] == "telegram_token_file_missing"
    assert proof["tokenFilePresent"] is False
    assert proof["secretValuesIncluded"] is False
    assert "secretValuesIncluded" in proc.stdout


def test_invalid_token_shape_fails_without_printing_token(tmp_path):
    secrets_dir = tmp_path / "secrets"
    secrets_dir.mkdir()
    token_path = secrets_dir / "leo-test-telegram-bot-token"
    token = "not-a-valid-token"
    token_path.write_text(token)
    proof_path = tmp_path / "proof.json"
    proc = run_checker(
        [
            "--agent",
            "leo-wallet-test",
            "--repo-root",
            str(REPO_ROOT),
            "--secrets-dir",
            str(secrets_dir),
            "--skip-getme",
            "--require-token",
            "--output",
            str(proof_path),
        ]
    )

    assert proc.returncode == 1
    assert token not in proc.stdout
    assert token not in proc.stderr
    proof = json.loads(proof_path.read_text())
    assert proof["exactBlocker"] == "telegram_token_shape_invalid"
    assert proof["tokenFilePresent"] is True
    assert proof["tokenShapeValid"] is False
    assert proof["secretValuesIncluded"] is False


def test_getme_result_is_sanitized_and_matches_expected_username():
    module_dir = str(SCRIPT.parent)
    sys.path.insert(0, module_dir)
    import check_telegram_leo_wallet_test_runtime as checker

    token = "dummy-token-value"
    response_body = {
        "ok": True,
        "result": {
            "id": 123456789,
            "is_bot": True,
            "first_name": "Living IP Leo Wallet Test",
            "username": "lipleowallet0622183538bot",
            "can_join_groups": True,
            "can_read_all_group_messages": False,
            "supports_inline_queries": False,
        },
    }
    response = MagicMock()
    response.status = 200
    response.read.return_value = json.dumps(response_body).encode("utf-8")
    response.__enter__.return_value = response

    with patch("urllib.request.urlopen", return_value=response):
        result = checker.telegram_get_me(token)

    serialized = json.dumps(result)
    assert result["ok"] is True
    assert result["username"] == "lipleowallet0622183538bot"
    assert result["botIdPresent"] is True
    assert result["secretValuesIncluded"] is False
    assert token not in serialized
