"""Preview fresh supplier costs or read an existing preview without starting a run."""

import json
import os
import re
import sys
from urllib.error import HTTPError
from urllib.request import HTTPRedirectHandler, Request, build_opener


API = "https://api.apify.com/v2"
ACTOR = "apifmcpfactory~htf-instagram-discovery"


class RefuseRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def request(path, token, body=None):
    headers = {"Authorization": "Bearer " + token}
    encoded = None
    if body is not None:
        encoded = json.dumps(body).encode("utf-8")
        headers["Content-Type"] = "application/json"
    req = Request(API + path, data=encoded, headers=headers)
    try:
        with build_opener(RefuseRedirect()).open(req, timeout=75) as response:
            return json.load(response)
    except HTTPError as error:
        raise SystemExit(f"Apify returned HTTP {error.code}.") from None


def main():
    token = os.environ.get("APIFY_TOKEN")
    if not token:
        raise SystemExit("Set APIFY_TOKEN in your environment.")
    args = sys.argv[1:]
    if len(args) > 1 or (args and not re.fullmatch(r"[a-zA-Z0-9]{17}", args[0])):
        raise SystemExit("Pass only an optional 17-character run ID.")
    if args:
        run = request("/actor-runs/" + args[0], token)["data"]
    else:
        run = request(f"/acts/{ACTOR}/runs?waitForFinish=60", token, {
            "mode": "experimentPlan",
            "brandUsername": "nasa",
            "rivalUsername": "europeanspaceagency",
            "sourceAction": "preview",
            "maxCollectionChargeUsd": 0,
        })["data"]
    if run["status"] != "SUCCEEDED":
        raise SystemExit(f"Check run {run['id']} in Apify before trying again.")
    output = request("/key-value-stores/" + run["defaultKeyValueStoreId"] + "/records/OUTPUT", token)
    if output.get("mode") != "experimentPlan" or output.get("action") != "preview" or output.get("supplierRunsStarted") != 0:
        raise SystemExit("This run did not return the no-collection preview.")
    print(json.dumps({
        "build": run["buildNumber"],
        "maximumSupplierChargeForRequestedRowsUsd": output["maximumSupplierChargeForRequestedRowsUsd"],
        "supplierRunsStarted": output["supplierRunsStarted"],
    }, indent=2))


if __name__ == "__main__":
    main()
