"""Exercise the installer's real sync gate without running an upgrade."""
import json
from pathlib import Path
import subprocess

LOCAL = Path(__file__).resolve().parent / "txc-stm-fix-upgrade.sh"
SCRIPT = LOCAL if LOCAL.exists() else Path(__file__).resolve().parents[2] / "install/txc-stm-fix-upgrade.sh"


def ready(info):
    source = SCRIPT.read_text()
    function = source.split("recount_ready() {", 1)[1].split("\n}", 1)[0]
    command = 'rpc() { printf "%s" "$INFO"; }; recount_ready() {' + function + '\n}; recount_ready'
    import os
    return subprocess.run(["bash", "-c", command], env={**os.environ, "INFO": json.dumps(info)}, capture_output=True).returncode == 0


def test_initial_download_cannot_pass_balance_gate():
    assert not ready({"initialblockdownload": True, "blocks": 378127, "headers": 378127})


def test_lagging_node_cannot_pass_balance_gate():
    assert not ready({"initialblockdownload": False, "blocks": 378126, "headers": 378127})


def test_synced_node_passes_balance_gate():
    assert ready({"initialblockdownload": False, "blocks": 378127, "headers": 378127})


def test_missing_sync_state_fails_closed():
    assert not ready({})

def updated(core, omni):
    function = SCRIPT.read_text().split("already_updated() {", 1)[1].split("\n}", 1)[0]
    command = 'already_updated() {' + function + '\n}; already_updated "$1" "$2"'
    return subprocess.run(["bash", "-c", command, "check", core, omni], capture_output=True).returncode == 0


def test_updated_versions_skip_recount():
    assert updated("TEXITcoin Core version v0.26.2", "1.0.0")


def test_old_core_does_not_skip_recount():
    assert not updated("TEXITcoin Core version v0.26.1", "1.0.0")


def test_old_omni_does_not_skip_recount():
    assert not updated("TEXITcoin Core version v0.26.2", "0.9.0")


def test_different_patch_version_does_not_skip_recount():
    assert not updated("TEXITcoin Core version v0.26.20", "1.0.0")


def test_no_startclean_restart_omits_startclean():
    source = SCRIPT.read_text()
    branch = source.split('if [[ "${NO_STARTCLEAN:-0}" == "1" ]]; then', 1)[1].split("elif", 1)[0]
    assert "-startclean" not in branch.replace("NO_STARTCLEAN", "")
    assert 'systemctl start "$UNIT"' in branch
