import json
import subprocess
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]


def run_php(source: str):
    completed = subprocess.run(
        ["php", "-r", source],
        cwd=ROOT,
        capture_output=True,
        text=True,
    )
    assert completed.returncode == 0, completed.stderr
    return json.loads(completed.stdout)


def test_instrument_settlement_currency_uses_quote_for_linear_and_base_for_inverse():
    source = (
        f"require {json.dumps(str(ROOT / 'classes' / 'Instrument.php'))}; "
        "echo json_encode(["
        "Instrument::getSettlementCurrency(['is_linear' => 1, 'base_currency' => 'BTC', 'quote_currency' => 'USDT']),"
        "Instrument::getSettlementCurrency(['is_linear' => 0, 'base_currency' => 'BTC', 'quote_currency' => 'USD'])"
        "]);"
    )

    assert run_php(source) == ["USDT", "BTC"]


def test_account_summary_validates_requested_currency_and_returns_canonical_settlement():
    source = (ROOT / "api" / "private" / "get_account_summary.php").read_text(
        encoding="utf-8"
    )

    assert "Instrument::getSettlementCurrency($instrument_data)" in source
    assert "strcasecmp($currency, $settlement_currency) === 0" in source
    assert '"currency" => $settlement_currency' in source
