#!/usr/bin/env python3
"""Write one JSON object per Focus library document. Requires documents:list."""
import getpass
import http.client
import json
import os
import re
import sys
import time
import uuid
import warnings
from urllib.parse import urlencode


def read_page(connection, key, query):
    headers = {
        "Accept": "application/json",
        "Authorization": "Bearer " + key,
        "Idempotency-Key": str(uuid.uuid4()),
    }
    for attempt in range(3):
        delay = 2 ** attempt
        try:
            connection.request("GET", "/api/v1/documents?" + urlencode(query), headers=headers)
            response = connection.getresponse()
            body = response.read()
        except (OSError, http.client.HTTPException):
            connection.close()
            if attempt == 2:
                raise RuntimeError("Connection failed after three attempts.") from None
        else:
            if response.status == 200:
                return json.loads(body)
            try:
                code = json.loads(body)["code"]
            except (KeyError, TypeError, ValueError):
                code = None
            code = code if isinstance(code, str) and re.fullmatch(r"[a-z_]{1,64}", code) else "unexpected_response"
            retry = response.getheader("Retry-After", "")
            if response.status not in (429, 503) or not re.fullmatch(r"[0-9]{1,6}", retry) or attempt == 2:
                raise RuntimeError(f"HTTP {response.status} ({code}). See https://couldfocus.com/developers#errors")
            delay = max(delay, int(retry))
            if delay > 60:
                raise RuntimeError(f"HTTP {response.status} ({code}). Try again in {delay} seconds.")
        time.sleep(delay)


def documents(connection, key, page_size=100):
    query = {"limit": page_size}
    seen = set()
    while True:
        page = read_page(connection, key, query)
        yield from page["data"]
        cursor = page["next"]
        if cursor is None:
            return
        if not isinstance(cursor, str) or cursor in seen:
            raise RuntimeError("Focus returned an invalid or repeated page cursor.")
        seen.add(cursor)
        query["after"] = cursor


def main():
    sys.stdout.reconfigure(encoding="utf-8")
    key = os.environ.get("FOCUS_API_KEY")
    if not key:
        if not sys.stdin.isatty():
            raise RuntimeError("Set FOCUS_API_KEY through your job's secret store or run in a terminal.")
        with warnings.catch_warnings():
            warnings.simplefilter("error", getpass.GetPassWarning)
            try:
                key = getpass.getpass("Focus API key (hidden): ")
            except getpass.GetPassWarning:
                raise RuntimeError("Use a terminal with hidden input or supply FOCUS_API_KEY.") from None
    if not key or not re.fullmatch(r"[!-~]+", key):
        raise RuntimeError("Enter the key copied from Developer access.")
    connection = http.client.HTTPSConnection("couldfocus.com", timeout=20)
    try:
        for document in documents(connection, key):
            print(json.dumps(document, ensure_ascii=False))
    finally:
        connection.close()


if __name__ == "__main__":
    try:
        main()
    except (RuntimeError, ValueError, KeyError, EOFError) as error:
        sys.exit(str(error))
