#!/usr/bin/env python3
"""Reproduce the Atlas US–Canada pickup benchmark and check current market coverage."""
import argparse
import json
import os
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from uuid import uuid4

BASE = "https://automarketatlas.com"
STUDY = "us-canada-2022-ram-1500-prices-by-mileage-november-2026"


def read_json(path, headers=None, payload=None):
    body = json.dumps(payload).encode() if payload is not None else None
    settings = {"Accept": "application/json", "X-Atlas-Source": "research_" + STUDY}
    if headers:
        settings.update(headers)
    if body is not None:
        settings["Content-Type"] = "application/json"
    with urlopen(Request(BASE + path, data=body, headers=settings), timeout=15) as response:
        return json.load(response)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--mileage-km", type=int, default=75000)
    parser.add_argument("--live-comparison", action="store_true", help="Request current prices using prepaid credits")
    parser.add_argument("--max-charge-cents", type=int, help="Maximum charge in USD cents for the live request")
    parser.add_argument("--request-id", help="Reuse this value when retrying the same live request")
    args = parser.parse_args()
    if args.mileage_km < 0:
        parser.error("Mileage must be zero or greater.")
    if args.live_comparison and (args.max_charge_cents is None or args.max_charge_cents < 0):
        parser.error("Provide a nonnegative --max-charge-cents for a live comparison.")
    if args.live_comparison and not (key := os.getenv("ATLAS_API_KEY")):
        parser.error("Set ATLAS_API_KEY for a live comparison.")

    vehicle = {"make": "RAM", "model": "1500", "year": 2022, "mileage_km": args.mileage_km}
    archive = read_json("/research/" + STUDY + "/data.json")
    coverage = {}
    for country in ("US", "CA"):
        query = urlencode({"country": country, **vehicle})
        coverage[country] = read_json("/v1/market/availability?" + query)
    result = {
        "data_as_of": archive["as_of"],
        "fx_date": archive["fx_date"],
        "archived_rows": [row for row in archive["rows"] if row["odometer_km"] == args.mileage_km],
        "current_coverage": coverage,
    }
    if args.live_comparison:
        result["live_comparison"] = read_json("/v1/market/cross-market", {
            "Authorization": "Bearer " + key,
            "Idempotency-Key": args.request_id or str(uuid4()),
            "Max-Charge-Cents": str(args.max_charge_cents),
        }, {"vehicle": {"country": "US", **vehicle}, "other_countries": ["CA"], "display_currency": "USD"})
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    try:
        main()
    except HTTPError as error:
        try:
            detail = json.load(error).get("error", {})
        except (ValueError, AttributeError):
            detail = {}
        raise SystemExit(f"Atlas returned HTTP {error.code}: {detail.get('message', 'Request failed.')}")
    except (URLError, TimeoutError) as error:
        raise SystemExit(f"Atlas could not be reached: {error}")
