#!/usr/bin/env python3
"""Net Debt Standard v1.0 — reference implementation (US-GAAP / USD filers, SEC companyfacts).
Computes ND-A, ND-B, ND-C and the Mining/HPC profile from one balance-sheet date, with components, tags used and a quality grade.
Output: src/data/filings/net_debt.csv. Rules: src/content/standards/net-debt.md. Honest SEC user agent only (SEC_UA)."""
import os, sys, csv, json, time, urllib.request

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUT = os.path.join(ROOT, 'src/data/filings/net_debt.csv')
UA = os.environ.get('SEC_UA') or 'hashflops-research-bot'
# tag priority lists (first tag that has a value at the balance-sheet date wins; components are never summed across alternative tags)
DEBT_TOTAL = ['LongTermDebt', 'DebtLongtermAndShorttermCombinedAmount', 'ConvertibleNotesPayable', 'SeniorNotes']
DEBT_NONCUR = ['LongTermDebtNoncurrent', 'ConvertibleNotesPayableNoncurrent', 'LongTermNotesPayable', 'ConvertibleDebtNoncurrent']
DEBT_CUR = ['LongTermDebtCurrent', 'DebtCurrent', 'ConvertibleNotesPayableCurrent', 'ConvertibleDebtCurrent', 'LoansPayableCurrent']
DEBT_INSTR = ['DebtInstrumentCarryingAmount']   # v1.0.1: total of the debt note when no balance-sheet total is tagged (grade B, basis 'debt note total')
DEBT_SHORT = ['ShortTermBorrowings', 'CommercialPaper', 'LinesOfCreditCurrent']
LEASE_TOTAL = ['OperatingLeaseLiability', 'FinanceLeaseLiability']
LEASE_PARTS = [['OperatingLeaseLiabilityCurrent', 'OperatingLeaseLiabilityNoncurrent'], ['FinanceLeaseLiabilityCurrent', 'FinanceLeaseLiabilityNoncurrent']]
CASH = ['CashAndCashEquivalentsAtCarryingValue', 'Cash']
STI = ['ShortTermInvestments', 'MarketableSecuritiesCurrent', 'AvailableForSaleSecuritiesDebtSecuritiesCurrent']
CASH_RESTR_TOTAL = ['CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents']   # the 'including disposal group' variant is not used: it adds cash held for sale
RESTR = ['RestrictedCashAndCashEquivalentsAtCarryingValue', 'RestrictedCashCurrent', 'RestrictedCash']
RESTR_PARTS = [['RestrictedCashCurrent', 'RestrictedCashAndCashEquivalentsCurrent'], ['RestrictedCashNoncurrent', 'RestrictedCashAndCashEquivalentsNoncurrent']]   # current, non-current (first tag of each)
NCI = ['MinorityInterest', 'StockholdersEquityIncludingPortionAttributableToNoncontrollingInterest']
PREF = ['PreferredStockValue', 'TemporaryEquityCarryingAmountAttributableToParent']
FIELDS = ['ticker', 'status', 'bs_end', 'form', 'debt', 'debt_basis', 'leases', 'cash', 'sti', 'restricted', 'nci', 'preferred',
          'nd_a', 'nd_b', 'nd_c', 'nd_mining', 'grade', 'accn', 'cik', 'notes']

ACC = []   # (filed, accession) of every fact used; the latest filing that supplied a value is recorded

def get(url):
    for i in range(3):
        try:
            return json.load(urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent': UA, 'Accept-Encoding': 'identity'}), timeout=60))
        except Exception:
            if i == 2: return None
            time.sleep(3)

def at(cf, tags, end):
    """value of the first tag with an instant fact at exactly `end`"""
    for t in tags:
        u = cf.get('facts', {}).get('us-gaap', {}).get(t)
        if not u or 'USD' not in u['units']: continue
        v = [r for r in u['units']['USD'] if r['end'] == end and 'start' not in r]
        if v: m = max(v, key=lambda r: r.get('filed', '')); ACC.append((m.get('filed', ''), m.get('accn', ''))); return m['val'], t
    return None, None

def last_seen(cf, tags):
    """latest period end at which any of the tags was reported (to detect a component that vanished from the latest balance sheet)"""
    m = None
    for t in tags:
        u = cf.get('facts', {}).get('us-gaap', {}).get(t)
        if u and 'USD' in u['units']:
            e = [r['end'] for r in u['units']['USD'] if 'start' not in r and r.get('form') in ('10-Q', '10-K')]
            if e and (m is None or max(e) > m): m = max(e)
    return m

def latest_bs(cf):
    best = None
    for t in CASH:
        u = cf.get('facts', {}).get('us-gaap', {}).get(t)
        if not u or 'USD' not in u['units']: continue
        for r in u['units']['USD']:
            if r.get('form') in ('10-Q', '10-K') and 'start' not in r and r['end'] >= '2025-06-01':
                if best is None or r['end'] > best[0]: best = (r['end'], r['form'])
    return best

def compute(cf):
    ACC.clear()
    b = latest_bs(cf)
    if not b: return None
    end, form = b; notes = []; used = {}
    # financial debt
    d, t = at(cf, DEBT_TOTAL, end); basis = 'total'
    if d is None:
        nc, t1 = at(cf, DEBT_NONCUR, end); cu, t2 = at(cf, DEBT_CUR, end)
        if nc is not None: d = nc + (cu or 0); basis = 'noncurrent+current'; t = f'{t1}+{t2 or "none"}'
    if d is None:   # v1.0.1: the debt note total when the balance sheet tags no total (e.g. Hut 8: only per-note facts on the face)
        di, t4 = at(cf, DEBT_INSTR, end)
        if di is not None: d = di; t = t4; basis = 'debt note total'
    sb, t3 = at(cf, DEBT_SHORT, end)
    if d is not None and sb and basis != 'debt note total': d += sb; t = f'{t}+{t3}'
    elif d is None and sb is not None: d = sb; t = t3; basis = 'short-term only'
    used['debt'] = t
    # leases
    ls = 0; lt = []; found = False
    for tot, parts in zip(LEASE_TOTAL, LEASE_PARTS):
        v, tg = at(cf, [tot], end)
        if v is None:
            c1, _ = at(cf, [parts[0]], end); c2, _ = at(cf, [parts[1]], end)
            if c1 is not None or c2 is not None: v = (c1 or 0) + (c2 or 0); tg = '+'.join(parts)
        if v is not None: ls += v; lt.append(tg); found = True
    cash, _ = at(cf, CASH, end); sti, _ = at(cf, STI, end)
    tot_r, _ = at(cf, CASH_RESTR_TOTAL, end)
    # v1.0.1: restricted cash = current + non-current. First the cash-flow total minus cash (covers both), then the sum of the current
    # and non-current tags, then a single restricted tag. v1.0 took the first single tag and missed non-current restricted cash
    # (Core Scientific $636m, Cipher $477m at 30 Sep 2026).
    restr = None
    if tot_r is not None and cash is not None and tot_r >= cash: restr = tot_r - cash
    if restr is None:   # no cash-flow total: the larger of (current + non-current) and a single restricted tag (a single tag is the total for some filers, the current part for others)
        parts = [at(cf, x, end)[0] for x in RESTR_PARTS]; single, _ = at(cf, RESTR, end)
        cands = ([sum(v or 0 for v in parts)] if any(v is not None for v in parts) else []) + ([single] if single is not None else [])
        restr = max(cands) if cands else None
    nci, _ = at(cf, NCI, end); pref, _ = at(cf, PREF, end)
    if d is None or cash is None: return dict(bs_end=end, form=form, note='debt or cash tag missing at the balance-sheet date', grade='C')
    if d == 0 and not found: notes.append('no financial debt tagged')
    nd_a = d - cash - (sti or 0); nd_b = nd_a + ls; nd_c = nd_b + (nci or 0) + (pref or 0)
    nd_m = nd_a - (restr or 0)
    import datetime as dt
    age = (dt.date.today() - dt.date.fromisoformat(end)).days
    grade = 'A'
    if basis == 'debt note total': grade = 'B'; notes.append('debt from the debt-note total (DebtInstrumentCarryingAmount): no balance-sheet total tagged')
    if basis not in ('total', 'noncurrent+current', 'debt note total'): grade = 'C'
    else:
        if not found: notes.append('lease liability tags absent: ND-B equals ND-A')
        if age > 135: grade = 'B'; notes.append(f'balance sheet {age} days old')
        for nm, v, tags in (('short-term investments', sti, STI), ('lease liabilities', ls if found else None, LEASE_TOTAL + sum(LEASE_PARTS, [])), ('restricted cash', restr, RESTR + sum(RESTR_PARTS, []))):
            ls_ = last_seen(cf, tags)
            if v is None and ls_ and ls_ < end:
                grade = 'B'; notes.append(f'{nm}: tag last reported {ls_}, not at {end} - possible omission')
    if sti is None: notes.append('no short-term investment value at the date')
    if restr is None: notes.append('no restricted cash value')
    if nci is None: notes.append('no non-controlling-interest value')
    return dict(bs_end=end, form=form, debt=d, debt_basis=basis, leases=ls if found else '', cash=cash, sti=sti if sti is not None else '', restricted=restr if restr is not None else '',
                nci=nci if nci is not None else '', preferred=pref if pref is not None else '', nd_a=nd_a, nd_b=nd_b, nd_c=nd_c, nd_mining=nd_m, grade=grade, accn=max(ACC)[1] if ACC else '', note='; '.join(notes))

def main():
    cat = json.load(open(os.path.join(ROOT, 'src/data/companies.json'), encoding='utf-8'))['companies']
    only = set(a.upper() for a in sys.argv[1:])
    tk = get('https://www.sec.gov/files/company_tickers.json'); by_t = {v['ticker'].upper(): v for v in tk.values()}
    out = []
    for c in cat:
        t = c['ticker']
        if only and t.upper() not in only: continue
        row = {k: '' for k in FIELDS}; row.update(ticker=t, status='not computed')
        rec = by_t.get(t.upper())
        if not rec or c['mic'] not in ('XNAS', 'XNYS') or c.get('metric_currency', 'USD') != 'USD':
            row['notes'] = 'not a US-GAAP / USD filer in this check'; out.append(row); continue
        cf = get(f"https://data.sec.gov/api/xbrl/companyfacts/CIK{int(rec['cik_str']):010d}.json"); time.sleep(0.2)
        if not cf or 'us-gaap' not in cf.get('facts', {}): row['notes'] = 'no US-GAAP facts'; out.append(row); continue
        r = compute(cf)
        if not r: row['notes'] = 'no balance sheet in 10-Q/10-K since mid-2025'; out.append(row); continue
        row.update({k: v for k, v in r.items() if k in FIELDS}); row['cik'] = int(rec['cik_str']); row['notes'] = r.get('note', '')
        row['status'] = 'computed' if r.get('grade') != 'C' or r.get('nd_a') != None else 'incomplete'
        if 'nd_a' not in r: row['status'] = 'incomplete'
        out.append(row)
    with open(OUT if not only else OUT + '.partial', 'w', newline='', encoding='utf-8') as fh:
        w = csv.DictWriter(fh, FIELDS); w.writeheader(); w.writerows(out)
    from collections import Counter
    print(Counter(r['status'] for r in out), Counter(r['grade'] for r in out if r['status'] == 'computed'))

if __name__ == '__main__':
    main()
