"""One request to the third-party scrapestack API; requires your own key."""
import json
import os
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import urlopen

def fetch_html(target):
    query = urlencode({"access_key": os.environ["SCRAPESTACK_ACCESS_KEY"], "url": target})
    # Keep the full request URL out of logs: it contains your private API key.
    try:
        with urlopen("https://api.scrapestack.com/scrape?" + query, timeout=45) as response:
            raw = response.read()
    except (HTTPError, URLError):
        raise RuntimeError("Request failed. Check account status, quota and target availability.") from None
    try:
        result = json.loads(raw)
    except (ValueError, UnicodeDecodeError):
        result = None
    if isinstance(result, dict) and result.get("success") is False:
        raise RuntimeError("The API returned an error. Review the official error documentation.")
    return raw

if __name__ == "__main__":
    Path("page.html").write_bytes(fetch_html("https://example.com/"))
    print("Saved page.html. Parse it separately to extract fields or write CSV.")
