"""Follow one securities offering through its registration lifecycle.

The SEC file number (333-XXXXXX) is the join key EDGAR itself uses across one
offering: the initial S-1/F-1, each pre-effective amendment, the EFFECT notice,
and the final priced prospectus (424B1/424B4) all carry it. Filter
/v1/registrations on file_number and you get the whole thread in one call.

Plain stdlib HTTP on purpose — the endpoint works with any client.

Usage:
    export FILINGPULSE_API_KEY=fp_your_key
    python ipo_lifecycle.py                  # thread the newest registration
    python ipo_lifecycle.py 333-296288       # thread a specific offering
"""
import json
import os
import sys
import urllib.parse
import urllib.request

BASE = os.environ.get("FILINGPULSE_BASE_URL", "https://api.filingpulse.io")

STAGE_LABEL = {
    "registration": "filed",
    "amendment": "amended",
    "effectiveness": "declared effective",
    "prospectus": "priced (final prospectus)",
}


def get(path: str, **params) -> dict:
    query = urllib.parse.urlencode({k: v for k, v in params.items() if v is not None})
    req = urllib.request.Request(
        f"{BASE}{path}?{query}",
        headers={"X-API-Key": os.environ["FILINGPULSE_API_KEY"]})
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.loads(r.read())


def iso(yyyymmdd):
    d = yyyymmdd or ""
    return f"{d[:4]}-{d[4:6]}-{d[6:8]}" if len(d) == 8 else (d or "?")


def main() -> None:
    if "FILINGPULSE_API_KEY" not in os.environ:
        sys.exit("Set FILINGPULSE_API_KEY (free key: https://filingpulse.io/signup.html)")

    if len(sys.argv) > 1:
        file_number = sys.argv[1]
    else:
        newest = get("/v1/registrations", stage="registration", limit=50)["data"]
        first = next((e for e in newest if e["file_number"]), None)
        if not first:
            sys.exit("No recent registration statements with a file number.")
        file_number = first["file_number"]

    thread = get("/v1/registrations", file_number=file_number, limit=200)["data"]
    if not thread:
        sys.exit(f"No events on file {file_number}.")
    thread.sort(key=lambda e: e["filed_date"] or "")

    issuer = thread[-1]["issuer"]
    print(f"{issuer['name']} (CIK {issuer['cik']}) — file {file_number}")
    if issuer.get("sic"):
        print(f"  industry: {issuer['sic']} (SIC {issuer['sic_code']})")
    for former in thread[-1].get("former_names", []):
        print(f"  formerly: {former['name']} (until {iso(former['date_changed'])})")
    print()
    for e in thread:
        label = STAGE_LABEL.get(e["stage"], e["stage"])
        print(f"  {iso(e['filed_date'])}  {e['form_type']:<7} {label}")
    print(f"\n{len(thread)} tracked event(s). EFFECT notices for untracked form types "
          "(S-3, S-8, ...) won't appear unless they share this file number.")


if __name__ == "__main__":
    main()
