"""Network helpers: API URL resolution and account info fetching.

Uses only urllib (stdlib) to avoid depending on httpx/requests.
"""

from __future__ import annotations

import json
import urllib.request
import urllib.error

_API_URLS = {
    "mainnet": "https://api.hiro.so",
    "testnet": "https://api.testnet.hiro.so",
}


def get_api_url(network: str) -> str:
    """Return the Hiro API base URL for the given network."""
    return _API_URLS.get(network, _API_URLS["testnet"])


def fetch_account_nonce(address: str, network: str = "testnet") -> int:
    """Fetch the current nonce for an account from the Stacks API."""
    base = get_api_url(network)
    url = f"{base}/v2/accounts/{address}?proof=0"
    req = urllib.request.Request(url, headers={"Accept": "application/json"})
    with urllib.request.urlopen(req, timeout=15) as resp:
        data = json.loads(resp.read())
    return int(data["nonce"])


def fetch_estimated_fee(network: str = "testnet") -> int:
    """Fetch an estimated fee from the Stacks API.

    Falls back to a default fee of 200 microSTX on error.
    """
    try:
        base = get_api_url(network)
        url = f"{base}/v2/fees/transfer"
        req = urllib.request.Request(url, headers={"Accept": "application/json"})
        with urllib.request.urlopen(req, timeout=10) as resp:
            data = json.loads(resp.read())
        # API returns fee estimate in microSTX
        return int(data) if isinstance(data, (int, float, str)) else 200
    except Exception:
        return 200
