"""Read a public MinerAPI sample. No third-party Python packages required."""
import argparse
import json
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen


def get_sample(kind: str = "asic", base_url: str = "https://minerapi.com") -> dict:
    """Return a version-1.0 fixture, or raise a clear validation/network error."""
    if kind not in {"asic", "gpu", "prompts"}:
        raise ValueError("Expected asic, gpu, or prompts")
    endpoint = base_url.rstrip("/") + "/api/demo/" + kind + ".json"
    request = Request(endpoint, headers={"Accept": "application/json"})
    try:
        with urlopen(request, timeout=7) as response:
            data = json.load(response)
    except (HTTPError, URLError, TimeoutError, ValueError) as error:
        raise RuntimeError(f"Unable to read sample: {error}") from error
    if not isinstance(data, dict) or data.get("demo") is not True:
        raise ValueError("Expected a public demo record")
    if data.get("schema_version") != "1.0":
        raise ValueError("Unsupported sample schema")
    return data


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("kind", choices=["asic", "gpu", "prompts"], nargs="?", default="asic")
    parser.add_argument("--base-url", default="https://minerapi.com")
    args = parser.parse_args()
    try:
        print(json.dumps(get_sample(args.kind, args.base_url), indent=2))
    except (ValueError, RuntimeError) as error:
        parser.exit(1, f"Error: {error}\n")
