#!/usr/bin/env python3
"""Query recorded Reciprocal Seam v3 measurements from the public AWS API."""

import argparse
import json
import sys
from urllib.error import HTTPError
from urllib.parse import quote, urlencode
from urllib.request import Request, urlopen

API = "https://ka7e2gruk9.execute-api.us-east-1.amazonaws.com/v3"
RELEASE = "20261203-electric-seams-v1"


def record_number(text):
    if not (text.isascii() and text.isdecimal() and len(text) <= 125):
        raise argparse.ArgumentTypeError("expected a nonnegative decimal integer of up to 125 digits")
    return int(text)


def query_url(args):
    base = f"{API}/{quote(args.run, safe='')}"
    if args.action is None:
        return base
    if args.action == "journal":
        if args.observer is not None:
            base += f"/observers/{args.observer}"
        query = urlencode({"offset": args.offset, "limit": args.limit})
        return f"{base}/journal/{args.version}?{query}"
    if args.action == "face-field":
        return f"{base}/face-field/{args.tick}"
    path = "rows" if args.action == "row" else "observers"
    return f"{base}/{path}/{args.identifier}?round={args.round}"


def main():
    parser = argparse.ArgumentParser(
        description=__doc__,
        epilog="Run without arguments to list runs, or supply only a run ID for its archived coverage.",
    )
    parser.add_argument("run", help="archived run ID, e.g. level13 or level202-r3000")
    commands = parser.add_subparsers(dest="action")
    field = commands.add_parser("face-field", help="read receiver flux on the Level 202 radius-3000 face chart")
    field.add_argument("tick", type=record_number, help="field step from 0 to 3000")
    journal = commands.add_parser("journal", help="read one page of arrivals at a journal version")
    journal.add_argument("version", type=record_number)
    journal.add_argument("--observer", type=record_number, help="native address (default: the run’s selected receiver)")
    journal.add_argument("--offset", type=record_number, default=0, help="zero-based arrival offset within this version")
    journal.add_argument("--limit", type=record_number, default=50, help="maximum readings per page, 1 to 128")
    for name, description in (
        ("row", "read material by zero-based reporting ordinal"),
        ("observer", "read material by native observer address"),
    ):
        material = commands.add_parser(name, help=description)
        material.add_argument("identifier", type=record_number, help=description)
        material.add_argument("--round", type=int, choices=(0, 1, 2), default=2, help="native material cut (default: 2)")

    url = API
    if sys.argv[1:]:
        args = parser.parse_args()
        if args.action == "journal" and not 1 <= args.limit <= 128:
            journal.error("--limit must be between 1 and 128")
        url = query_url(args)
    request = Request(url, headers={"Accept": "application/json", "User-Agent": "OPH-v3-atlas-query/1"})
    try:
        with urlopen(request, timeout=30) as response:
            result = json.load(response)
        if not isinstance(result, dict) or result.get("release") != RELEASE:
            raise ValueError("The API response does not identify the registered electric-seam release")
    except HTTPError as error:
        message = error.reason
        try:
            payload = json.loads(error.read(8192))
            if isinstance(payload, dict):
                message = payload.get("error") or payload.get("message") or message
        except (ValueError, UnicodeError):
            pass
        parser.exit(1, f"Record query failed (HTTP {error.code}): {message}\n")
    except (OSError, ValueError) as error:
        parser.exit(1, f"Record query failed: {error}\n")
    print(json.dumps(result, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()
