from eth_account import Account

from src.config.hyperliquid_env import diagnose_hyperliquid_env, load_hyperliquid_env


def _write_env(path, *, wallet, private_key, api_key):
    path.write_text(
        f"HL_WALLET_ADDRESS={wallet}\n"
        f"HL_API_PRIVATE_KEY={private_key}\n"
        "API Wallet Name=Hermes Agent\n"
        f"API Key={api_key}\n",
        encoding="utf-8",
    )


def test_loader_uses_only_requested_env_file_and_masks(tmp_path):
    main_acct = Account.create()
    test_acct = Account.create()
    main_wallet = Account.create().address
    test_wallet = Account.create().address
    _write_env(tmp_path / "Mainnet.env", wallet=main_wallet, private_key=main_acct.key.hex(), api_key=main_acct.address)
    _write_env(tmp_path / "Testnet.env", wallet=test_wallet, private_key=test_acct.key.hex(), api_key=test_acct.address)

    cfg = load_hyperliquid_env("testnet", search_dirs=(tmp_path,))

    assert cfg.env == "testnet"
    assert cfg.env_file_path.name == "Testnet.env"
    assert cfg.account_address == test_wallet
    assert cfg.api_wallet_address_from_env == test_acct.address
    assert cfg.api_wallet_address_derived == test_acct.address
    assert cfg.safe_to_run_testnet_smokes is True
    assert cfg.will_use_mainnet_key is False
    assert cfg.masked()["account_address_masked"].startswith(test_wallet[:6])
    assert main_acct.key.hex() not in str(cfg.masked())


def test_loader_fails_closed_when_requested_file_missing_even_if_other_exists(tmp_path):
    acct = Account.create()
    _write_env(tmp_path / "Mainnet.env", wallet=Account.create().address, private_key=acct.key.hex(), api_key=acct.address)

    diag = diagnose_hyperliquid_env("testnet", search_dirs=(tmp_path,))

    assert diag["env_file_found"] is False
    assert diag["safe_to_run_testnet_smokes"] is False
    assert "missing_env_file" in diag["errors"]


def test_loader_blocks_api_key_private_key_mismatch_and_account_equals_api_wallet(tmp_path):
    acct = Account.create()
    other = Account.create()
    _write_env(tmp_path / "Testnet.env", wallet=acct.address, private_key=acct.key.hex(), api_key=other.address)

    diag = diagnose_hyperliquid_env("testnet", search_dirs=(tmp_path,))

    assert diag["api_wallet_key_matches_private_key"] is False
    assert diag["account_address_equals_api_wallet_address"] is False
    assert "api_key_private_key_mismatch" in diag["errors"]
    assert diag["safe_to_run_testnet_smokes"] is False


def test_loader_blocks_account_address_equal_to_api_wallet(tmp_path):
    acct = Account.create()
    _write_env(tmp_path / "Testnet.env", wallet=acct.address, private_key=acct.key.hex(), api_key=acct.address)

    diag = diagnose_hyperliquid_env("testnet", search_dirs=(tmp_path,))

    assert diag["account_address_equals_api_wallet_address"] is True
    assert "account_address_equals_api_wallet_address" in diag["errors"]
    assert diag["safe_to_run_testnet_smokes"] is False
