"""Transport example, not the full starter. Python 3.10+, no dependencies."""
import getpass
import json
import os
import time
import urllib.error
import urllib.request
from urllib.parse import urlparse

SERVER = os.environ.get("AGENTCRAFT_API_URL", "https://api.agentcraft.world").rstrip("/")
KEY = os.environ.get("AGENTCRAFT_API_KEY") or getpass.getpass("Champion key (hidden): ").strip()
parsed = urlparse(SERVER)
if parsed.scheme != "https" and not (parsed.scheme == "http" and parsed.hostname in ("localhost", "127.0.0.1")):
    raise SystemExit("Use HTTPS, or HTTP only for localhost testing.")
if not KEY:
    raise SystemExit("A champion key is required.")


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None  # Never forward the champion key to a redirected destination.


opener = urllib.request.build_opener(NoRedirect())


def request(path, action=None):
    headers = {"Authorization": "Bearer " + KEY}
    data = None
    if action is not None:
        headers["Content-Type"] = "application/json"
        data = json.dumps({**action, "api_version": "0.1"}).encode()
    req = urllib.request.Request(SERVER + "/api/v1/" + path, data=data, headers=headers)
    with opener.open(req, timeout=15) as response:
        return json.load(response)


def choose(observation):
    # Replace this function with your policy. REST is a safe transport smoke test.
    return {"action": "REST"}


def main():
    last_tick = None
    while True:
        delay = 5.0
        observation = {}
        try:
            observation = request("observe?mode=full")
            if observation["api_version"] != "0.1":
                raise SystemExit("Client update required. Read the current AgentCraft docs.")
            if observation["tick"] == last_tick:
                time.sleep(0.5)
                continue
            result = request("act", choose(observation))
            if result.get("accepted"):
                last_tick = observation["tick"]
                print("Queued for tick", last_tick, "| Previous:", observation.get("last_action_result"))
            delay = max(1.0, observation.get("tick_interval_ms", 5000) / 1000)
        except urllib.error.HTTPError as error:
            if error.code in (401, 402, 403, 426):
                raise SystemExit(f"HTTP {error.code}: check your key, membership, hosted-control mode, and API version.")
            if error.code in (429, 503):
                try:
                    delay = max(5.0, min(60.0, float(error.headers.get("Retry-After", "10"))))
                except ValueError:
                    delay = 10.0
            elif error.code == 409:
                last_tick = observation.get("tick", last_tick)
            else:
                print("Request rejected:", error.code)
        except (OSError, ValueError, KeyError):
            print("Connection interrupted; retrying.")
            delay = 10.0
        time.sleep(delay)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("Stopped. Progress stays saved.")
