"""Systematic restatement audit: does using earliest-filed vs latest-filed values
change any quarter in the six-quarter grid? Latest-filed is the correct policy:
it is the company's current statement of the fact, and mixing bases across a
restatement boundary breaks comparability inside your own time series."""
from edgar import *
set_identity("Your Name your@email.com")
import pandas as pd, datetime as dt, json

T={"Apple":"AAPL","Microsoft":"MSFT","Alphabet":"GOOGL","Amazon":"AMZN",
   "Nvidia":"NVDA","Meta":"META","Tesla":"TSLA"}
CAP={"Amazon":"PaymentsToAcquireProductiveAssets","Nvidia":"PaymentsToAcquireProductiveAssets"}
DEF="PaymentsToAcquirePropertyPlantAndEquipment"
OCF="NetCashProvidedByUsedInOperatingActivities"
Q=["CY2024Q4","CY2025Q1","CY2025Q2","CY2025Q3","CY2025Q4","CY2026Q1"]

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 series(facts, concept, latest):
    df=facts.query().by_concept(concept).to_dataframe()
    df=df[df.period_type=="duration"].copy()
    df["period_start"]=pd.to_datetime(df.period_start); df["period_end"]=pd.to_datetime(df.period_end)
    df["filing_date"]=pd.to_datetime(df.filing_date)
    df["dur"]=(df.period_end-df.period_start).dt.days
    df=df.sort_values("filing_date").drop_duplicates(["period_start","period_end"],
                                                     keep="last" if latest else "first")
    df=df.sort_values("period_end")
    out={}
    for _,r in df[df.dur.between(80,100)].iterrows(): out[r.period_end.date()]=r.numeric_value
    for st,g in df.groupby("period_start"):
        prev=0.0
        for _,r in g.sort_values("period_end").iterrows():
            d=r.numeric_value-prev; prev=r.numeric_value
            if r.period_end.date() not in out and 80<=r.dur<=400: out[r.period_end.date()]=d
    return {cq(k):round(abs(v)/1e6) for k,v in out.items()}

print(f"{'Company':<10} {'Quarter':<9} {'concept':<6} {'earliest':>9} {'latest':>9} {'delta':>7}")
print("-"*60)
changed=[]; final={}
for c,tk in T.items():
    f=Company(tk).facts
    oE,oL = series(f,OCF,False), series(f,OCF,True)
    pE,pL = series(f,CAP.get(c,DEF),False), series(f,CAP.get(c,DEF),True)
    final[c]={}
    for q in Q:
        final[c][q]={"ocf":oL.get(q),"capex":pL.get(q)}
        for lbl,E,L in [("ocf",oE,oL),("capex",pE,pL)]:
            e,l=E.get(q),L.get(q)
            if e is not None and l is not None and e!=l:
                changed.append((c,q,lbl,e,l))
                print(f"{c:<10} {q:<9} {lbl:<6} {e:>9,} {l:>9,} {l-e:>+7,}")
print("-"*60)
print(f"cells affected by restatement policy: {len(changed)} of {len(T)*len(Q)*2}")
for c,q,lbl,e,l in changed: final[c][q]  # noqa
json.dump(final, open("data/restated_fcf.json","w"), indent=1)
print("wrote data/restated_fcf.json (latest-filed basis)")
