from eth_account import Account

from src.config.hyperliquid_env import load_hyperliquid_env, diagnose_hyperliquid_env


def _write_env(path, *, wallet, private_key, api_key=None):
    lines = [
        f"HL_WALLET_ADDRESS={wallet}",
        f"HL_API_PRIVATE_KEY={private_key}",
        "API Wallet Name=Hermes Agent",
    ]
    if api_key is not None:
        lines.append(f"API Key={api_key}")
    path.write_text("\n".join(lines) + "\n", encoding="utf-8")


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

    cfg = load_hyperliquid_env("mainnet", search_dirs=(tmp_path,), validation_mode="readonly")

    assert cfg.account_address == wallet
    assert cfg.api_wallet_key_matches_private_key is False
    assert "api_key_private_key_mismatch" not in cfg.errors
    assert "api_key_private_key_mismatch" in cfg.warnings
    assert cfg.safe_for_readonly is True


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

    cfg = load_hyperliquid_env("testnet", search_dirs=(tmp_path,), validation_mode="signed", allow_errors=True)

    assert "api_key_private_key_mismatch" in cfg.errors
    assert cfg.safe_to_run_testnet_smokes is False


def test_readonly_mode_requires_only_wallet_address(tmp_path):
    wallet = Account.create().address
    (tmp_path / "Testnet.env").write_text(f"HL_WALLET_ADDRESS={wallet}\n", encoding="utf-8")

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

    assert cfg.account_address == wallet
    assert cfg.api_private_key is None
    assert cfg.api_wallet_address_derived is None
    assert cfg.safe_for_readonly is True
    assert cfg.masked()["credential_warning"] is None


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

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

    assert diag["env_file_path"].endswith("Testnet.env")
    assert diag["credential_warning"] == "api_key_private_key_mismatch"
    assert diag["errors"] == []
    assert diag["safe_for_readonly"] is True
