#!/usr/bin/env python3
"""Fetch two source-timestamped gas prices and write a basis CSV to stdout.

Usage: set OILPRICEAPI_KEY in your environment, then:
    python3 waha_basis.py > waha-basis.csv
Requires Python 3.9+; uses only the standard library.
"""
import csv
import datetime
import json
import math
import os
import sys
import urllib.error
import urllib.request


def validate_price(payload, code):
    if not isinstance(payload, dict):
        raise ValueError(f"{code}: expected a JSON object")
    data = payload.get("data")
    if payload.get("status") != "success" or not isinstance(data, dict):
        raise ValueError(f"{code}: expected a successful single-price response")
    value = data.get("price")
    if isinstance(value, bool) or value is None or str(value).strip() == "":
        raise ValueError(f"{code}: price is missing")
    price = float(value)
    if not math.isfinite(price) or data.get("code") != code:
        raise ValueError(f"{code}: invalid price or mismatched benchmark")
    timestamp = data.get("created_at")
    if not isinstance(timestamp, str):
        raise ValueError(f"{code}: source timestamp is missing")
    parsed = datetime.datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
    if parsed.tzinfo is None:
        raise ValueError(f"{code}: source timestamp must include a timezone")
    if data.get("currency") != "USD":
        raise ValueError(f"{code}: expected USD")
    unit = data.get("unit")
    if unit is not None and str(unit).lower() != "mmbtu":
        raise ValueError(f"{code}: expected MMBtu units")
    return price, timestamp


def fetch_price(code, key):
    request = urllib.request.Request(
        f"https://api.oilpriceapi.com/v1/prices/latest?by_code={code}",
        headers={"Authorization": f"Token {key}", "Accept": "application/json"},
    )
    with urllib.request.urlopen(request, timeout=20) as response:
        return validate_price(json.load(response), code)


def main():
    key = os.environ.get("OILPRICEAPI_KEY", "").strip()
    if not key:
        print("Set OILPRICEAPI_KEY to your account's API key before running this script.", file=sys.stderr)
        return 1
    try:
        waha, waha_at = fetch_price("NATURAL_GAS_WAHA", key)
        henry, henry_at = fetch_price("NATURAL_GAS_USD", key)
    except urllib.error.HTTPError as error:
        recovery = {401: "Check your API key.", 402: "Check dataset access in your plan.", 403: "Check dataset access in your plan.", 429: "Wait for the request limit to reset before retrying."}
        print(f"Request failed (HTTP {error.code}). {recovery.get(error.code, 'Retry later; no CSV was written.')}", file=sys.stderr)
        return 1
    except (urllib.error.URLError, TimeoutError, ValueError, TypeError) as error:
        print(f"Unable to create a complete basis snapshot: {type(error).__name__}. Check connectivity and the response fields; no CSV was written.", file=sys.stderr)
        return 1
    writer = csv.writer(sys.stdout)
    writer.writerow(["generated_at", "waha_source_timestamp", "henry_hub_source_timestamp", "waha_usd_mmbtu", "henry_hub_usd_mmbtu", "waha_minus_henry_hub_usd_mmbtu"])
    writer.writerow([datetime.datetime.now(datetime.timezone.utc).isoformat(), waha_at, henry_at, waha, henry, round(waha - henry, 6)])
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
