"""What cash to net against debt, and why one cash tag is not enough.

This is the evidence behind /guides/cash-and-short-term-investments/. It is kept
in the repo and published so the claims on that page can be checked rather than
taken on trust. Re-run it and the JSON regenerates; if a number on the page and
a number in the JSON disagree, the JSON is right and the page is out of date.

Net debt is debt minus cash. The cash side is usually read from one tag,
CashAndCashEquivalentsAtCarryingValue. For the same 20 large filers as the
earlier guides, this script reads every cash and investment tag at the latest
annual balance-sheet date only, and records three things:

  1. filers that no longer tag CashAndCashEquivalentsAtCarryingValue at all,
     and the stale value a newest-fact pipeline would pick up instead
  2. short-term investments held outside cash and cash equivalents
  3. long-term investments, reported but never counted (a modelling choice)

Debt is the same non-overlapping path as /guides/net-debt-overlapping-debt-tags/
(rule_debt below is copied from research/net-debt-survey.py unchanged).

Usage:  python research/cash-survey.py
Writes: research/cash-survey.json
"""
import io
import json
import os
import time
import urllib.error
import urllib.request

UA = "Fairvalue Radar (privacy@fairvalueradar.com)"
HERE = os.path.dirname(os.path.abspath(__file__))
ANNUAL = ("10-K", "20-F", "40-F")

COMPANIES = [
    ("AAPL", 320193), ("MSFT", 789019), ("NVDA", 1045810), ("AMZN", 1018724),
    ("GOOGL", 1652044), ("META", 1326801), ("TSLA", 1318605), ("JPM", 19617),
    ("XOM", 34088), ("JNJ", 200406), ("WMT", 104169), ("PG", 80424),
    ("KO", 21344), ("PFE", 78003), ("INTC", 50863), ("CVX", 93410),
    ("T", 732717), ("BA", 12927), ("GE", 40545), ("MRK", 310158),
]

CASH = "CashAndCashEquivalentsAtCarryingValue"
CASH_RESTRICTED = "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents"
RESTRICTED = ["RestrictedCashAndCashEquivalentsCurrent", "RestrictedCashCurrent"]
COMBINED = "CashAndCashEquivalentsAndShortTermInvestments"
# current investment tags, in the order the rule tries them; only one is ever used
SHORT = ["ShortTermInvestments", "MarketableSecuritiesCurrent", "OtherShortTermInvestments",
         "AvailableForSaleSecuritiesDebtSecuritiesCurrent"]
LONG = ["MarketableSecuritiesNoncurrent", "AvailableForSaleSecuritiesDebtSecuritiesNoncurrent",
        "LongTermInvestments"]

DEBT_TAGS = [
    "DebtLongtermAndShorttermCombinedAmount", "LongTermDebt", "LongTermDebtNoncurrent",
    "LongTermDebtCurrent", "DebtCurrent", "ShortTermBorrowings", "CommercialPaper",
    "LongTermDebtAndCapitalLeaseObligations", "LongTermDebtAndCapitalLeaseObligationsCurrent",
]

NOT_COMPARABLE = {
    "JPM": "bank: cash and deposits with banks are operating assets, not a cushion against debt",
}


def fetch(url, tries=4):
    req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "application/json"})
    for attempt in range(tries):
        try:
            with urllib.request.urlopen(req, timeout=30) as r:
                return json.loads(r.read().decode("utf-8"))
        except urllib.error.HTTPError as e:
            if e.code == 404:
                return None
            time.sleep(1.5 * (attempt + 1))
        except Exception:
            time.sleep(1.5 * (attempt + 1))
    return None


def annual_instants(cik, tag):
    """end date -> fact, annual forms only, latest accession wins."""
    time.sleep(0.15)
    d = fetch("https://data.sec.gov/api/xbrl/companyconcept/CIK%010d/us-gaap/%s.json" % (cik, tag))
    if not d:
        return {}
    units = d.get("units", {})
    rows = units.get("USD") or next(iter(units.values()), [])
    by = {}
    for f in rows:
        if f.get("form") not in ANNUAL or not f.get("end") or f.get("start"):
            continue
        prev = by.get(f["end"])
        if not prev or f.get("accn", "") > prev.get("accn", ""):
            by[f["end"]] = f
    return by


def rule_debt(v):
    """One path through the hierarchy, never a total plus its own parts."""
    short = v.get("ShortTermBorrowings")
    if short is None:
        short = v.get("CommercialPaper")
    if v.get("DebtLongtermAndShorttermCombinedAmount") is not None:
        return v["DebtLongtermAndShorttermCombinedAmount"]
    if v.get("LongTermDebtNoncurrent") is not None and v.get("DebtCurrent") is not None:
        return v["LongTermDebtNoncurrent"] + v["DebtCurrent"]
    if v.get("LongTermDebt") is not None:
        return v["LongTermDebt"] + (short or 0)
    if v.get("LongTermDebtAndCapitalLeaseObligations") is not None and v.get("DebtCurrent") is not None:
        return v["LongTermDebtAndCapitalLeaseObligations"] + v["DebtCurrent"]
    if v.get("LongTermDebtNoncurrent") is not None:
        return v["LongTermDebtNoncurrent"] + (v.get("LongTermDebtCurrent") or 0) + (short or 0)
    if v.get("LongTermDebtAndCapitalLeaseObligations") is not None:
        return (v["LongTermDebtAndCapitalLeaseObligations"]
                + (v.get("LongTermDebtAndCapitalLeaseObligationsCurrent") or 0) + (short or 0))
    if short is not None or v.get("DebtCurrent") is not None:
        return v.get("DebtCurrent") if v.get("DebtCurrent") is not None else short
    return None


def rule_cash(v):
    """Cash at the date; if the filer stopped tagging it, the cash-flow total less restricted cash."""
    if v.get(CASH) is not None:
        return v[CASH], CASH
    if v.get(CASH_RESTRICTED) is not None:
        restricted = next((v[t] for t in RESTRICTED if v.get(t) is not None), 0)
        return v[CASH_RESTRICTED] - restricted, CASH_RESTRICTED + (" less restricted cash" if restricted else "")
    return None, None


def rule_short(v):
    """One current-investment tag, never two: they can be the same line and its own part."""
    for t in SHORT:
        if v.get(t) is not None:
            return v[t], t
    return 0, None


def main():
    out = {"readOn": time.strftime("%Y-%m-%d"),
           "source": "SEC EDGAR XBRL companyconcept, annual forms, instant facts",
           "note": "All figures in USD at the latest annual balance-sheet date (the newest annual "
                   "Assets fact). Long-term investments are reported but never counted as cash.",
           "companies": []}

    for ticker, cik in COMPANIES:
        rec = {"ticker": ticker, "cik": cik}
        if ticker in NOT_COMPARABLE:
            rec["comparable"] = False
            rec["why"] = NOT_COMPARABLE[ticker]
        assets = annual_instants(cik, "Assets")
        if not assets:
            rec["state"] = "no annual balance sheet"
            out["companies"].append(rec)
            continue
        anchor = max(assets)
        rec["balanceSheetDate"] = anchor
        rec["form"] = assets[anchor].get("form")

        at, stale = {}, {}
        for tag in [CASH, CASH_RESTRICTED, COMBINED] + RESTRICTED + SHORT + LONG + DEBT_TAGS:
            by = annual_instants(cik, tag)
            if not by:
                continue
            if anchor in by:
                at[tag] = by[anchor]["val"]
            else:
                last = max(by)
                stale[tag] = {"lastDate": last, "lastVal": by[last]["val"]}

        rec["cashTagsAtDate"] = {t: at[t] for t in [CASH, CASH_RESTRICTED, COMBINED] + RESTRICTED if t in at}
        rec["shortTermAtDate"] = {t: at[t] for t in SHORT if t in at}
        rec["longTermAtDate"] = {t: at[t] for t in LONG if t in at}
        rec["staleTags"] = {t: s for t, s in stale.items() if t not in DEBT_TAGS}
        rec["shortTermTagsAtDate"] = len(rec["shortTermAtDate"])

        cash, cash_path = rule_cash(at)
        sti, sti_tag = rule_short(at)
        if at.get(COMBINED) is not None:
            liquid, liquid_path = at[COMBINED], COMBINED
        else:
            liquid = (cash + sti) if cash is not None else None
            liquid_path = (cash_path + (" + " + sti_tag if sti_tag else "")) if cash is not None else None
        debt = rule_debt({t: at[t] for t in DEBT_TAGS if t in at})

        rec["cash"] = cash
        rec["cashPath"] = cash_path
        rec["shortTerm"] = sti
        rec["shortTermTag"] = sti_tag
        rec["liquid"] = liquid
        rec["liquidPath"] = liquid_path
        rec["debt"] = debt
        rec["netDebtCashOnly"] = (debt - at[CASH]) if debt is not None and at.get(CASH) is not None else None
        rec["netDebtRule"] = (debt - liquid) if debt is not None and liquid is not None else None
        rec["newestFactCash"] = stale.get(CASH)

        out["companies"].append(rec)
        print("%-6s %s cash=%s path=%s sti=%s(%s) liquid=%s debt=%s nd_cash=%s nd_rule=%s stale=%s" % (
            ticker, anchor, cash, cash_path, sti, sti_tag, liquid, debt,
            rec["netDebtCashOnly"], rec["netDebtRule"], stale.get(CASH)), flush=True)

    io.open(os.path.join(HERE, "cash-survey.json"), "w", encoding="utf-8").write(
        json.dumps(out, indent=1))
    print("\nwritten: research/cash-survey.json", flush=True)


if __name__ == "__main__":
    main()
