"""Test: can filings be saved to your folder as real files he can open?
Downloads run inside the sandbox and never pass through the model's context."""
from edgar import *
set_identity("Your Name your@email.com")
from pathlib import Path
import time

OUT = Path("filings"); OUT.mkdir(exist_ok=True)
TARGETS = [("AAPL","Apple"), ("AMZN","Amazon")]
log=[]

for tk,name in TARGETS:
    f = Company(tk).get_filings(form="10-Q").latest(1)
    d = OUT/f"{tk}_10Q_{f.filing_date}"; d.mkdir(exist_ok=True)
    print(f"\n=== {name} {f.form} {f.filing_date} {f.accession_no} ===")

    # 1. rendered HTML filing (the human-readable document)
    t=time.time()
    html = f.html()
    p = d/f"{tk}_10Q_filing.html"; p.write_text(html, encoding="utf-8")
    log.append((name,"rendered HTML filing",p.name,p.stat().st_size,time.time()-t)); print(f"  HTML          {p.stat().st_size:>10,} bytes  {time.time()-t:.1f}s")

    # 2. raw inline-XBRL instance document (the machine-readable source)
    t=time.time()
    inst=[a for a in f.attachments if str(a.document).endswith("_htm.xml")] or \
         [a for a in f.attachments if str(a.document).endswith(".xml") and "_cal" not in str(a.document)
          and "_def" not in str(a.document) and "_lab" not in str(a.document) and "_pre" not in str(a.document)]
    if inst:
        raw = inst[0].download()
        if isinstance(raw,bytes): raw=raw.decode("utf-8","replace")
        p = d/f"{tk}_xbrl_instance.xml"; p.write_text(raw, encoding="utf-8")
        log.append((name,"raw XBRL instance",p.name,p.stat().st_size,time.time()-t)); print(f"  XBRL instance {p.stat().st_size:>10,} bytes  {time.time()-t:.1f}s")

    # 3. the XBRL taxonomy sidecars (schema + label + calculation + presentation linkbases)
    for suffix,desc in [(".xsd","schema"),("_lab.xml","labels"),("_cal.xml","calculation"),("_pre.xml","presentation")]:
        m=[a for a in f.attachments if str(a.document).endswith(suffix)]
        if m:
            raw=m[0].download()
            if isinstance(raw,bytes): raw=raw.decode("utf-8","replace")
            p=d/f"{tk}_taxonomy{suffix if suffix.startswith('_') else '_schema.xsd'}"
            p.write_text(raw,encoding="utf-8")
            log.append((name,f"taxonomy {desc}",p.name,p.stat().st_size,0)); print(f"  {desc:<13} {p.stat().st_size:>10,} bytes")

    # 4. the cash flow statement as CSV, for spreadsheet use
    t=time.time()
    cf = f.xbrl().statements.cashflow_statement().to_dataframe()
    p = d/f"{tk}_cashflow_statement.csv"; cf.to_csv(p, index=False)
    log.append((name,"cash flow CSV",p.name,p.stat().st_size,time.time()-t)); print(f"  CF CSV        {p.stat().st_size:>10,} bytes  {time.time()-t:.1f}s")

print("\n\n=== SUMMARY ===")
tot=0
for name,kind,fn,size,el in log:
    print(f"{name:<8} {kind:<22} {fn:<38} {size:>10,} B"); tot+=size
print(f"{'':<8} {'TOTAL':<22} {'':<38} {tot:>10,} B  ({tot/1e6:.1f} MB)")
