#!/usr/bin/env python3
"""Send one fictional GET event to the loopback receiver; no VICIdial access."""
import argparse
import json
from pathlib import Path
import urllib.error
from urllib.parse import urlencode
from urllib.request import urlopen
from receiver import state_path, token

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--state", type=Path, default=Path("call-url-state"))
parser.add_argument("--fixture", type=Path, default=Path("event-fictional.json"))
parser.add_argument("--port", type=int, default=8765)
args = parser.parse_args()
try:
    values = json.loads(args.fixture.read_text())
    values["token"] = token(state_path(args.state))
    url = f"http://127.0.0.1:{args.port}/call-event?" + urlencode(values)
    try:
        response = urlopen(url, timeout=5)
    except urllib.error.HTTPError as error:
        response = error
    with response:
        print(f"HTTP {response.status}: {response.read(4096).decode().strip()}")
except (OSError, ValueError, urllib.error.URLError):
    raise SystemExit("Local send failed; check state, fixture and receiver without printing the token.")
