"""Download and verify a source-linked FilingSift analyst workbook using only the standard library.""" import hashlib import json import os import pathlib import sys from urllib.request import Request, urlopen api_key = os.environ.get("FILINGSIFT_API_KEY") if not api_key: raise RuntimeError("Set FILINGSIFT_API_KEY to a live server-side API key.") base_url = os.environ.get("FILINGSIFT_API_URL", "https://api.filingsift.com/api/v1").rstrip("/") tickers = [value.strip().upper() for value in (sys.argv[1] if len(sys.argv) > 1 else "AAPL").split(",") if value.strip()] output = pathlib.Path(sys.argv[2] if len(sys.argv) > 2 else "filingsift-financing-analysis.xlsx") payload = json.dumps({"tickers": tickers, "periods": 8, "metrics": ["total_debt", "cash", "revolver_capacity", "revolver_drawn", "letters_of_credit", "revolver_availability"]}).encode() headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json", "Accept": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"} with urlopen(Request(f"{base_url}/analyst/exports/xlsx", data=payload, headers=headers, method="POST"), timeout=30) as response: workbook = response.read() expected_workbook_hash = response.headers["X-Export-Sha256"] expected_manifest_hash = response.headers["X-Manifest-Sha256"] workbook_hash = hashlib.sha256(workbook).hexdigest() if workbook_hash != expected_workbook_hash: raise RuntimeError("Workbook checksum did not match the response header.") with output.open("xb") as handle: handle.write(workbook) manifest_headers = {**headers, "Accept": "application/json"} with urlopen(Request(f"{base_url}/analyst/exports/xlsx/manifest", data=payload, headers=manifest_headers, method="POST"), timeout=30) as response: manifest = json.load(response)["data"] if manifest["manifestSha256"] != expected_manifest_hash: raise RuntimeError("Manifest checksum did not match the workbook response header.") print(json.dumps({"output": str(output), "bytes": len(workbook), "workbookSha256": workbook_hash, "manifest": manifest}, indent=2))