# /// script
# requires-python = ">=3.10"
# dependencies = ["pypdf==6.10.0"]
# ///
"""Extract page 1 of USDA's February 24, 2017 energy report to Excel-readable CSV."""
import csv
import re
import sys
from pypdf import PdfReader

text = PdfReader(sys.argv[1]).pages[0].extract_text(extraction_mode="layout")
section = text.split("Ethanol ($/gal)", 1)[1].split("Biodiesel", 1)[0]
markets = ("Iowa", "Minnesota", "Nebraska", "South Dakota", "Eastern Cornbelt", "Wisconsin")
rows = []
for line in section.splitlines()[1:]:
    match = re.match(r"^\s*(" + "|".join(markets) + r")\s+", line)
    if not match:
        continue
    quotes = re.findall(r"unq|\d+\.\d{2}\s*-\s*\d+\.\d{2}", line)[:3]
    for period, quote in zip(("Week ending 2017-02-24", "Previous week", "Year ago"), quotes, strict=True):
        low, high = ("", "") if quote == "unq" else map(str.strip, quote.split("-"))
        rows.append((match[1], period, low, high, "unq" if quote == "unq" else "", 1))
if len(rows) != 18:
    raise ValueError("Expected all 18 observations in the ethanol table.")
writer = csv.writer(sys.stdout)
writer.writerow(("Market", "Comparison period", "Low (USD/gal)", "High (USD/gal)", "Source note", "PDF page"))
writer.writerows(rows)
