"""Read one approved HTTPS reporting endpoint and create a BidLab shift bundle.
Python 3 standard library. For the data contract and usage see renewal-data-guide.html.
"""
import argparse
import json
import os
from pathlib import Path
import sys
from urllib.error import HTTPError, URLError
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener

FIELDS = ("case_id", "team", "channel", "arrival_min", "due_min", "handling_min")


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


def collect(endpoint, mapping, token, fetch):
    parts = urlsplit(endpoint)
    if parts.scheme != "https" or not parts.hostname or parts.username or parts.password or parts.fragment:
        raise ValueError("Use an HTTPS reporting endpoint without embedded credentials or fragment.")
    params = parse_qsl(parts.query, keep_blank_values=True)
    if any(key == "cursor" for key, value in params):
        raise ValueError("The adapter manages the cursor parameter.")
    if set(mapping) != set(FIELDS) or not all(isinstance(v, str) and v for v in mapping.values()):
        raise ValueError("Map each required BidLab field to one source field.")
    rows, seen, ids = [], set(), set()
    cursor = None
    for _ in range(100):
        query = params + ([("cursor", cursor)] if cursor is not None else [])
        url = urlunsplit(parts._replace(query=urlencode(query)))
        headers = {"Accept": "application/json"}
        if token:
            headers["Authorization"] = "Bearer " + token
        with fetch(Request(url, headers=headers, method="GET"), timeout=20) as response:
            data = response.read(1048577)
        if len(data) > 1048576:
            raise ValueError("Reporting page exceeds 1 MB.")
        page = json.loads(data)
        if not isinstance(page, dict) or not isinstance(page.get("rows"), list):
            raise ValueError("Expected an object with a rows array.")
        for source in page["rows"]:
            row = {key: source[mapping[key]] for key in FIELDS}
            if not isinstance(row["case_id"], str) or row["case_id"] in ids:
                raise ValueError("Invalid or duplicate case ID.")
            ids.add(row["case_id"])
            rows.append(row)
            if len(rows) > 500:
                raise ValueError("Use at most 500 cases per pilot shift.")
        cursor = page.get("next_cursor")
        if cursor is None:
            if not rows:
                raise ValueError("No cases returned.")
            return rows
        if not isinstance(cursor, str) or not cursor or cursor in seen:
            raise ValueError("Invalid or repeated cursor.")
        seen.add(cursor)
    raise ValueError("Too many reporting pages.")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--url", required=True, help="Approved reporting endpoint")
    parser.add_argument("--config", required=True, type=Path, help="Local mapping and staffing JSON")
    parser.add_argument("--out", required=True, type=Path, help="New output JSON file")
    args = parser.parse_args()
    config = json.loads(args.config.read_text(encoding="utf-8"))
    rows = collect(args.url, config["mapping"], os.getenv("BIDLAB_READ_TOKEN"), build_opener(NoRedirect()).open)
    bundle = {"schema": "bidlab.shift.v1", "settings": config["settings"], "cases": rows}
    payload = json.dumps(bundle, ensure_ascii=False, allow_nan=False, indent=2)
    with args.out.open("x", encoding="utf-8") as out:
        out.write(payload)
    print(f"Prepared {len(rows)} cases. Import the JSON in Renewal shift planner for validation.")


if __name__ == "__main__":
    try:
        main()
    except HTTPError as exc:
        sys.exit(f"Report request failed (HTTP {exc.code}).")
    except (ValueError, KeyError, TypeError, OSError, URLError) as exc:
        sys.exit(f"Import failed ({type(exc).__name__}). Check the endpoint, mapping, data and output path.")
