import requests
import csv
import time

API_URL = "https://www.sereiaguardia.com.br/web_api/orders/:orderId/complete?access_token=APP_ID-6197-STORE_ID-1018776-7a249468d35d27e5b151a11228bc88a1d2db55edb59b4a6477ec9b04e7aa703c"
OUTPUT_CSV = "orders.csv"
RATE_LIMIT_SECONDS = 0.5  # 60 req/min = 1 req/sec

# Optional authentication
HEADERS = {
    # "Authorization": "Bearer TOKEN",
    # "Accept": "application/json"
}

def fetch_order(order_id):
    """Fetch a single order."""
    url = API_URL.replace(":orderId", str(order_id))
    response = requests.get(url, headers=HEADERS, timeout=10)
    response.raise_for_status()  # will throw if request fails
    return response.json()

def main():
    # Create CSV file and write headers after fetching first row
    first_row_written = False

    with open(OUTPUT_CSV, mode="w", newline="", encoding="utf-8") as file:
        writer = None

        for order_id in range(1, 2001):
            try:
                data = fetch_order(order_id)

                # Create the CSV writer and header dynamically from the JSON keys
                if not first_row_written:
                    fieldnames = data.keys()
                    writer = csv.DictWriter(file, fieldnames=fieldnames)
                    writer.writeheader()
                    first_row_written = True

                # Write the row
                writer.writerow(data)

                print(f"Saved order {order_id}")

            except requests.exceptions.HTTPError as err:
                print(f"HTTP error for order {order_id}: {err}")
            except Exception as err:
                print(f"Error for order {order_id}: {err}")

            # Respect rate limit
            time.sleep(RATE_LIMIT_SECONDS)

    print("Done!")

if __name__ == "__main__":
    main()
