#!/usr/bin/env python3
"""market.py 0.1.0 (2026-11-08): market context for the article series, computed from raw filings and published holdings.
  concentration  share of S&P 500 value in the largest firms and in an AI-linked set, from index-fund holdings: iShares Core
                 S&P 500 ETF (IVV) holdings in SEC Form N-PORT (quarter ends) and the SPDR S&P 500 ETF (SPY) daily holdings file.
                 Share classes of one firm (Alphabet A and C) are merged by the 6-character CUSIP issuer code. Equity rows only.
  returns        share of the index's price return from a group: with buy-and-hold weights, a group's return over a window is
                 (1 + index return) * (group weight at end / group weight at start) - 1, and its contribution in index points
                 is weight at start * group return (an approximation: index changes and share-count changes are ignored).
  capex          capital spending (cash purchases of property and equipment) from SEC XBRL company facts, fiscal years and the
                 latest twelve months; AI revenue is recorded only where a filing states it (quotes verified verbatim).
Wording is about the record. The AI-linked set is our own choice and is labeled as such; opinions are labeled and attributed.
Usage: market.py RAW_DIR QUOTES.json --report OUT.json"""
import hashlib, html, json, os, re, sys
from datetime import date, timedelta

AI_SET = {"67066G": "NVIDIA", "594918": "Microsoft", "02079K": "Alphabet", "023135": "Amazon", "30303M": "Meta",
          "11135F": "Broadcom", "68389X": "Oracle", "007903": "AMD", "69608A": "Palantir"}
AI_SET_BROAD = dict(AI_SET, **{"037833": "Apple", "88160R": "Tesla"})
CAPEX_TAGS = ("PaymentsToAcquirePropertyPlantAndEquipment", "PaymentsToAcquireProductiveAssets")
REVENUE_TAGS = ("RevenueFromContractWithCustomerExcludingAssessedTax", "Revenues")
MONTHS = {m: i + 1 for i, m in enumerate("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split())}

def tag(block, name):
    m = re.search(r"<%s>([^<]*)</%s>" % (name, name), block)
    return m.group(1).strip() if m else None

def ident(b):
    """a holding's identifier: its CUSIP; when that is missing, "N/A" or all zeros (some foreign-domiciled firms in older
    filings), the fund's in-house CUSIP-style id, else "ISIN:" + its ISIN; None if it has none"""
    c = tag(b, "cusip")
    if c and c != "N/A" and c.strip("0"): return c
    m = re.search(r'otherDesc="Inhouse Asset ID" value="([^"]+)"', b)
    if m: return m.group(1)
    m = re.search(r'<isin value="([^"]+)"', b)
    return m and "ISIN:" + m.group(1)

def issuer(c):
    """the firm key: the 6-character CUSIP issuer code (joins share classes), or the whole ISIN id"""
    return c if c.startswith("ISIN:") else c[:6]

def nport(text):
    """(report date, {issuer: [name, value]}) for equity rows (assetCat EC) of an N-PORT primary_doc.xml"""
    d = tag(text, "repPdDate"); firms = {}
    for b in re.findall(r"<invstOrSec>(.*?)</invstOrSec>", text, re.S):
        if tag(b, "assetCat") != "EC": continue
        c = ident(b)
        if not c: continue
        f = firms.setdefault(issuer(c), [html.unescape(tag(b, "name") or ""), 0.0]); f[1] += float(tag(b, "valUSD"))
    return d, firms

def nport_prices(text):
    """{9-character CUSIP: value / shares} for equity rows: a direct price check on the weight method"""
    out = {}
    for b in re.findall(r"<invstOrSec>(.*?)</invstOrSec>", text, re.S):
        if tag(b, "assetCat") != "EC" or tag(b, "units") != "NS": continue
        c = ident(b)
        bal = float(tag(b, "balance") or 0)
        if c and bal > 0: out[c] = float(tag(b, "valUSD")) / bal
    return out

def price_return(pa, pb, issuer_):
    """price return (%) of the first share class of an issuer present at both dates; None if none (a split shows as a
    large negative number, so the report flags differences from the weight method)"""
    ks = sorted(k for k in pa if k[:6] == issuer_ and k in pb)
    return None if not ks else round((pb[ks[0]] / pa[ks[0]] - 1) * 100, 1)

def spy(rows):
    """(date, {issuer: [name, weight]}) from the SPY holdings sheet rows; rows without a 9-character identifier are skipped"""
    d = None; firms = {}
    for r in rows:
        if r and r[0] == "Holdings:" and r[1]:
            dd, mm, yy = r[1].split()[-1].split("-"); d = f"{yy}-{MONTHS[mm]:02d}-{dd}"
        elif r and len(r) > 4 and isinstance(r[4], (int, float)) and isinstance(r[2], str) and len(r[2]) == 9:
            f = firms.setdefault(r[2][:6], [r[0], 0.0]); f[1] += float(r[4])
    return d, firms

def weights(firms):
    """firm values to percent of the total"""
    t = sum(v for _, v in firms.values())
    return {k: v / t * 100 for k, (_, v) in firms.items()}

def top(w, n):
    """the n largest by weight (ties by key)"""
    return sorted(w, key=lambda k: (-w[k], k))[:n]

def concentration(firms, groups):
    w = weights(firms); top_ = top(w, len(w))
    out = dict(firms=len(w), top1=round(w[top_[0]], 2), top5=round(sum(w[k] for k in top_[:5]), 2),
               top10=round(sum(w[k] for k in top_[:10]), 2), top10_names=[firms[k][0] for k in top_[:10]])
    for g, members in groups.items(): out[g] = round(sum(w.get(k, 0) for k in members), 2)
    return out

def contribution(ws, we, r_idx):
    """group weights at start and end (%), index price return (fraction) -> the group's return and its share of the index return"""
    if ws <= 0 or r_idx is None: return None
    g = (1 + r_idx) * we / ws - 1
    pts = ws / 100 * g
    rest = None if ws >= 100 else (r_idx - pts) / (1 - ws / 100)
    return dict(weight_start=round(ws, 2), weight_end=round(we, 2), group_return_pct=round(g * 100, 1),
                index_return_pct=round(r_idx * 100, 1), contribution_pct_points=round(pts * 100, 2),
                share_of_index_return_pct=None if r_idx == 0 else round(pts / r_idx * 100, 1),
                rest_of_index_return_pct=None if rest is None else round(rest * 100, 1))

def level(series, d):
    """index level on date d, or the last one before it (holidays are blank in FRED files)"""
    ks = [k for k in series if k <= d]
    return series[max(ks)] if ks else None

def fred_daily(text):
    out = {}
    for line in text.splitlines()[1:]:
        k, _, v = line.partition(",")
        if v.strip() not in ("", "."): out[k] = float(v)
    return out

def days(a, b): return (date.fromisoformat(b) - date.fromisoformat(a)).days

def flows(facts, tags=CAPEX_TAGS):
    """USD duration facts from 10-K/10-Q as {(start, end): (value, filed)}; earlier tags win, then the latest filing"""
    out = {}
    for t in reversed(tags):
        g = facts.get("facts", {}).get("us-gaap", {}).get(t)
        if not g: continue
        pick = {}
        for x in g["units"].get("USD", []):
            if "start" in x and x.get("form") in ("10-K", "10-Q"):
                k = (x["start"], x["end"])
                if k not in pick or x["filed"] > pick[k][1]: pick[k] = (x["val"], x["filed"])
        out.update(pick)
    return out

def annual(fl):
    """{end: value} for twelve-month periods (350-380 days)"""
    return {e: v for (s, e), (v, _) in fl.items() if 350 <= days(s, e) <= 380}

def fiscal_years(a, fy_end, n=4):
    """the last n twelve-month periods that end within 7 days of the fiscal year-end date (52/53-week years drift),
    up to fy_end; quarterly trailing-twelve-month values reported in 10-Qs are left out"""
    def near(e):
        y = int(e[:4])
        return any(abs(days(e, f"{yy}{fy_end[4:]}")) <= 7 for yy in (y - 1, y, y + 1))
    return {e: a[e] for e in sorted(e for e in a if e <= fy_end and near(e))[-n:]}

def ttm(fl, fy_end):
    """latest twelve months: a reported twelve-month period ending after the last fiscal year, else fiscal year plus the
    newest year-to-date period minus the same period a year before; (end, value) or None if no newer data"""
    a = annual(fl)
    later = [e for e in a if e > fy_end]
    if later: e = max(later); return e, a[e]
    ytd = [(s, e) for (s, e) in fl if 0 < days(fy_end, s) <= 10]  # starts within 10 days after the fiscal year end
    if not ytd: return None
    s, e = max(ytd, key=lambda k: k[1]); n = days(s, e)
    prev = [(s2, e2) for (s2, e2) in fl if abs(days(s2, e2) - n) <= 7 and abs(days(e2, e) - 365) <= 10]
    if not prev or fy_end not in a: return None
    return e, a[fy_end] + fl[(s, e)][0] - fl[prev[0]][0]

def norm(text):
    t = re.sub(r"<[^>]+>", " ", text); t = html.unescape(t)
    return re.sub(r"\s+", " ", t).strip()  # \s also matches the no-break space

def verify(raw, quotes):
    """each quote must appear verbatim in the normalized text of its file"""
    cache, out = {}, []
    for q in quotes:
        if q["file"] not in cache:
            with open(os.path.join(raw, q["file"]), encoding="utf-8", errors="replace") as f: cache[q["file"]] = norm(f.read())
        out.append(dict(q, found=q["quote"] in cache[q["file"]]))
    return out

def sha(p):
    with open(p, "rb") as f: return hashlib.sha256(f.read()).hexdigest()

def read_spy(path):
    import openpyxl
    wb = openpyxl.load_workbook(path)
    return [tuple(r) for r in wb.worksheets[0].iter_rows(values_only=True)]

def report(raw, qpath):
    with open(qpath, encoding="utf-8") as f: Q = json.load(f)
    groups = dict(ai_set=AI_SET, ai_set_broad=AI_SET_BROAD)
    snaps = {}
    for fn in os.listdir(raw):
        if fn.startswith("ivv-nport-") and fn.endswith(".xml"):
            with open(os.path.join(raw, fn), encoding="utf-8") as f: text = f.read()
            d, firms = nport(text); snaps[d] = dict(source=fn, firms=firms, prices=nport_prices(text))
    d, firms = spy(read_spy(os.path.join(raw, Q["spy_file"]))); snaps[d] = dict(source=Q["spy_file"], firms=firms)
    with open(os.path.join(raw, Q["index_file"]), encoding="utf-8") as f: idx = fred_daily(f.read())
    conc = [dict(date=k, source=v["source"], **concentration(v["firms"], groups)) for k, v in sorted(snaps.items())]
    rets = []
    for a, b in Q["windows"]:
        wa, wb_ = weights(snaps[a]["firms"]), weights(snaps[b]["firms"])
        r = level(idx, b) / level(idx, a) - 1
        row = dict(start=a, end=b, index_start=level(idx, a), index_end=level(idx, b), sources=[snaps[a]["source"], snaps[b]["source"]])
        for g, members in dict(top10_at_start=top(wa, 10), **groups).items():
            members = [k for k in members if k in wa]  # firms not in the index at the start are left out
            row[g] = contribution(sum(wa[k] for k in members), sum(wb_.get(k, 0) for k in members), r)
        row["ai_set_firms"] = {AI_SET[k]: contribution(wa.get(k, 0), wb_.get(k, 0), r) for k in AI_SET}
        if "prices" in snaps[a] and "prices" in snaps[b]:
            row["direct_price_check"] = pc = {AI_SET[k]: price_return(snaps[a]["prices"], snaps[b]["prices"], k) for k in AI_SET}
            ok = [k for k in AI_SET if pc[AI_SET[k]] is not None]
            row["ai_set_direct_contribution_pct_points"] = round(sum(wa[k] / 100 * pc[AI_SET[k]] for k in ok), 2)
        rets.append(row)
    capex = {}
    for t, fy_end in Q["capex"].items():
        with open(os.path.join(raw, f"edgar-companyfacts-{t}.json"), encoding="utf-8") as f:
            facts = json.load(f)
        capex[t] = {}
        for name, tags in (("capex", CAPEX_TAGS), ("revenue", REVENUE_TAGS)):
            fl = flows(facts, tags); tt = ttm(fl, fy_end)
            capex[t][name] = dict(fiscal_years={e: round(v / 1e9, 1) for e, v in fiscal_years(annual(fl), fy_end).items()},
                                  latest_twelve_months=None if tt is None else dict(end=tt[0], usd_bn=round(tt[1] / 1e9, 1)))
    return dict(tool="tools/market.py 0.1.0", inputs={fn: sha(os.path.join(raw, fn)) for fn in sorted(os.listdir(raw))
                if fn not in ("SHA256SUMS", "METHOD.md", "fetch-log.txt")},
                ai_set_definition=dict(label="our choice (fed-words), not an index provider's", members=sorted(AI_SET.values()),
                                       broad_adds=["Apple", "Tesla"]),
                concentration=conc, returns=rets, capex_and_revenue_usd_bn=capex, quotes=verify(raw, Q["quotes"]),
                opinions=Q.get("opinions", []))

def main(argv):
    if len(argv) != 4 or argv[2] != "--report": print(__doc__, file=sys.stderr); return 2
    R = report(argv[0], argv[1])
    with open(argv[3], "w", encoding="utf-8") as f: json.dump(R, f, indent=1); f.write("\n")
    found = sum(q["found"] for q in R["quotes"])
    print(f"wrote {argv[3]}; quotes {found}/{len(R['quotes'])} verbatim")
    return 0 if found == len(R["quotes"]) else 1

if __name__ == "__main__": sys.exit(main(sys.argv[1:]))
