#!/usr/bin/env python3
"""FRED alternate transports: requests (TLS stack differs from http.client), and
a range-limited CSV to shrink payload. Fallback chain for HTTP/2 stalls."""
import json, time, ssl, sys
import pandas as pd

out = {}
try:
    import requests
    print("requests available:", requests.__version__, flush=True)
except Exception as e:
    print("no requests:", e, flush=True); requests = None

SIDS = ("BAMLH0A0HYM2", "BAMLC0A0CM")

def try_requests(sid):
    """requests uses urllib3+OpenSSL; may negotiate differently than http.client."""
    for attempt in range(3):
        try:
            r = requests.get(
                f"https://fred.stlouisfed.org/graph/fredgraph.csv?id={sid}",
                params={"cosd": "2026-08-01", "coed": "2026-10-26"},
                headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36",
                         "Accept": "*/*", "Accept-Encoding": "gzip, deflate"},
                timeout=(30, 200), stream=False)
            if r.status_code == 200 and len(r.text) > 100:
                return r.text
            print(f"  {sid} requests attempt{attempt+1}: status={r.status_code} len={len(r.text)}", flush=True)
        except Exception as e:
            print(f"  {sid} requests attempt{attempt+1}: {type(e).__name__}: {e}", flush=True)
        time.sleep(4)
    return None

for sid in SIDS:
    txt = None
    if requests is not None:
        txt = try_requests(sid)
    if not txt:
        # last resort: download endpoint via requests
        try:
            r = requests.get(f"https://fred.stlouisfed.org/series/{sid}/downloaddata/{sid}.csv",
                             headers={"User-Agent": "Mozilla/5.0"}, timeout=(30, 200))
            if r.status_code == 200 and len(r.text) > 100:
                txt = r.text
        except Exception as e:
            print(f"  {sid} download attempt: {type(e).__name__}: {e}", flush=True)
    if not txt:
        out[sid] = None; continue
    lines = [l for l in txt.strip().splitlines() if l]
    rows = []
    for l in lines[1:]:
        p = l.split(",")
        try: v = float(p[1])
        except Exception: continue
        rows.append((p[0], v))
    out[sid] = {"date": rows[-1][0], "value": rows[-1][1], "prev": rows[-2][1],
                "prev_date": rows[-2][0], "n": len(rows),
                "recent": [[d, v] for d, v in rows[-8:]]}
    print(sid, out[sid]["date"], out[sid]["value"], "n=", len(rows), flush=True)

if out.get("BAMLH0A0HYM2") and out.get("BAMLC0A0CM"):
    out["hy_ig_spread_bps"] = out["BAMLH0A0HYM2"]["value"] - out["BAMLC0A0CM"]["value"]
    print("HY-IG spread bps:", out["hy_ig_spread_bps"], flush=True)
else:
    out["hy_ig_spread_bps"] = None

json.dump(out, open("/root/.hermes/cron/output/_fred_alt_20261026.json", "w"), ensure_ascii=False, indent=1)
print("SAVED", flush=True)
