"""Does edgartools' own quarterize() reproduce the hand-rolled de-cumulation?
Fourth independent path over the same six-quarter grid."""
from edgar import *
set_identity("Your Name your@email.com")
from edgar.ttm.calculator import TTMCalculator
import json, datetime as dt

raw=json.load(open("data/rawapi_fcf.json")); Q=raw["quarters"]; order=raw["order"]
T={"Apple":"AAPL","Microsoft":"MSFT","Alphabet":"GOOGL","Amazon":"AMZN",
   "Nvidia":"NVDA","Meta":"META","Tesla":"TSLA"}
CAP={"Amazon":"PaymentsToAcquireProductiveAssets","Nvidia":"PaymentsToAcquireProductiveAssets"}
DEF="PaymentsToAcquirePropertyPlantAndEquipment"

def cq(d):
    y,m=d.year,d.month; best=None
    for ay,am in [(y-1,12),(y,3),(y,6),(y,9),(y,12),(y+1,3)]:
        last=dt.date(ay+(am==12),(am%12)+1,1)-dt.timedelta(days=1)
        dist=abs((d-last).days)
        if best is None or dist<best[0]: best=(dist,ay,am)
    _,ay,am=best; return f"CY{ay}Q{(am-1)//3+1}"

def qmap(facts, concept):
    fl = facts.query().by_concept(concept).execute()
    if not fl: return {}, {}
    qs = TTMCalculator(fl).quarterize()
    vals={}; qual={}
    for f in qs:
        if f.numeric_value is None: continue
        k=cq(f.period_end); vals[k]=round(abs(f.numeric_value)/1e6)
        qual[k]=str(getattr(f,"data_quality","")).replace("DataQuality.","")
    return vals, qual

print(f"{'Company':<10} {'Quarter':<9} {'mine OCF':>9} {'qtize':>9} {'':<7} {'mine cap':>9} {'qtize':>9} {'quality':>8}")
print("-"*80)
ok=0; bad=0; miss=0
for c in order:
    f=Company(T[c]).facts
    o,oq = qmap(f,"NetCashProvidedByUsedInOperatingActivities")
    p,pq = qmap(f,CAP.get(c,DEF))
    for q in Q:
        mo=raw["rows"][c][q]["ocf"]; mc=raw["rows"][c][q]["capex"]
        go=o.get(q); gc=p.get(q)
        if go is None or gc is None: miss+=1; st="MISSING"
        elif go==mo and gc==mc: ok+=1; st=""
        else: bad+=1; st="DIFF"
        print(f"{c:<10} {q:<9} {mo:>9,} {str(go):>9} {'':<7} {mc:>9,} {str(gc):>9} {oq.get(q,''):>8} {st}")
print("-"*80)
print(f"quarters: {len(order)*len(Q)}   matching: {ok}   differing: {bad}   missing: {miss}")
